Source Code
Overview
ETH Balance
0 ETH
ETH Value
$0.00
Cross-Chain Transactions
Loading...
Loading
Contract Source Code Verified (Exact Match)
Contract Name:
AvKatMorphoFlashLoanableStrategy
Compiler Version
v0.8.28+commit.7893614a
Optimization Enabled:
Yes with 50 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import {
IAvKatMorphoFlashLoanableConfigFetcher
} from "../../../../../interfaces/positions/Looping/IAvKatMorphoFlashLoanableCommons.sol";
import { AvKatMorphoFlashLoanablePreviewUtils } from "./AvKatMorphoFlashLoanablePreviewUtils.sol";
contract AvKatMorphoFlashLoanableStrategy is
IAvKatMorphoFlashLoanableConfigFetcher,
AvKatMorphoFlashLoanablePreviewUtils
{
constructor(LoopingStrategyConfig memory config, address positionManager) Ownable(msg.sender) {
_initVersionedVaultStrategyStorage(positionManager);
_setLoopingStrategyStorage(config);
}
function getLoopingFlashLoanableConfig() external view override returns (LoopingStrategyVersionedConfig memory) {
LoopingStrategyConfig memory config = _getLoopingStrategyConfig();
VaultStrategyStorage memory vaultStrategyConfig = _getVaultStrategyStorage();
return
LoopingStrategyVersionedConfig({ loopingStrategyConfig: config, vaultStrategyConfig: vaultStrategyConfig });
}
/// @dev This call will always be delegated
function setConfig(address strategy) external override onlyDelegate {
LoopingStrategyVersionedConfig memory config =
IAvKatMorphoFlashLoanableConfigFetcher(strategy).getLoopingFlashLoanableConfig();
_setVaultStrategyStorage(config.vaultStrategyConfig);
_setLoopingStrategyStorage(config.loopingStrategyConfig);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { IAuthorizedSwapRouter } from "../IAuthorizedSwapRouter.sol";
import { IVersionedVaultUtils } from "../IVaultStrategy.sol";
import { IMorphoCommons } from "../BorrowLending/IMorphoCommons.sol";
import { ILoopingFlashLoanableCommons } from "./ILoopingFlashLoanableCommons.sol";
interface IAvKatMorphoFlashLoanableCommons {
error InvalidSwapParams();
struct LoopingStrategyStorage {
IAuthorizedSwapRouter authorizedSwapRouter;
IERC4626 avKatVault;
}
struct LoopingStrategyConfig {
LoopingStrategyStorage loopingStrategyStorage;
IMorphoCommons.MorphoStrategyConfig morphoStrategyConfig;
ILoopingFlashLoanableCommons.LoopingFlashLoanableCommonStorage loopingFlashLoanableCommonStorage;
}
}
interface IAvKatMorphoFlashLoanableConfigFetcher {
struct LoopingStrategyVersionedConfig {
IAvKatMorphoFlashLoanableCommons.LoopingStrategyConfig loopingStrategyConfig;
IVersionedVaultUtils.VaultStrategyStorage vaultStrategyConfig;
}
function getLoopingFlashLoanableConfig() external view returns (LoopingStrategyVersionedConfig memory);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
import {
StandardWithdrawEstimateResult,
WithdrawAllEstimateResult
} from "../../../../../interfaces/positions/ILoopingInternals.sol";
import { AvKatMorphoFlashLoanableUtils } from "./AvKatMorphoFlashLoanableUtils.sol";
import { Constants } from "../../../../../positions/Constants.sol";
abstract contract AvKatMorphoFlashLoanablePreviewUtils is AvKatMorphoFlashLoanableUtils {
function _previewStandardWithdraw(
address user,
uint256 shares
)
internal
view
override
returns (StandardWithdrawEstimateResult memory result)
{
LoopingFlashLoanableCommonStorage memory s = _getLoopingFlashLoanableCommonStorage();
if (_getLeverage(user) == Constants.WAD) {
result.amountToBeSwapped = shares;
result.totalSharesReceivedInPrimaryDepositToken = _previewSwapCollateralToPrimaryDepositToken(shares);
result.deadline = block.timestamp + s.actionDeadline;
return result;
}
uint256 totalBorrow = borrowBalance(user);
uint256 totalCollateral = collateralBalance(user);
PreviewStandardWithdrawCalculations memory calc;
(calc.totalCollateralWithdrawn, calc.flashLoanAmount) =
_calculateWithdrawalAmountByShares(shares, totalBorrow, totalCollateral);
if (calc.totalCollateralWithdrawn > totalCollateral) revert MaxCollateralSharesExceeded();
// Convert withdrawn collateral to primary deposit token
calc.collateralWithdrawnInPrimaryDepositToken =
_previewSwapCollateralToPrimaryDepositToken(calc.totalCollateralWithdrawn);
// Remove buffer from primary deposit token withdrawn to account for potential slippage
calc.collateralWithdrawnInPrimaryDepositTokenWithBuffer =
_getSwapAmountWithBuffer(calc.collateralWithdrawnInPrimaryDepositToken);
if (calc.collateralWithdrawnInPrimaryDepositTokenWithBuffer < calc.flashLoanAmount) {
revert WithdrawalBalanceExceeded();
}
totalBorrow -= calc.flashLoanAmount;
totalCollateral -= calc.totalCollateralWithdrawn;
result.risk = _previewRiskInternal(Constants.WAD, totalCollateral, totalBorrow);
result.totalSharesReceivedInPrimaryDepositToken =
calc.collateralWithdrawnInPrimaryDepositTokenWithBuffer - calc.flashLoanAmount;
result.collateralToBePulled = calc.totalCollateralWithdrawn;
result.amountToBeSwapped = result.collateralToBePulled;
result.flashLoanAmount = calc.flashLoanAmount;
result.minAmountOut = calc.flashLoanAmount;
result.deadline = block.timestamp + s.actionDeadline;
}
function _previewWithdrawAll(address user)
internal
view
override
returns (WithdrawAllEstimateResult memory result)
{
LoopingFlashLoanableCommonStorage memory s = _getLoopingFlashLoanableCommonStorage();
uint256 actionDeadline = s.actionDeadline;
uint256 totalBorrow = borrowBalance(user);
uint256 totalCollateral = collateralBalance(user);
// repay complete borrow using flash loan and then pull out collateral to repay the flash loan
// assuming that flash loan amount is equivalent to total borrow balance
PreviewWithdrawAllCalculations memory calc = PreviewWithdrawAllCalculations({
collateralInPrimaryDepositToken: _previewSwapCollateralToPrimaryDepositToken(totalCollateral),
collateralInPrimaryDepositTokenWithBuffer: 0,
collateralInBorrowToken: 0
});
// Remove buffer from primary deposit token withdrawn to account for potential slippage
calc.collateralInPrimaryDepositTokenWithBuffer = _getSwapAmountWithBuffer(calc.collateralInPrimaryDepositToken);
if (calc.collateralInPrimaryDepositTokenWithBuffer < totalBorrow) revert InsufficientWithdrawalLiquidity();
result.totalSharesReceivedInPrimaryDepositToken = calc.collateralInPrimaryDepositTokenWithBuffer - totalBorrow;
result.amountToBeSwapped = totalCollateral;
result.flashLoanAmount = _getFlashLoanAmountWithBuffer(totalBorrow);
result.minAmountOut = totalBorrow;
result.deadline = block.timestamp + actionDeadline;
return result;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @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 v5.4.0) (interfaces/IERC4626.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
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 redemption 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: GPL-3.0
pragma solidity 0.8.28;
// @notice This interface is used to calldata from external SDKs
// verify the signature and execute the swap with the verified calldata
interface IAuthorizedSwapRouter {
struct AuthorizedSwapConfig {
address authority;
address router;
}
struct SwapNonces {
mapping(address => uint256) nonces;
}
struct SwapAuth {
address router;
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 minAmountOut;
bytes32 routeCalldataHash;
uint256 deadline;
uint256 nonce;
}
error Expired();
error CallFailed(string reason);
error InvalidSig();
error SlippageExceeded();
error NonceMismatch();
error CalldataMismatch();
error RouterMismatch();
function executeAuthorizedSwap(
SwapAuth calldata auth,
bytes calldata sig,
bytes calldata swapCallData
)
external
returns (uint256);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
import { IStrategyManager } from "./IStrategyManager.sol";
import { IVaultManager } from "./IVaultManager.sol";
interface IVaultStrategy {
// errors
error InvalidToken(address token);
error InvalidUserConfig();
error StrategyLoopingNotEnabled();
error InvalidTransactionCode(uint256 code);
// read-only functions
function version() external view returns (uint256);
function risk(address user, uint256 baseValue) external view returns (uint256);
function balance(address user) external view returns (uint256);
function balanceInUSD(address user) external view returns (uint256);
function balanceInDepositToken(address user) external view returns (uint256);
function balanceInWithdrawalToken(address user) external view returns (uint256);
function validatePreDeposit(
address user,
uint64 transactionCode,
address _tokenAddress,
uint256 _value,
IStrategyManager.StrategyConfig calldata strategyConfig,
IVaultManager.VaultStrategyConfig calldata userConfig,
bytes calldata _extras
)
external
view;
// write-only functions
/// @dev This call will always be delegated
/// @notice Called by vault to copy the strategy config to vault storage slot
function setConfig(address strategy) external;
// @dev this call will always be delegated
function deposit(
address user,
uint64 transactionCode,
address _tokenAddress,
uint256 _value,
IStrategyManager.StrategyConfig calldata strategyConfig,
IVaultManager.VaultStrategyConfig calldata userConfig,
bytes calldata _extras
)
external
payable;
// @dev this call will always be delegated
function withdraw(
address user,
uint64 transactionCode,
address _tokenAddress,
uint256 _value,
IStrategyManager.StrategyConfig calldata strategyConfig,
IVaultManager.VaultStrategyConfig calldata userConfig,
bytes calldata _extras
)
external
payable;
}
interface IVersionedVaultUtils {
struct VaultStrategyStorage {
uint256 version;
address positionManager;
}
struct CallerInfoStorage {
address self;
}
function getConfig() external view returns (VaultStrategyStorage memory);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
import { IMorpho, MarketParams } from "@morpho-blue/src/interfaces/IMorpho.sol";
import { IVersionedVaultUtils } from "../IVaultStrategy.sol";
import { IBorrowLendingUtils } from "./IBorrowLendingUtils.sol";
interface IMorphoCommons {
struct MorphoCommonsStorage {
MarketParams marketParams;
IMorpho morpho;
}
struct MorphoStrategyConfig {
MorphoCommonsStorage morphoCommons;
address priceFeed;
}
struct MorphoRepayParams {
IMorpho morpho;
MarketParams marketParams;
address borrowToken;
}
}
interface IMorphoConfigFetcher {
struct MorphoStrategyVersionedConfig {
IMorphoCommons.MorphoStrategyConfig morphoStrategyConfig;
IVersionedVaultUtils.VaultStrategyStorage vaultStrategyConfig;
}
function getMorphoCommonsConfig() external view returns (MorphoStrategyVersionedConfig memory);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
import { ILoopingUtil } from "../ILoopingUtil.sol";
import { IPriceFeed } from "../../shared/IPriceFeed.sol";
abstract contract ILoopingFlashLoanableCommons {
event InitialDeposit(
address user,
uint256 leverageInWAD,
address _tokenAddress,
uint256 value,
address _collateralAddress,
uint256 preDepositCollateral,
uint256 collateralAdded,
address _borrowAddress,
uint256 preDepositBorrow,
uint256 amountBorrowed
);
event StandardDeposit(
address user,
address _tokenAddress,
uint256 value,
address _collateralAddress,
uint256 preDepositCollateral,
uint256 collateralAdded,
address _borrowAddress,
uint256 preDepositBorrow,
uint256 amountBorrowed
);
event StandardWithdraw(
address user,
address _tokenAddress,
uint256 value,
address _collateralAddress,
uint256 preWithdrawCollateral,
address _borrowAddress,
uint256 preWithdrawBorrow,
uint256 sharesReceivedInBorrowToken,
address _primaryDepositTokenAddress,
uint256 sharesReceivedInPrimaryDepositToken
);
event WithdrawAll(
address user,
address _tokenAddress,
uint256 value,
address _collateralAddress,
uint256 preWithdrawCollateral,
address _borrowAddress,
uint256 preWithdrawBorrow,
uint256 sharesReceivedInBorrowToken,
address _primaryDepositTokenAddress,
uint256 sharesReceivedInPrimaryDepositToken
);
error DeadlineExceeded();
error SlippageExceeded();
error LeverageOutOfBounds();
error InitialDepositAlreadyMade();
error WithdrawalBalanceExceeded();
error MaxCollateralSharesExceeded();
error InsufficientWithdrawalLiquidity();
struct DepositParams {
address user;
address _tokenAddress;
uint256 _value;
uint256 _flashLoanAmount;
uint256 _leastCollateralSharesAfterSlippage;
bool isInitial;
}
struct DepositResult {
uint256 leverageInWAD;
uint256 collateralAdded;
uint256 amountBorrowed;
}
struct LoopingFlashLoanableCommonStorage {
/// @notice buffer to be applied to the amount to be swapped
uint256 amountToBeSwappedBufferInWAD;
/// @notice buffer added to the flash loan amount to ensure that the flash loan amount is sufficient to withdraw
/// all
uint256 withdrawAllBufferInWAD;
uint256 actionDeadline;
uint256 maxLeverage;
address primaryDepositToken;
ILoopingUtil loopingUtil;
IPriceFeed priceFeed;
address flashLoanCaller;
}
struct StandardWithdrawCoreParams {
address borrowToken;
address collateralToken;
address primaryDepositToken;
ILoopingUtil loopingUtil;
}
struct WithdrawAllCoreParams {
address borrowToken;
address collateralToken;
address primaryDepositToken;
ILoopingUtil loopingUtil;
}
struct WithdrawResult {
uint256 sharesReceivedInPrimaryDepositToken;
uint256 sharesReceivedInBorrowToken;
}
struct PreviewDepositCoreParams {
IPriceFeed priceFeed;
uint256 maxLeverage;
uint256 actionDeadline;
address borrowToken;
}
struct PreviewDepositCalculations {
uint256 valueInBorrowToken;
uint256 flashLoanAmount;
uint256 collateralSharesOnDeposit;
uint256 collateralSharesOnFlashLoan;
uint256 totalCollateralAdded;
}
struct DepositCoreParams {
address borrowToken;
address collateralToken;
ILoopingUtil loopingUtil;
}
struct StandardDepositBalances {
uint256 preDepositCollateral;
uint256 preDepositBorrow;
}
struct FlashLoanDepositCalculations {
uint256 primaryDepositTokenShares;
uint256 collateralShares;
uint256 initialShares;
}
struct PreviewStandardWithdrawCalculations {
uint256 totalCollateralWithdrawn;
uint256 flashLoanAmount;
uint256 collateralWithdrawnInPrimaryDepositToken;
uint256 collateralWithdrawnInPrimaryDepositTokenWithBuffer;
uint256 collateralWithdrawnInBorrowToken;
}
struct PreviewWithdrawAllCalculations {
uint256 collateralInPrimaryDepositToken;
uint256 collateralInPrimaryDepositTokenWithBuffer;
uint256 collateralInBorrowToken;
}
struct BalanceInUSDParams {
IPriceFeed priceFeed;
address collateralToken;
}
struct FlashLoanCallerParams {
address borrowToken;
address flashLoanCaller;
}
struct WithdrawalAmountCalculations {
uint256 sharesInBorrowToken;
uint256 totalCollateralInBorrowToken;
uint256 adjustedRiskRatio;
}
function _previewDepositToCollateral(
address tokenAddress,
uint256 depositAmount
)
internal
view
virtual
returns (uint256);
function _previewSwapCollateralToBorrow(uint256 shares) internal view virtual returns (uint256);
function _previewSwapPrimaryDepositTokenToBorrow(uint256 shares) internal view virtual returns (uint256);
function _previewSwapCollateralToPrimaryDepositToken(uint256 shares) internal view virtual returns (uint256);
function _previewSwapBorrowToCollateral(uint256 shares) internal view virtual returns (uint256);
function _swapDepositToCollateral(
address user,
address tokenAddress,
uint256 depositAmount,
uint256 minShares
)
internal
virtual
returns (uint256);
function _swapBorrowToPrimaryDepositToken(
address user,
uint256 shares,
uint256 minShares,
bytes memory swapCalldata
)
internal
virtual
returns (uint256);
function _swapCollateralToBorrow(
address user,
uint256 shares,
uint256 minShares,
bytes memory swapCalldata
)
internal
virtual
returns (uint256);
function _swapCollateralToPrimaryDepositToken(
address user,
uint256 shares,
uint256 minShares,
bytes memory swapCalldata
)
internal
virtual
returns (uint256);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
struct DepositActionParams {
uint256 deadline;
uint256 flashLoanAmount;
uint256 minCollateralSharesAfterSlippage;
}
struct WithdrawActionParams {
uint256 deadline;
uint256 flashLoanAmount;
uint256 collateralToBePulled;
uint256 minSharesReceivedInPrimaryDepositToken;
uint256 minSharesReceivedInBorrowToken;
}
/// @dev Preview deposit estimate
struct InitialDepositEstimateResult {
uint256 totalCollateral;
uint256 estimatedLeverage;
uint256 risk;
uint256 flashLoanAmount;
uint256 amountToBeSwapped;
uint256 lendingThreshold;
uint256 deadline;
uint64 iteration;
}
/// @dev Preview Standard deposit estimate
struct StandardDepositEstimateResult {
uint256 totalCollateralBought;
uint256 flashLoanAmount;
uint256 amountToBeSwapped;
uint256 deadline;
uint256 risk;
}
/// @dev Preview Standard withdraw estimate
struct StandardWithdrawEstimateResult {
uint256 totalSharesReceivedInPrimaryDepositToken;
uint256 totalSharesReceivedInBorrowToken;
uint256 flashLoanAmount;
uint256 amountToBeSwapped;
uint256 collateralToBePulled;
uint256 minAmountOut;
uint256 deadline;
uint256 risk;
}
/// @dev Preview Withdraw All estimate
struct WithdrawAllEstimateResult {
uint256 totalSharesReceivedInPrimaryDepositToken;
uint256 totalSharesReceivedInBorrowToken;
uint256 flashLoanAmount;
uint256 amountToBeSwapped;
uint256 minAmountOut;
uint256 deadline;
}
/// @dev Values post simulation for a given lending threshold
struct LoopedDepositPreviewResult {
uint256 totalCollateral;
uint256 totalBorrow;
uint256 lendingThreshold;
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
import { MarketParams } from "@morpho-blue/src/interfaces/IMorpho.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IPriceFeed } from "../../../../../interfaces/shared/IPriceFeed.sol";
import { IAuthorizedSwapRouter } from "../../../../../interfaces/positions/IAuthorizedSwapRouter.sol";
import { IBorrowLendingUtils } from "../../../../../interfaces/positions/BorrowLending/IBorrowLendingUtils.sol";
import { DepositActionParams } from "../../../../../interfaces/positions/ILoopingInternals.sol";
import {
IAvKatMorphoFlashLoanableCommons
} from "../../../../../interfaces/positions/Looping/IAvKatMorphoFlashLoanableCommons.sol";
import { BaseMorphoUtils } from "../../../base/BorrowLending/Morpho/BaseMorphoUtils.sol";
import {
BaseLoopingFlashLoanableCommon
} from "../../../base/Looping/LoopingFlashLoanable/BaseLoopingFlashLoanableCommon.sol";
import {
BaseLoopingFlashLoanableStrategy
} from "../../../base/Looping/LoopingFlashLoanable/BaseLoopingFlashLoanableStrategy.sol";
import { ZeroAddress } from "../../../../../utils/Helpers.sol";
abstract contract AvKatMorphoFlashLoanableUtils is
IAvKatMorphoFlashLoanableCommons,
BaseLoopingFlashLoanableStrategy,
BaseMorphoUtils
{
bytes32 constant LOOPING_STRATEGY_STORAGE_POSITION = keccak256("looping.strategy.storage")
& ~bytes32(uint256(0xff));
function _previewDepositToCollateral(
address tokenAddress,
uint256 depositAmount
)
internal
view
override
returns (uint256)
{
LoopingStrategyStorage storage l = _getLoopingStrategyStorage();
if (tokenAddress == address(l.avKatVault)) {
return depositAmount;
}
if (tokenAddress == l.avKatVault.asset()) {
return l.avKatVault.previewDeposit(depositAmount);
}
revert InvalidToken(tokenAddress);
}
function _previewSwapBorrowToCollateral(uint256 assets) internal view override returns (uint256) {
LoopingStrategyStorage storage s = _getLoopingStrategyStorage();
return s.avKatVault.previewDeposit(assets);
}
function _previewSwapCollateralToPrimaryDepositToken(uint256 shares) internal view override returns (uint256) {
return _previewSwapCollateralToBorrow(shares);
}
function _previewSwapCollateralToBorrow(uint256 shares) internal view override returns (uint256) {
LoopingStrategyStorage storage s = _getLoopingStrategyStorage();
return s.avKatVault.previewRedeem(shares);
}
/// @dev Convert Primary Deposit Token To Borrow Token Using Spot Price
function _previewSwapPrimaryDepositTokenToBorrow(uint256 shares) internal pure override returns (uint256) {
return shares;
}
function previewAvKatVaultDeposit(address _tokenAddress, uint256 _value) external view returns (uint256) {
return _previewDepositToCollateral(_tokenAddress, _value);
}
/// @dev balance in underlying
function balance(address user) external view override returns (uint256) {
LoopingFlashLoanableCommonStorage storage l = _getLoopingFlashLoanableCommonStorage();
BorrowLendingUtilStorage storage b = _getBorrowLendingStorage();
return
b.priceFeed.convertTokenBalance(b.collateralToken, l.primaryDepositToken, _balanceInCollateralToken(user));
}
/// @dev balance in underlying
function balanceInDepositToken(address user) external view override returns (uint256) {
LoopingFlashLoanableCommonStorage storage l = _getLoopingFlashLoanableCommonStorage();
BorrowLendingUtilStorage storage b = _getBorrowLendingStorage();
return
b.priceFeed.convertTokenBalance(b.collateralToken, l.primaryDepositToken, _balanceInCollateralToken(user));
}
function _validateInputForDeposit(
address _tokenAddress,
DepositActionParams memory actionParams
)
internal
view
override
{
LoopingStrategyStorage storage s = _getLoopingStrategyStorage();
if (_tokenAddress != address(s.avKatVault) && _tokenAddress != s.avKatVault.asset()) {
revert InvalidToken(_tokenAddress);
}
super._validateInputForDeposit(_tokenAddress, actionParams);
}
function _swapDepositToCollateral(
address user,
address tokenAddress,
uint256 depositAmount,
uint256 /*minShares*/
)
internal
override
returns (uint256)
{
LoopingStrategyStorage storage s = _getLoopingStrategyStorage();
if (tokenAddress == s.avKatVault.asset()) {
SafeERC20.forceApprove(IERC20(tokenAddress), address(s.avKatVault), depositAmount);
return s.avKatVault.deposit(depositAmount, user);
} else if (tokenAddress == address(s.avKatVault)) {
return depositAmount;
}
revert InvalidToken(tokenAddress);
}
function _swapCollateralToPrimaryDepositToken(
address user,
uint256 shares,
uint256 minShares,
bytes memory swapCalldata
)
internal
override
returns (uint256)
{
return _swapCollateralToBorrow(user, shares, minShares, swapCalldata);
}
function _swapBorrowToPrimaryDepositToken(
address, /*user*/
uint256 shares,
uint256, /*minShares*/
bytes memory /*swapCalldata*/
)
internal
pure
override
returns (uint256)
{
return shares;
}
function _swapCollateralToBorrow(
address, /*user*/
uint256 shares,
uint256 minShares,
bytes memory swapCalldata
)
internal
override
returns (uint256)
{
if (shares == 0) return 0;
LoopingStrategyStorage storage s = _getLoopingStrategyStorage();
IAuthorizedSwapRouter authorizedSwapRouter = s.authorizedSwapRouter;
(IAuthorizedSwapRouter.SwapAuth memory auth, bytes memory sig, bytes memory callData) =
_decodeSwapCalldata(swapCalldata);
_validateCalldataForCollateralToBorrowSwap(auth, minShares);
SafeERC20.forceApprove(IERC20(s.avKatVault), address(authorizedSwapRouter), shares);
return authorizedSwapRouter.executeAuthorizedSwap(auth, sig, callData);
}
function _decodeSwapCalldata(bytes memory swapCalldata)
private
pure
returns (IAuthorizedSwapRouter.SwapAuth memory, bytes memory, bytes memory)
{
return abi.decode(swapCalldata, (IAuthorizedSwapRouter.SwapAuth, bytes, bytes));
}
function _validateCalldataForCollateralToBorrowSwap(
IAuthorizedSwapRouter.SwapAuth memory auth,
uint256 minOutShares
)
private
view
{
LoopingStrategyStorage storage s = _getLoopingStrategyStorage();
if (auth.tokenIn != address(s.avKatVault)) revert InvalidSwapParams();
if (auth.tokenOut != s.avKatVault.asset()) revert InvalidSwapParams();
if (auth.minAmountOut < minOutShares) revert InvalidSwapParams();
}
function _setLoopingStrategyStorage(LoopingStrategyConfig memory config) internal {
_setMorphoCommonsStorage(config.morphoStrategyConfig);
_setLoopingFlashLoanableCommonStorage(config.loopingFlashLoanableCommonStorage);
LoopingStrategyStorage storage s = _getLoopingStrategyStorage();
s.authorizedSwapRouter = config.loopingStrategyStorage.authorizedSwapRouter;
s.avKatVault = config.loopingStrategyStorage.avKatVault;
}
function _getLoopingStrategyConfig() internal view returns (LoopingStrategyConfig memory) {
MorphoStrategyConfig memory morphoStrategyConfig = _getMorphoCommonsConfig();
LoopingStrategyStorage memory loopingStrategyStorage = _getLoopingStrategyStorage();
LoopingFlashLoanableCommonStorage memory loopingFlashLoanableCommonStorage =
_getLoopingFlashLoanableCommonStorage();
return LoopingStrategyConfig({
loopingStrategyStorage: loopingStrategyStorage,
loopingFlashLoanableCommonStorage: loopingFlashLoanableCommonStorage,
morphoStrategyConfig: morphoStrategyConfig
});
}
function _getLoopingStrategyStorage() internal pure returns (LoopingStrategyStorage storage s) {
bytes32 slot = LOOPING_STRATEGY_STORAGE_POSITION;
assembly {
s.slot := slot
}
}
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
library Constants {
uint64 internal constant TRANSACTION_CODE_STANDARD_DEPOSIT = 1001; // Deposit for Permissionless Strategy
uint64 internal constant TRANSACTION_CODE_LEVERAGED_DEPOSIT = 1002; // Deposit for Looping Borrow-Lending Strategy
uint64 internal constant TRANSACTION_CODE_REPAY = 1003; // Deposit for Borrow-Lending Repay Strategy
uint64 internal constant TRANSACTION_CODE_INITIAL_DEPOSIT = 1004; // Deposit at time of initial position creation
uint64 internal constant TRANSACTION_CODE_STANDARD_WITHDRAW = 2001; // Withdrawal for Permissionless Strategy
uint64 internal constant TRANSACTION_CODE_WITHDRAW_ALL = 2010; // Withdrawal all the assets (used to close
// positions)
uint64 internal constant TRANSACTION_CODE_WITHDRAW_BORROW = 2002; // Withdrawal for Borrow Lending Borrowed Token
// Deposit user's asset in flash loan callback
uint64 internal constant TRANSACTION_CODE_FLASH_LOAN_DEPOSIT = 3001;
// Withdraw user's asset in flash loan callback
uint64 internal constant TRANSACTION_CODE_FLASH_LOAN_WITHDRAW = 3002;
// Withdraw All user's asset in flash loan callback
uint64 internal constant TRANSACTION_CODE_FLASH_LOAN_WITHDRAW_ALL = 3003;
uint256 constant DOLLAR_BALANCE_PRECISION = 18;
uint256 constant WEI_DECIMALS = 18;
uint256 constant WAD = 1e18;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
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 value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` 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 value) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
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: GPL-3.0
pragma solidity 0.8.28;
interface IStrategyManager {
struct StrategyConfig {
address underlying;
address primaryDepositToken; // useful in case of swapping token to primary token for deposits
address primaryWithdrawalToken; // useful in case of swapping token to primary token for withdrawals
bool depositEnabled;
bool loopingEnabled;
}
// event
event StrategyAdded(
address strategyAddress,
address primaryDepositToken,
address primaryWithdrawalToken,
address underlying,
bool loopingEnabled
);
event StrategyRemoved(address strategyAddress);
event StrategyDepositFlagUpdated(address strategyAddress, bool flag);
event StrategyTransactionCodeUpdated(address strategyAddress, uint64 transactionCode, bool flag);
event StrategyTokenWhitelistingUpdated(address strategyAddress, address tokenAddress, uint64 purpose, bool flag);
// error
error InvalidStrategy();
error StrategyAlreadyExist(address strategy);
error StrategyDoesNotExist(address strategy);
error StrategyTokenNotWhitelisted(address strategy, address token, uint64 purpose);
// read-only function
function isDepositEnabled(address strategyAddress) external view returns (bool);
function getStrategyConfig(address strategyAddress) external view returns (StrategyConfig memory);
function assertStrategyExists(address strategyAddress) external view;
function isTransactionCodeWhitelisted(address strategyAddress, uint64 transactionCode) external view returns (bool);
function assertStrategyTokenWhitelisted(
address strategyAddress,
address tokenAddress,
uint64 purpose
)
external
view;
// write-only functions
function addStrategy(
address strategyAddress,
address primaryDepositToken,
address primaryWithdrawalToken,
address underlying,
bool loopingEnabled
)
external;
function removeStrategy(address strategyAddress) external;
function upsertDepositEnabled(address strategyAddress, bool flag) external;
function upsertTransactionCode(address strategyAddress, uint64 transactionCode, bool flag) external;
function updateTokenWhitelisting(address strategyAddress, address tokenAddress, uint64 purpose, bool flag) external;
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
interface IVaultManager {
struct VaultStrategyConfig {
address user;
address strategy;
uint64 iteration;
uint256 lendingThreshold;
bool depositEnabled;
}
// event
event VaultGlobalDepositFlagUpdated(address sender, bool flag);
event VaultDepositFlagUpdated(address vault, address sender, bool flag);
event VaultRegistered(address user, address vault, address strategy, uint256 lendingThreshold, uint64 iteration);
event VaultRegistryUpdated(address sender, address vaultRegistry);
event PositionManagerUpdated(address sender, address positionManager);
event MorphoBlueCallerUpdated(address sender, address morphoBlueCaller);
// errors
error InvalidStrategyMapping();
error VaultNotRegistered();
// read-only functions
function assertValidStrategy(address vault, address strategy) external view;
function getStrategyManager() external view returns (address);
function getPositionManager() external view returns (address);
function getVaultStrategyConfig(address vault) external view returns (VaultStrategyConfig memory);
function getDepositEnabled(address vault) external view returns (bool);
function getMorphoBlueCaller() external view returns (address);
// write-only functions
function upsertGlobalDepositFlag(bool flag) external;
function registerVault(
address user,
address vault,
address strategy,
uint256 lendingThreshold,
uint64 iteration
)
external;
function upsertDepositEnabled(address vault, bool flag) external;
}// 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 {
/// @notice The EIP-712 domain separator.
/// @dev Warning: Every EIP-712 signed message based on this domain separator can be reused on chains sharing the
/// same chain id and on forks because the domain separator would be the same.
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice The owner of the contract.
/// @dev It has the power to change the owner.
/// @dev It has the power to set fees on markets and set the fee recipient.
/// @dev It has the power to enable but not disable IRMs and LLTVs.
function owner() external view returns (address);
/// @notice The fee recipient of all markets.
/// @dev The recipient receives the fees of a given market through a supply position on that market.
function feeRecipient() external view returns (address);
/// @notice Whether the `irm` is enabled.
function isIrmEnabled(address irm) external view returns (bool);
/// @notice Whether the `lltv` is enabled.
function isLltvEnabled(uint256 lltv) external view returns (bool);
/// @notice Whether `authorized` is authorized to modify `authorizer`'s position on all markets.
/// @dev Anyone is authorized to modify their own positions, regardless of this variable.
function isAuthorized(address authorizer, address authorized) external view returns (bool);
/// @notice The `authorizer`'s current nonce. Used to prevent replay attacks with EIP-712 signatures.
function nonce(address authorizer) external view returns (uint256);
/// @notice Sets `newOwner` as `owner` of the contract.
/// @dev Warning: No two-step transfer ownership.
/// @dev Warning: The owner can be set to the zero address.
function setOwner(address newOwner) external;
/// @notice Enables `irm` as a possible IRM for market creation.
/// @dev Warning: It is not possible to disable an IRM.
function enableIrm(address irm) external;
/// @notice Enables `lltv` as a possible LLTV for market creation.
/// @dev Warning: It is not possible to disable a LLTV.
function enableLltv(uint256 lltv) external;
/// @notice Sets the `newFee` for the given market `marketParams`.
/// @param newFee The new fee, scaled by WAD.
/// @dev Warning: The recipient can be the zero address.
function setFee(MarketParams memory marketParams, uint256 newFee) external;
/// @notice Sets `newFeeRecipient` as `feeRecipient` of the fee.
/// @dev Warning: If the fee recipient is set to the zero address, fees will accrue there and will be lost.
/// @dev Modifying the fee recipient will allow the new recipient to claim any pending fees not yet accrued. To
/// ensure that the current recipient receives all due fees, accrue interest manually prior to making any changes.
function setFeeRecipient(address newFeeRecipient) external;
/// @notice Creates the market `marketParams`.
/// @dev Here is the list of assumptions on the market's dependencies (tokens, IRM and oracle) that guarantees
/// Morpho behaves as expected:
/// - The token should be ERC-20 compliant, except that it can omit return values on `transfer` and `transferFrom`.
/// - The token balance of Morpho should only decrease on `transfer` and `transferFrom`. In particular, tokens with
/// burn functions are not supported.
/// - The token should not re-enter Morpho on `transfer` nor `transferFrom`.
/// - The token balance of the sender (resp. receiver) should decrease (resp. increase) by exactly the given amount
/// on `transfer` and `transferFrom`. In particular, tokens with fees on transfer are not supported.
/// - The IRM should not re-enter Morpho.
/// - The oracle should return a price with the correct scaling.
/// - The oracle price should not be able to change instantly such that the new price is less than the old price
/// multiplied by LLTV*LIF. In particular, if the loan asset is a vault that can receive donations, the oracle
/// should not price its shares using the AUM.
/// @dev Here is a list of assumptions on the market's dependencies which, if broken, could break Morpho's liveness
/// properties (funds could get stuck):
/// - The token should not revert on `transfer` and `transferFrom` if balances and approvals are right.
/// - The amount of assets supplied and borrowed should not be too high (max ~1e32), otherwise the number of shares
/// might not fit within 128 bits.
/// - The IRM should not revert on `borrowRate`.
/// - The IRM should not return a very high borrow rate (otherwise the computation of `interest` in
/// `_accrueInterest` can overflow).
/// - The oracle should not revert `price`.
/// - The oracle should not return a very high price (otherwise the computation of `maxBorrow` in `_isHealthy` or of
/// `assetsRepaid` in `liquidate` can overflow).
/// @dev The borrow share price of a market with less than 1e4 assets borrowed can be decreased by manipulations, to
/// the point where `totalBorrowShares` is very large and borrowing overflows.
function createMarket(MarketParams memory marketParams) external;
/// @notice Supplies `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
/// `onMorphoSupply` function with the given `data`.
/// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
/// caller is guaranteed to have `assets` tokens pulled from their balance, but the possibility to mint a specific
/// amount of shares is given for full compatibility and precision.
/// @dev Supplying a large amount can revert for overflow.
/// @dev Supplying an amount of shares may lead to supply more or fewer assets than expected due to slippage.
/// Consider using the `assets` parameter to avoid this.
/// @param marketParams The market to supply assets to.
/// @param assets The amount of assets to supply.
/// @param shares The amount of shares to mint.
/// @param onBehalf The address that will own the increased supply position.
/// @param data Arbitrary data to pass to the `onMorphoSupply` callback. Pass empty data if not needed.
/// @return assetsSupplied The amount of assets supplied.
/// @return sharesSupplied The amount of shares minted.
function supply(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
bytes memory data
) external returns (uint256 assetsSupplied, uint256 sharesSupplied);
/// @notice Withdraws `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
/// @dev Either `assets` or `shares` should be zero. To withdraw max, pass the `shares`'s balance of `onBehalf`.
/// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
/// @dev Withdrawing an amount corresponding to more shares than supplied will revert for underflow.
/// @dev It is advised to use the `shares` input when withdrawing the full position to avoid reverts due to
/// conversion roundings between shares and assets.
/// @param marketParams The market to withdraw assets from.
/// @param assets The amount of assets to withdraw.
/// @param shares The amount of shares to burn.
/// @param onBehalf The address of the owner of the supply position.
/// @param receiver The address that will receive the withdrawn assets.
/// @return assetsWithdrawn The amount of assets withdrawn.
/// @return sharesWithdrawn The amount of shares burned.
function withdraw(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver
) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn);
/// @notice Borrows `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
/// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
/// caller is guaranteed to borrow `assets` of tokens, but the possibility to mint a specific amount of shares is
/// given for full compatibility and precision.
/// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
/// @dev Borrowing a large amount can revert for overflow.
/// @dev Borrowing an amount of shares may lead to borrow fewer assets than expected due to slippage.
/// Consider using the `assets` parameter to avoid this.
/// @param marketParams The market to borrow assets from.
/// @param assets The amount of assets to borrow.
/// @param shares The amount of shares to mint.
/// @param onBehalf The address that will own the increased borrow position.
/// @param receiver The address that will receive the borrowed assets.
/// @return assetsBorrowed The amount of assets borrowed.
/// @return sharesBorrowed The amount of shares minted.
function borrow(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
address receiver
) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed);
/// @notice Repays `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
/// `onMorphoRepay` function with the given `data`.
/// @dev Either `assets` or `shares` should be zero. To repay max, pass the `shares`'s balance of `onBehalf`.
/// @dev Repaying an amount corresponding to more shares than borrowed will revert for underflow.
/// @dev It is advised to use the `shares` input when repaying the full position to avoid reverts due to conversion
/// roundings between shares and assets.
/// @dev An attacker can front-run a repay with a small repay making the transaction revert for underflow.
/// @param marketParams The market to repay assets to.
/// @param assets The amount of assets to repay.
/// @param shares The amount of shares to burn.
/// @param onBehalf The address of the owner of the debt position.
/// @param data Arbitrary data to pass to the `onMorphoRepay` callback. Pass empty data if not needed.
/// @return assetsRepaid The amount of assets repaid.
/// @return sharesRepaid The amount of shares burned.
function repay(
MarketParams memory marketParams,
uint256 assets,
uint256 shares,
address onBehalf,
bytes memory data
) external returns (uint256 assetsRepaid, uint256 sharesRepaid);
/// @notice Supplies `assets` of collateral on behalf of `onBehalf`, optionally calling back the caller's
/// `onMorphoSupplyCollateral` function with the given `data`.
/// @dev Interest are not accrued since it's not required and it saves gas.
/// @dev Supplying a large amount can revert for overflow.
/// @param marketParams The market to supply collateral to.
/// @param assets The amount of collateral to supply.
/// @param onBehalf The address that will own the increased collateral position.
/// @param data Arbitrary data to pass to the `onMorphoSupplyCollateral` callback. Pass empty data if not needed.
function supplyCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, bytes memory data)
external;
/// @notice Withdraws `assets` of collateral on behalf of `onBehalf` and sends the assets to `receiver`.
/// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
/// @dev Withdrawing an amount corresponding to more collateral than supplied will revert for underflow.
/// @param marketParams The market to withdraw collateral from.
/// @param assets The amount of collateral to withdraw.
/// @param onBehalf The address of the owner of the collateral position.
/// @param receiver The address that will receive the collateral assets.
function withdrawCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, address receiver)
external;
/// @notice Liquidates the given `repaidShares` of debt asset or seize the given `seizedAssets` of collateral on the
/// given market `marketParams` of the given `borrower`'s position, optionally calling back the caller's
/// `onMorphoLiquidate` function with the given `data`.
/// @dev Either `seizedAssets` or `repaidShares` should be zero.
/// @dev Seizing more than the collateral balance will underflow and revert without any error message.
/// @dev Repaying more than the borrow balance will underflow and revert without any error message.
/// @dev An attacker can front-run a liquidation with a small repay making the transaction revert for underflow.
/// @param marketParams The market of the position.
/// @param borrower The owner of the position.
/// @param seizedAssets The amount of collateral to seize.
/// @param repaidShares The amount of shares to repay.
/// @param data Arbitrary data to pass to the `onMorphoLiquidate` callback. Pass empty data if not needed.
/// @return The amount of assets seized.
/// @return The amount of assets repaid.
function liquidate(
MarketParams memory marketParams,
address borrower,
uint256 seizedAssets,
uint256 repaidShares,
bytes memory data
) external returns (uint256, uint256);
/// @notice Executes a flash loan.
/// @dev Flash loans have access to the whole balance of the contract (the liquidity and deposited collateral of all
/// markets combined, plus donations).
/// @dev Warning: Not ERC-3156 compliant but compatibility is easily reached:
/// - `flashFee` is zero.
/// - `maxFlashLoan` is the token's balance of this contract.
/// - The receiver of `assets` is the caller.
/// @param token The token to flash loan.
/// @param assets The amount of assets to flash loan.
/// @param data Arbitrary data to pass to the `onMorphoFlashLoan` callback.
function flashLoan(address token, uint256 assets, bytes calldata data) external;
/// @notice Sets the authorization for `authorized` to manage `msg.sender`'s positions.
/// @param authorized The authorized address.
/// @param newIsAuthorized The new authorization status.
function setAuthorization(address authorized, bool newIsAuthorized) external;
/// @notice Sets the authorization for `authorization.authorized` to manage `authorization.authorizer`'s positions.
/// @dev Warning: Reverts if the signature has already been submitted.
/// @dev The signature is malleable, but it has no impact on the security here.
/// @dev The nonce is passed as argument to be able to revert with a different error message.
/// @param authorization The `Authorization` struct.
/// @param signature The signature.
function setAuthorizationWithSig(Authorization calldata authorization, Signature calldata signature) external;
/// @notice Accrues interest for the given market `marketParams`.
function accrueInterest(MarketParams memory marketParams) external;
/// @notice Returns the data stored on the different `slots`.
function extSloads(bytes32[] memory slots) external view returns (bytes32[] memory);
}
/// @dev This interface is inherited by Morpho so that function signatures are checked by the compiler.
/// @dev Consider using the IMorpho interface instead of this one.
interface IMorphoStaticTyping is IMorphoBase {
/// @notice The state of the position of `user` on the market corresponding to `id`.
/// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
/// accrual.
function position(Id id, address user)
external
view
returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral);
/// @notice The state of the market corresponding to `id`.
/// @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 accrued shares by `feeRecipient` since the last interest
/// accrual.
function market(Id id)
external
view
returns (
uint128 totalSupplyAssets,
uint128 totalSupplyShares,
uint128 totalBorrowAssets,
uint128 totalBorrowShares,
uint128 lastUpdate,
uint128 fee
);
/// @notice The market params corresponding to `id`.
/// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
/// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
function idToMarketParams(Id id)
external
view
returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv);
}
/// @title IMorpho
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @dev Use this interface for Morpho to have access to all the functions with the appropriate function signatures.
interface IMorpho is IMorphoBase {
/// @notice The state of the position of `user` on the market corresponding to `id`.
/// @dev Warning: For `feeRecipient`, `p.supplyShares` does not contain the accrued shares since the last interest
/// accrual.
function position(Id id, address user) external view returns (Position memory p);
/// @notice The state of the market corresponding to `id`.
/// @dev Warning: `m.totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `m.totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `m.totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last
/// interest accrual.
function market(Id id) external view returns (Market memory m);
/// @notice The market params corresponding to `id`.
/// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
/// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
function idToMarketParams(Id id) external view returns (MarketParams memory);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
import { IPriceFeed } from "../../shared/IPriceFeed.sol";
import { ZeroAddress } from "../../../utils/Helpers.sol";
/// @dev Borrow Lending Utils
abstract contract IBorrowLendingUtils {
bytes32 constant BORROW_LENDING_UTILS_STORAGE_POSITION =
keccak256("borrow.lending.utils.storage") & ~bytes32(uint256(0xff));
struct BorrowLendingUtilStorage {
address borrowToken;
address collateralToken;
IPriceFeed priceFeed;
}
function _riskInternal(address user, uint256 baseValue) internal view virtual returns (uint256);
/// @dev calculate TP -> borrow / collateral * 1.04
function _previewRiskInternal(
uint256 baseValue,
uint256 totalCollateral,
uint256 totalBorrow
)
internal
view
virtual
returns (uint256);
// get balance of borrowed token (with interest) (in borrowed Token)
function borrowBalance(address user) public view virtual returns (uint256);
// get balance of collateral token (in collateral Token)
function collateralBalance(address user) public view virtual returns (uint256);
/// @return updatedBorrowAmount = borrowAmount + fee
function _previewBorrow(uint256 borrowAmount) internal view virtual returns (uint256);
/// @notice Returns balance in terms of collateral token (collateral - debt)
function _balanceInCollateralToken(address user) internal view virtual returns (uint256);
/**
* @dev Use this function to add collateral or borrow amount
* @return collateralAdded - Collateral Added to Borrow Lending Pool
* @return amountBorrowed - Amount borrowed, this could be greater than debtToBorrow if fee is part of borrow
*/
function _drawDebt(
address user,
uint256 collateralToAdd,
uint256 debtToBorrow
)
internal
virtual
returns (uint256, uint256);
/**
* @dev Use this function to repay debt or pull out collateral post repayment
* @param repayReceipent - Repay remaining amount unpaid back to repayer
* @return collateralToPull - Collateral pulled out of Borrow Lending
* @return debtRepaid - Debt repaid (could be less than debtToRepay if remaining debt is less than amount
* provided)
*/
function _repayDebt(
address user,
uint256 collateralToPull,
uint256 debtToRepay,
address repayReceipent
)
internal
virtual
returns (uint256, uint256);
function _setBorrowLendingStorage(BorrowLendingUtilStorage memory config) internal virtual {
BorrowLendingUtilStorage storage s = _getBorrowLendingStorage();
if (config.borrowToken == address(0)) revert ZeroAddress();
if (config.collateralToken == address(0)) revert ZeroAddress();
if (address(config.priceFeed) == address(0)) revert ZeroAddress();
s.borrowToken = config.borrowToken;
s.collateralToken = config.collateralToken;
s.priceFeed = config.priceFeed;
}
function _getBorrowLendingStorage() internal pure virtual returns (BorrowLendingUtilStorage storage s) {
bytes32 slot = BORROW_LENDING_UTILS_STORAGE_POSITION;
assembly {
s.slot := slot
}
}
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
interface ILoopingUtil {
error WeightsAlreadyCreated();
error LoopLimitExceeded();
error ZeroValueError();
event WeightAdded(
address user,
uint64 stage,
uint256 borrowWeight,
uint256 collateralWeight,
uint256 totalBorrowWeight,
uint256 totalCollateralWeight
);
struct WeightInfo {
uint256[10] borrowWeights; // weight of borrow at each step
uint256[10] collateralWeights; // weight of collateral at each step
uint256 totalBorrowWeight; // aggregated at time of deposit and withdrawal
uint256 totalCollateralWeight; // aggregated at time of deposit and withdrawal
uint64 loop; // total loops made
}
struct TVLInfo {
uint256 totalCollateralAdded;
uint256 totalCollateralRemoved;
uint256 totalBorrowAdded;
uint256 totalBorrowRemoved;
}
struct StageInfo {
uint256 borrowWeight;
uint256 collateralWeight;
uint256 totalBorrowWeight;
uint256 totalCollateralWeight;
uint64 stage;
uint64 loop;
}
function assertWeightsCreated(address user) external view;
function getTVLInfo() external view returns (ILoopingUtil.TVLInfo memory);
function getStageInfo(address user, uint64 stage) external view returns (ILoopingUtil.StageInfo memory);
function pushWeightInfo(address user, uint256 borrowWeight, uint256 collateralWeight) external;
function onDeposit(uint256 collateralAdded, uint256 amountBorrowed) external;
function onWithdraw(uint256 collateralPulledOut, uint256 amountRepaid) external;
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
abstract contract IPriceFeed {
error TokenPairMissing();
// Gets token price in USD (WAD)
function _getTokenBalanceInUSD(address src, uint256 value) internal view virtual returns (uint256);
// Converts token src to token dst
function _convertTokenBalance(address src, address dst, uint256 value) internal view virtual returns (uint256) {
if (src == dst || value == 0) return value;
revert TokenPairMissing();
}
function getTokenBalanceInUSD(address src, uint256 value) external view returns (uint256) {
return _getTokenBalanceInUSD(src, value);
}
// Converts token src to token dst
function convertTokenBalance(address src, address dst, uint256 value) external view returns (uint256) {
return _convertTokenBalance(src, dst, value);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(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 towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* 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 {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 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 low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, 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.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
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⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// 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²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev 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) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* 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 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.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}.
*
* 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 ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both 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 returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual 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 returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual 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 `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` 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 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* 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 `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` 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.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` 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.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 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 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @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.encodeCall(token.transfer, (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.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, 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.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @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.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { IOracle } from "@morpho-blue/src/interfaces/IOracle.sol";
import { IMorpho, MarketParams, Id } from "@morpho-blue/src/interfaces/IMorpho.sol";
import { MorphoLib } from "@morpho-blue/src/libraries/periphery/MorphoLib.sol";
import { SharesMathLib } from "@morpho-blue/src/libraries/SharesMathLib.sol";
import { MarketParamsLib } from "@morpho-blue/src/libraries/MarketParamsLib.sol";
import { MorphoBalancesLib } from "@morpho-blue/src/libraries/periphery/MorphoBalancesLib.sol";
import { ORACLE_PRICE_SCALE } from "@morpho-blue/src/libraries/ConstantsLib.sol";
import { IPriceFeed } from "../../../../../interfaces/shared/IPriceFeed.sol";
import { Constants } from "../../../../../positions/Constants.sol";
import { BaseMorphoCommons } from "./BaseMorphoCommons.sol";
/// @dev Utility functions to be used by Ajna Borrow Lending strategy and Spectra Looping
abstract contract BaseMorphoUtils is BaseMorphoCommons {
using SharesMathLib for uint256;
using MorphoLib for IMorpho;
using MorphoBalancesLib for IMorpho;
using MarketParamsLib for MarketParams;
function _supplyLoanToken(
address user,
uint256 amount
)
internal
returns (uint256 assetsSupplied, uint256 sharesReceived)
{
MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
BorrowLendingUtilStorage storage b = _getBorrowLendingStorage();
IMorpho morpho = s.morpho;
IERC20 borrowToken = IERC20(b.borrowToken);
MarketParams memory params = s.marketParams;
SafeERC20.forceApprove(borrowToken, address(morpho), amount);
(assetsSupplied, sharesReceived) = morpho.supply(params, amount, 0, user, hex"");
}
/// @notice Withdraws a specified amount of loan tokens from the user's supply position
/// @dev use max amount if user wants to withdraw all shares
function _withdrawLoanToken(
address user,
uint256 amount
)
internal
returns (uint256 assetsWithdrawn, uint256 sharesBurned)
{
MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
IMorpho morpho = s.morpho;
MarketParams memory params = s.marketParams;
morpho.accrueInterest(params);
uint256 maxAmount = _supplyBalance(user);
if (amount > maxAmount) {
(assetsWithdrawn, sharesBurned) = _withdrawAllLoanToken(user);
return (assetsWithdrawn, sharesBurned);
}
(assetsWithdrawn, sharesBurned) = s.morpho.withdraw(params, amount, 0, user, user);
}
function _withdrawAllLoanToken(address user) internal returns (uint256 assetsWithdrawn, uint256 sharesBurned) {
MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
IMorpho morpho = s.morpho;
MarketParams memory params = s.marketParams;
uint256 allShares = morpho.supplyShares(params.id(), user);
(assetsWithdrawn, sharesBurned) = morpho.withdraw(params, 0, allShares, user, user);
}
/**
* @dev To be used via inheritence
*/
function _drawDebt(
address user,
uint256 collateralToAdd,
uint256 debtToBorrow
)
internal
override
returns (uint256, uint256)
{
MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
BorrowLendingUtilStorage storage b = _getBorrowLendingStorage();
IMorpho morpho = s.morpho;
MarketParams memory params = s.marketParams;
if (collateralToAdd > 0) {
ERC20 collateralToken = ERC20(b.collateralToken);
SafeERC20.forceApprove(collateralToken, address(morpho), collateralToAdd);
morpho.supplyCollateral(params, collateralToAdd, user, hex"");
}
uint256 debtBorrowed = 0;
if (debtToBorrow > 0) {
(debtBorrowed,) = morpho.borrow(params, debtToBorrow, 0, user, user);
}
return (collateralToAdd, debtBorrowed);
}
/**
* @dev To be used via inheritence
*/
function _repayDebt(
address user,
uint256 collateralToPull,
uint256 debtToRepay,
address repayRecipent
)
internal
override
returns (uint256, uint256)
{
MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
BorrowLendingUtilStorage storage b = _getBorrowLendingStorage();
MorphoRepayParams memory repayParams =
MorphoRepayParams({ morpho: s.morpho, marketParams: s.marketParams, borrowToken: b.borrowToken });
repayParams.morpho.accrueInterest(repayParams.marketParams);
uint256 debtRepaid = 0;
if (debtToRepay > 0) {
uint256 assetsMax = repayParams.morpho.expectedBorrowAssets(repayParams.marketParams, user);
if (debtToRepay >= assetsMax) {
debtRepaid = _repayAll(user, debtToRepay, repayRecipent);
} else {
SafeERC20.forceApprove(IERC20(repayParams.borrowToken), address(repayParams.morpho), debtToRepay);
(debtRepaid,) = repayParams.morpho.repay(repayParams.marketParams, debtToRepay, 0, user, hex"");
}
}
if (collateralToPull > 0) {
repayParams.morpho.withdrawCollateral(repayParams.marketParams, collateralToPull, user, user);
}
return (collateralToPull, debtRepaid);
}
/// @dev it is recommended to use borrow shares in cases where complete debt is to be paid
function _repayAll(
address user,
uint256 amount,
address repayRecipent
)
internal
override
returns (uint256 assetRepaid)
{
MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
BorrowLendingUtilStorage storage b = _getBorrowLendingStorage();
IERC20 borrowToken = IERC20(b.borrowToken);
SafeERC20.forceApprove(borrowToken, address(s.morpho), amount);
// Get Total borrow shares for user
uint256 shares = s.morpho.borrowShares(s.marketParams.id(), user);
(assetRepaid,) = s.morpho.repay(s.marketParams, 0, shares, user, hex"");
SafeERC20.forceApprove(borrowToken, address(s.morpho), 0);
if (amount > assetRepaid) {
SafeERC20.safeTransfer(borrowToken, repayRecipent, amount - assetRepaid);
}
}
function _onFlashLoan(uint256 assets, bytes memory data) internal override {
MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
BorrowLendingUtilStorage storage b = _getBorrowLendingStorage();
IMorpho morpho = s.morpho;
address borrowToken = b.borrowToken;
morpho.flashLoan(borrowToken, assets, data);
}
// get balance of borrowed token (with interest) (in borrowed Token)
function borrowBalance(address user) public view override returns (uint256) {
MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
IMorpho morpho = s.morpho;
MarketParams memory params = s.marketParams;
uint256 accuredBorrow = morpho.expectedBorrowAssets(params, user);
return accuredBorrow;
}
function _supplyBalance(address user) internal view returns (uint256) {
MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
IMorpho morpho = s.morpho;
MarketParams memory params = s.marketParams;
return morpho.expectedSupplyAssets(params, user);
}
function _withdrawableSupplyBalance(address user) internal view returns (uint256) {
MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
IMorpho morpho = s.morpho;
MarketParams memory params = s.marketParams;
uint256 totalBorrow = morpho.totalBorrowAssets(params.id());
uint256 totalSupply = morpho.totalSupplyAssets(params.id());
uint256 supplyBalance = morpho.expectedSupplyAssets(params, user);
uint256 withdrawableSupply = totalSupply - totalBorrow;
return Math.min(withdrawableSupply, supplyBalance);
}
// get balance of collateral token (in collateral Token)
function collateralBalance(address user) public view override returns (uint256) {
MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
IMorpho morpho = s.morpho;
MarketParams memory params = s.marketParams;
return morpho.collateral(params.id(), user);
}
function _riskInternal(address user, uint256 baseValue) internal view override returns (uint256) {
MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
IMorpho morpho = s.morpho;
MarketParams memory params = s.marketParams;
uint256 collateralPrice = IOracle(params.oracle).price();
uint256 collateral = morpho.collateral(params.id(), user);
uint256 borrowed = morpho.expectedBorrowAssets(params, user);
uint256 maxBorrowUncapped = Math.mulDiv(collateral, collateralPrice, ORACLE_PRICE_SCALE);
uint256 maxBorrow = Math.mulDiv(maxBorrowUncapped, params.lltv, Constants.WAD);
return Math.mulDiv(borrowed, baseValue, maxBorrow);
}
/// @dev calculate TP -> borrow / collateral * 1.04
function _previewRiskInternal(
uint256 baseValue,
uint256 totalCollateral,
uint256 totalBorrow
)
internal
view
override
returns (uint256)
{
MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
MarketParams memory params = s.marketParams;
IOracle oracle = IOracle(params.oracle);
uint256 collateralPrice = oracle.price();
uint256 maxBorrowUncapped = Math.mulDiv(totalCollateral, collateralPrice, ORACLE_PRICE_SCALE);
uint256 maxBorrow = Math.mulDiv(maxBorrowUncapped, params.lltv, Constants.WAD);
return Math.mulDiv(totalBorrow, baseValue, maxBorrow);
}
/// @return updatedBorrowAmount = borrowAmount + originationFee
function _previewBorrow(uint256 borrowAmount) internal pure override returns (uint256) {
return borrowAmount;
}
function _balanceInCollateralToken(address user) internal view override returns (uint256) {
BorrowLendingUtilStorage storage b = _getBorrowLendingStorage();
IPriceFeed priceFeed = b.priceFeed;
address collateralToken = b.collateralToken;
address borrowToken = b.borrowToken;
uint256 cBalance = collateralBalance(user);
uint256 bBalance = borrowBalance(user);
uint256 bBalanceInCollateralToken = priceFeed.convertTokenBalance(borrowToken, collateralToken, bBalance);
return cBalance > bBalanceInCollateralToken ? cBalance - bBalanceInCollateralToken : 0;
}
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IPriceFeed } from "../../../../../interfaces/shared/IPriceFeed.sol";
import { ILoopingUtil } from "../../../../../interfaces/positions/ILoopingUtil.sol";
import { IFlashLoanUtils } from "../../../../../interfaces/positions/BorrowLending/IFlashLoanUtils.sol";
import {
ILoopingFlashLoanableCommons
} from "../../../../../interfaces/positions/Looping/ILoopingFlashLoanableCommons.sol";
import { Constants } from "../../../../../positions/Constants.sol";
import { PermissionDenied, DivideByZeroError, ZeroAddress } from "../../../../../utils/Helpers.sol";
abstract contract BaseLoopingFlashLoanableCommon is ILoopingFlashLoanableCommons, IFlashLoanUtils {
bytes32 constant LOOPING_FLASH_LOANABLE_COMMON_STORAGE_POSITION =
keccak256("looping.flash.loanable.common.storage") & ~bytes32(uint256(0xff));
uint64 constant INITIAL_DEPOSIT_STAGE = 0;
modifier onlyFlashLoanCaller() {
LoopingFlashLoanableCommonStorage storage s = _getLoopingFlashLoanableCommonStorage();
if (s.flashLoanCaller != msg.sender) revert PermissionDenied();
_;
}
/// @notice get current user leverage in WAD
function _getLeverage(address user) internal view returns (uint256) {
LoopingFlashLoanableCommonStorage storage s = _getLoopingFlashLoanableCommonStorage();
ILoopingUtil loopingUtil = s.loopingUtil;
ILoopingUtil.StageInfo memory stageInfo = loopingUtil.getStageInfo(user, INITIAL_DEPOSIT_STAGE);
require(stageInfo.collateralWeight != 0, DivideByZeroError());
return Math.mulDiv(stageInfo.totalCollateralWeight, Constants.WAD, stageInfo.collateralWeight);
}
/// @dev Use this function to calculate how much amount needs to borrowed using flash loan
/// so that `_shares` amount of collateral can be withdrawn from portfolio without affecting the risk
function _calculateWithdrawalAmountByShares(
uint256 _shares,
uint256 totalBorrow,
uint256 totalCollateral
)
internal
view
returns (uint256 collateralToBePulled, uint256 flashLoanAmount)
{
require(_shares != 0, DivideByZeroError());
WithdrawalAmountCalculations memory calc = WithdrawalAmountCalculations({
sharesInBorrowToken: _previewSwapCollateralToBorrow(_shares),
totalCollateralInBorrowToken: _previewSwapCollateralToBorrow(totalCollateral),
adjustedRiskRatio: 0
});
require(calc.totalCollateralInBorrowToken != 0, DivideByZeroError());
// Use this value to calculate adjusted risk ratio
calc.adjustedRiskRatio = Math.mulDiv(totalBorrow, Constants.WAD, calc.totalCollateralInBorrowToken);
require(calc.adjustedRiskRatio < Constants.WAD, "Risk Ratio exceeds 1");
// flashLoanAmount = sharesInBorrowToken * adjustedRisk / (1 - adjustedRisk)
flashLoanAmount =
Math.mulDiv(calc.sharesInBorrowToken, calc.adjustedRiskRatio, Constants.WAD - calc.adjustedRiskRatio);
// Swap flash loan amount to collateral token
collateralToBePulled = _shares + _previewSwapBorrowToCollateral(flashLoanAmount);
// If flash loan amount exceed total borrow this implies user is withdrawing more shares than existing balance
if (flashLoanAmount > totalBorrow) revert WithdrawalBalanceExceeded();
if (collateralToBePulled > totalCollateral) revert MaxCollateralSharesExceeded();
}
/// @notice buffer to be applied to the amount to be swapped
/// @dev The amount to be swapped will be received after selling the PT to get primary deposit token.
/// @dev Hence we will keep the amount to be swapped lower than the amount previewed, to account for the slippage on
/// @dev PT -> primary deposit token.
function _getSwapAmountWithBuffer(uint256 amount) internal view returns (uint256) {
LoopingFlashLoanableCommonStorage storage s = _getLoopingFlashLoanableCommonStorage();
return Math.mulDiv(amount, Constants.WAD - s.amountToBeSwappedBufferInWAD, Constants.WAD);
}
/// @notice buffer to be applied to the flash loan amount
/// @dev The flash loan amount will be used to repay the borrow.
/// @dev Since the position can accure some debt at time of repayment, we will add some buffer to cover for that.
function _getFlashLoanAmountWithBuffer(uint256 amount) internal view returns (uint256) {
LoopingFlashLoanableCommonStorage storage s = _getLoopingFlashLoanableCommonStorage();
return Math.mulDiv(amount, Constants.WAD + s.withdrawAllBufferInWAD, Constants.WAD);
}
function _setLoopingFlashLoanableCommonStorage(LoopingFlashLoanableCommonStorage memory config) internal {
if (config.maxLeverage < Constants.WAD) revert LeverageOutOfBounds();
if (config.primaryDepositToken == address(0)) revert ZeroAddress();
if (config.flashLoanCaller == address(0)) revert ZeroAddress();
if (address(config.priceFeed) == address(0)) revert ZeroAddress();
if (address(config.loopingUtil) == address(0)) revert ZeroAddress();
LoopingFlashLoanableCommonStorage storage s = _getLoopingFlashLoanableCommonStorage();
s.amountToBeSwappedBufferInWAD = config.amountToBeSwappedBufferInWAD;
s.withdrawAllBufferInWAD = config.withdrawAllBufferInWAD;
s.actionDeadline = config.actionDeadline;
s.maxLeverage = config.maxLeverage;
s.primaryDepositToken = config.primaryDepositToken;
s.flashLoanCaller = config.flashLoanCaller;
s.loopingUtil = config.loopingUtil;
s.priceFeed = config.priceFeed;
}
function _getLoopingFlashLoanableCommonStorage()
internal
pure
returns (LoopingFlashLoanableCommonStorage storage s)
{
bytes32 slot = LOOPING_FLASH_LOANABLE_COMMON_STORAGE_POSITION;
assembly {
s.slot := slot
}
}
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {
InitialDepositEstimateResult,
StandardDepositEstimateResult,
StandardWithdrawEstimateResult,
WithdrawAllEstimateResult,
DepositActionParams,
WithdrawActionParams
} from "../../../../../interfaces/positions/ILoopingInternals.sol";
import { IVaultManager } from "../../../../../interfaces/positions/IVaultManager.sol";
import { IVaultStrategy } from "../../../../../interfaces/positions/IVaultStrategy.sol";
import { IStrategyManager } from "../../../../../interfaces/positions/IStrategyManager.sol";
import { Constants } from "../../../../../positions/Constants.sol";
import { VersionedVaultUtils } from "../../../base/VersionedVaultUtils.sol";
import { BaseLoopingFlashLoanableUtils } from "./BaseLoopingFlashLoanableUtils.sol";
abstract contract BaseLoopingFlashLoanableStrategy is
VersionedVaultUtils,
BaseLoopingFlashLoanableUtils,
IVaultStrategy
{
/// =========================== View Functions ==============================================
function version() external view override returns (uint256) {
return _getVaultStrategyStorage().version;
}
/// @notice Used to preview total PT shares bought by the user and risk taken
/// @dev This function should be called by static call or in simulated fashion
/// @param _tokenAddress address of input token (hemiBTC, bfBTC)
/// @param _value value of deposit token
/// @param _leverage target leverage user wants to achieve
/// @dev The remaining two parameters are for internal use and not to be shown by the user
/// @return InitialDepositEstimateResult -> (totalCollateral, estimatedLeverage, risk, lendingThreshold, iterations)
function previewInitialDeposit(
address _tokenAddress,
uint256 _value,
uint256 _leverage
)
external
view
virtual
returns (InitialDepositEstimateResult memory)
{
return _previewInitialDeposit(_tokenAddress, _value, _leverage);
}
/// @notice Used to preview total PT shares bought by the user and risk taken
/// @dev This function should be called by static call or in simulated fashion
/// @param _tokenAddress address of input token (hemiBTC, bfBTC)
/// @param _value value of deposit token
/// @return StandardDepositEstimateResult -> (totalCollateralBought, risk)
function previewStandardDeposit(
address user,
address _tokenAddress,
uint256 _value
)
external
view
virtual
returns (StandardDepositEstimateResult memory)
{
return _previewStandardDeposit(user, _tokenAddress, _value);
}
/// @notice Used to preview total IBT shares received by the user and risk
/// @dev This function should be called by static call or in simulated fashion
/// @param _shares withdrawn by the user
/// @return StandardWithdrawEstimateResult -> (totalIBTReceived, risk)
function previewStandardWithdraw(
address user,
uint256 _shares
)
external
view
virtual
returns (StandardWithdrawEstimateResult memory)
{
return _previewStandardWithdraw(user, _shares);
}
/// @notice Used to preview max IBT shares received by the user
/// @dev This function should be called by static call or in simulated fashion
function previewWithdrawAll(address user) external view virtual returns (WithdrawAllEstimateResult memory) {
return _previewWithdrawAll(user);
}
function encodeConfigForDeposit(
DepositActionParams memory actionParams,
bytes calldata swapCalldata
)
external
pure
returns (bytes memory)
{
return abi.encode(actionParams, swapCalldata);
}
function encodeConfigForWithdraw(
WithdrawActionParams memory actionParams,
bytes calldata swapCalldata
)
external
pure
returns (bytes memory)
{
return abi.encode(actionParams, swapCalldata);
}
// read-only functions
function risk(address user, uint256 baseValue) external view returns (uint256) {
return _riskInternal(user, baseValue);
}
/// @return lev in WAD
function leverage(address user) external view returns (uint256) {
return _getLeverage(user);
}
function balanceInUSD(address user) external view override returns (uint256) {
BorrowLendingUtilStorage memory b = _getBorrowLendingStorage();
LoopingFlashLoanableCommonStorage memory s = _getLoopingFlashLoanableCommonStorage();
BalanceInUSDParams memory params =
BalanceInUSDParams({ priceFeed: s.priceFeed, collateralToken: b.collateralToken });
return params.priceFeed.getTokenBalanceInUSD(params.collateralToken, _balanceInCollateralToken(user));
}
// Withdrawal Token - PT
function balanceInWithdrawalToken(address user) external view override returns (uint256) {
return _balanceInWithdrawalToken(user);
}
function validatePreDeposit(
address, /*user*/
uint64, /*transactionCode*/
address _tokenAddress,
uint256,
/*value*/ // value in terms of underlying / IBT token.
IStrategyManager.StrategyConfig calldata, /*strategyConfig*/
IVaultManager.VaultStrategyConfig calldata, /*userConfig*/
bytes calldata _extras
)
external
view
virtual
{
(DepositActionParams memory actionParams,) = _decodeConfigForDeposit(_extras);
_validateInputForDeposit(_tokenAddress, actionParams);
}
/// =========================== Write Functions =============================================
/// @dev this call will always be delegated
function deposit(
address user,
uint64 transactionCode,
address _tokenAddress,
uint256 _value,
IStrategyManager.StrategyConfig calldata, /*strategyConfig*/
IVaultManager.VaultStrategyConfig calldata, /*userConfig*/
bytes calldata _extras
)
external
payable
override
onlyPositionManager
{
(DepositActionParams memory actionParams, bytes memory swapCalldata) = _decodeConfigForDeposit(_extras);
_validateInputForDeposit(_tokenAddress, actionParams);
if (transactionCode == Constants.TRANSACTION_CODE_INITIAL_DEPOSIT) {
return _initialDeposit(user, _tokenAddress, _value, actionParams, swapCalldata);
} else if (transactionCode == Constants.TRANSACTION_CODE_STANDARD_DEPOSIT) {
return _standardDeposit(user, _tokenAddress, _value, actionParams, swapCalldata);
}
revert InvalidTransactionCode(transactionCode);
}
/// @dev this call will always be delegated
function withdraw(
address user,
uint64 transactionCode,
address _tokenAddress,
uint256 _value,
IStrategyManager.StrategyConfig calldata, /*strategyConfig*/
IVaultManager.VaultStrategyConfig calldata userConfig,
bytes calldata _extras
)
external
payable
override
onlyPositionManager
{
(WithdrawActionParams memory actionParams, bytes memory swapCalldata) = _decodeConfigForWithdrawal(_extras);
_validateInputForWithdrawal(_tokenAddress, actionParams);
if (transactionCode == Constants.TRANSACTION_CODE_STANDARD_WITHDRAW) {
return _standardWithdraw(user, _value, userConfig, actionParams, swapCalldata);
} else if (transactionCode == Constants.TRANSACTION_CODE_WITHDRAW_ALL) {
return _withdrawAll(user, userConfig, actionParams, swapCalldata);
}
revert InvalidTransactionCode(transactionCode);
}
function onFlashLoan(
address user,
uint64 transactionCode,
address _tokenAddress,
uint256 _value,
uint256 flashLoanAmount,
bytes calldata _extras
)
external
payable
onlyFlashLoanCaller
{
LoopingFlashLoanableCommonStorage memory s = _getLoopingFlashLoanableCommonStorage();
BorrowLendingUtilStorage storage b = _getBorrowLendingStorage();
FlashLoanCallerParams memory params =
FlashLoanCallerParams({ borrowToken: b.borrowToken, flashLoanCaller: s.flashLoanCaller });
if (transactionCode == Constants.TRANSACTION_CODE_FLASH_LOAN_DEPOSIT) {
(bool isInitial, bytes memory swapCalldata) = _decodeConfigForFlashLoanDeposit(_extras);
_onFlashLoanForDeposit(user, flashLoanAmount, _tokenAddress, _value, swapCalldata, isInitial);
} else if (transactionCode == Constants.TRANSACTION_CODE_FLASH_LOAN_WITHDRAW) {
(bytes memory swapCalldata) = _decodeConfigForFlashLoanWithdrawal(_extras);
_onFlashLoanForStandardWithdrawal(user, _value, flashLoanAmount, swapCalldata);
} else if (transactionCode == Constants.TRANSACTION_CODE_FLASH_LOAN_WITHDRAW_ALL) {
(bytes memory swapCalldata) = _decodeConfigForFlashLoanWithdrawal(_extras);
_onFlashLoanForWithdrawAll(user, flashLoanAmount, swapCalldata);
} else {
revert InvalidTransactionCode(transactionCode);
}
SafeERC20.forceApprove(ERC20(params.borrowToken), params.flashLoanCaller, flashLoanAmount);
}
function _validateInputForDeposit(
address, /*_tokenAddress*/
DepositActionParams memory actionParams
)
internal
view
virtual
{
if (actionParams.deadline < block.timestamp) revert DeadlineExceeded();
}
function _validateInputForWithdrawal(
address _tokenAddress,
WithdrawActionParams memory actionParams
)
internal
view
{
BorrowLendingUtilStorage storage b = _getBorrowLendingStorage();
address collateralToken = b.collateralToken;
if (_tokenAddress != collateralToken) revert InvalidToken(_tokenAddress);
if (actionParams.deadline < block.timestamp) revert DeadlineExceeded();
}
function _decodeConfigForFlashLoanDeposit(bytes calldata _extras) private pure returns (bool, bytes memory) {
return abi.decode(_extras, (bool, bytes));
}
function _decodeConfigForFlashLoanWithdrawal(bytes calldata _extras) private pure returns (bytes memory) {
return abi.decode(_extras, (bytes));
}
function _decodeConfigForDeposit(bytes calldata _extras)
private
pure
returns (DepositActionParams memory, bytes memory)
{
return abi.decode(_extras, (DepositActionParams, bytes));
}
function _decodeConfigForWithdrawal(bytes calldata _extras)
private
pure
returns (WithdrawActionParams memory, bytes memory)
{
return abi.decode(_extras, (WithdrawActionParams, bytes));
}
}// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.28; // common errors error IncorrectTypeID(uint256 _typeId, address _sender); error NegativePriceError(); error PriceStaleError(); error CallFailed(); error NotDepositContract(address _address); error NotExecutor(address _address); error NotStrategyContract(address _address); error IncorrectTokenAddress(address _tokenAddress); error IncorrectValue(); error IncorrectMessageAddress(address _sender); error ZeroAddress(); error ZeroAmount(); error ZeroValue(); error MinimumDustAmountError(); error NonPayableFunction(); error DivideByZeroError(); error PermissionDenied(); error InvalidLendingThreshold(); error NotImplemented(); // common events //deposit events //deposit
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title IOracle /// @author Morpho Labs /// @custom:contact [email protected] /// @notice Interface that oracles used by Morpho must implement. /// @dev It is the user's responsibility to select markets with safe oracles. interface IOracle { /// @notice Returns the price of 1 asset of collateral token quoted in 1 asset of loan token, scaled by 1e36. /// @dev It corresponds to the price of 10**(collateral token decimals) assets of collateral token quoted in /// 10**(loan token decimals) assets of loan token with `36 + loan token decimals - collateral token decimals` /// decimals of precision. function price() external view returns (uint256); }
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {IMorpho, Id} from "../../interfaces/IMorpho.sol";
import {MorphoStorageLib} from "./MorphoStorageLib.sol";
/// @title MorphoLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Helper library to access Morpho storage variables.
/// @dev Warning: Supply and borrow getters may return outdated values that do not include accrued interest.
library MorphoLib {
function supplyShares(IMorpho morpho, Id id, address user) internal view returns (uint256) {
bytes32[] memory slot = _array(MorphoStorageLib.positionSupplySharesSlot(id, user));
return uint256(morpho.extSloads(slot)[0]);
}
function borrowShares(IMorpho morpho, Id id, address user) internal view returns (uint256) {
bytes32[] memory slot = _array(MorphoStorageLib.positionBorrowSharesAndCollateralSlot(id, user));
return uint128(uint256(morpho.extSloads(slot)[0]));
}
function collateral(IMorpho morpho, Id id, address user) internal view returns (uint256) {
bytes32[] memory slot = _array(MorphoStorageLib.positionBorrowSharesAndCollateralSlot(id, user));
return uint256(morpho.extSloads(slot)[0] >> 128);
}
function totalSupplyAssets(IMorpho morpho, Id id) internal view returns (uint256) {
bytes32[] memory slot = _array(MorphoStorageLib.marketTotalSupplyAssetsAndSharesSlot(id));
return uint128(uint256(morpho.extSloads(slot)[0]));
}
function totalSupplyShares(IMorpho morpho, Id id) internal view returns (uint256) {
bytes32[] memory slot = _array(MorphoStorageLib.marketTotalSupplyAssetsAndSharesSlot(id));
return uint256(morpho.extSloads(slot)[0] >> 128);
}
function totalBorrowAssets(IMorpho morpho, Id id) internal view returns (uint256) {
bytes32[] memory slot = _array(MorphoStorageLib.marketTotalBorrowAssetsAndSharesSlot(id));
return uint128(uint256(morpho.extSloads(slot)[0]));
}
function totalBorrowShares(IMorpho morpho, Id id) internal view returns (uint256) {
bytes32[] memory slot = _array(MorphoStorageLib.marketTotalBorrowAssetsAndSharesSlot(id));
return uint256(morpho.extSloads(slot)[0] >> 128);
}
function lastUpdate(IMorpho morpho, Id id) internal view returns (uint256) {
bytes32[] memory slot = _array(MorphoStorageLib.marketLastUpdateAndFeeSlot(id));
return uint128(uint256(morpho.extSloads(slot)[0]));
}
function fee(IMorpho morpho, Id id) internal view returns (uint256) {
bytes32[] memory slot = _array(MorphoStorageLib.marketLastUpdateAndFeeSlot(id));
return uint256(morpho.extSloads(slot)[0] >> 128);
}
function _array(bytes32 x) private pure returns (bytes32[] memory) {
bytes32[] memory res = new bytes32[](1);
res[0] = x;
return res;
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {MathLib} from "./MathLib.sol";
/// @title SharesMathLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Shares management library.
/// @dev This implementation mitigates share price manipulations, using OpenZeppelin's method of virtual shares:
/// https://docs.openzeppelin.com/contracts/4.x/erc4626#inflation-attack.
library SharesMathLib {
using MathLib for uint256;
/// @dev The number of virtual shares has been chosen low enough to prevent overflows, and high enough to ensure
/// high precision computations.
/// @dev Virtual shares can never be redeemed for the assets they are entitled to, but it is assumed the share price
/// stays low enough not to inflate these assets to a significant value.
/// @dev Warning: The assets to which virtual borrow shares are entitled behave like unrealizable bad debt.
uint256 internal constant VIRTUAL_SHARES = 1e6;
/// @dev A number of virtual assets of 1 enforces a conversion rate between shares and assets when a market is
/// empty.
uint256 internal constant VIRTUAL_ASSETS = 1;
/// @dev Calculates the value of `assets` quoted in shares, rounding down.
function toSharesDown(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return assets.mulDivDown(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
}
/// @dev Calculates the value of `shares` quoted in assets, rounding down.
function toAssetsDown(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return shares.mulDivDown(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
}
/// @dev Calculates the value of `assets` quoted in shares, rounding up.
function toSharesUp(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return assets.mulDivUp(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
}
/// @dev Calculates the value of `shares` quoted in assets, rounding up.
function toAssetsUp(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
return shares.mulDivUp(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {Id, MarketParams} from "../interfaces/IMorpho.sol";
/// @title MarketParamsLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Library to convert a market to its id.
library MarketParamsLib {
/// @notice The length of the data used to compute the id of a market.
/// @dev The length is 5 * 32 because `MarketParams` has 5 variables of 32 bytes each.
uint256 internal constant MARKET_PARAMS_BYTES_LENGTH = 5 * 32;
/// @notice Returns the id of the market `marketParams`.
function id(MarketParams memory marketParams) internal pure returns (Id marketParamsId) {
assembly ("memory-safe") {
marketParamsId := keccak256(marketParams, MARKET_PARAMS_BYTES_LENGTH)
}
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {Id, MarketParams, Market, IMorpho} from "../../interfaces/IMorpho.sol";
import {IIrm} from "../../interfaces/IIrm.sol";
import {MathLib} from "../MathLib.sol";
import {UtilsLib} from "../UtilsLib.sol";
import {MorphoLib} from "./MorphoLib.sol";
import {SharesMathLib} from "../SharesMathLib.sol";
import {MarketParamsLib} from "../MarketParamsLib.sol";
/// @title MorphoBalancesLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Helper library exposing getters with the expected value after interest accrual.
/// @dev This library is not used in Morpho itself and is intended to be used by integrators.
/// @dev The getter to retrieve the expected total borrow shares is not exposed because interest accrual does not apply
/// to it. The value can be queried directly on Morpho using `totalBorrowShares`.
library MorphoBalancesLib {
using MathLib for uint256;
using MathLib for uint128;
using UtilsLib for uint256;
using MorphoLib for IMorpho;
using SharesMathLib for uint256;
using MarketParamsLib for MarketParams;
/// @notice Returns the expected market balances of a market after having accrued interest.
/// @return The expected total supply assets.
/// @return The expected total supply shares.
/// @return The expected total borrow assets.
/// @return The expected total borrow shares.
function expectedMarketBalances(IMorpho morpho, MarketParams memory marketParams)
internal
view
returns (uint256, uint256, uint256, uint256)
{
Id id = marketParams.id();
Market memory market = morpho.market(id);
uint256 elapsed = block.timestamp - market.lastUpdate;
// Skipped if elapsed == 0 or totalBorrowAssets == 0 because interest would be null, or if irm == address(0).
if (elapsed != 0 && market.totalBorrowAssets != 0 && marketParams.irm != address(0)) {
uint256 borrowRate = IIrm(marketParams.irm).borrowRateView(marketParams, market);
uint256 interest = market.totalBorrowAssets.wMulDown(borrowRate.wTaylorCompounded(elapsed));
market.totalBorrowAssets += interest.toUint128();
market.totalSupplyAssets += interest.toUint128();
if (market.fee != 0) {
uint256 feeAmount = interest.wMulDown(market.fee);
// The fee amount is subtracted from the total supply in this calculation to compensate for the fact
// that total supply is already updated.
uint256 feeShares =
feeAmount.toSharesDown(market.totalSupplyAssets - feeAmount, market.totalSupplyShares);
market.totalSupplyShares += feeShares.toUint128();
}
}
return (market.totalSupplyAssets, market.totalSupplyShares, market.totalBorrowAssets, market.totalBorrowShares);
}
/// @notice Returns the expected total supply assets of a market after having accrued interest.
function expectedTotalSupplyAssets(IMorpho morpho, MarketParams memory marketParams)
internal
view
returns (uint256 totalSupplyAssets)
{
(totalSupplyAssets,,,) = expectedMarketBalances(morpho, marketParams);
}
/// @notice Returns the expected total borrow assets of a market after having accrued interest.
function expectedTotalBorrowAssets(IMorpho morpho, MarketParams memory marketParams)
internal
view
returns (uint256 totalBorrowAssets)
{
(,, totalBorrowAssets,) = expectedMarketBalances(morpho, marketParams);
}
/// @notice Returns the expected total supply shares of a market after having accrued interest.
function expectedTotalSupplyShares(IMorpho morpho, MarketParams memory marketParams)
internal
view
returns (uint256 totalSupplyShares)
{
(, totalSupplyShares,,) = expectedMarketBalances(morpho, marketParams);
}
/// @notice Returns the expected supply assets balance of `user` on a market after having accrued interest.
/// @dev Warning: Wrong for `feeRecipient` because their supply shares increase is not taken into account.
function expectedSupplyAssets(IMorpho morpho, MarketParams memory marketParams, address user)
internal
view
returns (uint256)
{
Id id = marketParams.id();
uint256 supplyShares = morpho.supplyShares(id, user);
(uint256 totalSupplyAssets, uint256 totalSupplyShares,,) = expectedMarketBalances(morpho, marketParams);
return supplyShares.toAssetsDown(totalSupplyAssets, totalSupplyShares);
}
/// @notice Returns the expected borrow assets balance of `user` on a market after having accrued interest.
/// @dev Warning: The expected balance is rounded up, so it may be greater than the market's expected total borrow
/// assets.
function expectedBorrowAssets(IMorpho morpho, MarketParams memory marketParams, address user)
internal
view
returns (uint256)
{
Id id = marketParams.id();
uint256 borrowShares = morpho.borrowShares(id, user);
(,, uint256 totalBorrowAssets, uint256 totalBorrowShares) = expectedMarketBalances(morpho, marketParams);
return borrowShares.toAssetsUp(totalBorrowAssets, totalBorrowShares);
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @dev The maximum fee a market can have (25%).
uint256 constant MAX_FEE = 0.25e18;
/// @dev Oracle price scale.
uint256 constant ORACLE_PRICE_SCALE = 1e36;
/// @dev Liquidation cursor.
uint256 constant LIQUIDATION_CURSOR = 0.3e18;
/// @dev Max liquidation incentive factor.
uint256 constant MAX_LIQUIDATION_INCENTIVE_FACTOR = 1.15e18;
/// @dev The EIP-712 typeHash for EIP712Domain.
bytes32 constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(uint256 chainId,address verifyingContract)");
/// @dev The EIP-712 typeHash for Authorization.
bytes32 constant AUTHORIZATION_TYPEHASH =
keccak256("Authorization(address authorizer,address authorized,bool isAuthorized,uint256 nonce,uint256 deadline)");// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
import { IMorpho, MarketParams } from "@morpho-blue/src/interfaces/IMorpho.sol";
import { IPriceFeed } from "../../../../../interfaces/shared/IPriceFeed.sol";
import { IMorphoCommons } from "../../../../../interfaces/positions/BorrowLending/IMorphoCommons.sol";
import { IFlashLoanUtils } from "../../../../../interfaces/positions/BorrowLending/IFlashLoanUtils.sol";
import { ZeroAddress } from "../../../../../utils/Helpers.sol";
abstract contract BaseMorphoCommons is IMorphoCommons, IFlashLoanUtils {
error PreviewRiskExceeded();
bytes32 constant MORPHO_STORAGE_POSITION = keccak256("morpho.commons.storage") & ~bytes32(uint256(0xff));
function _getMorphoCommonsConfig() internal view virtual returns (MorphoStrategyConfig memory) {
MorphoCommonsStorage memory morphoCommons = _getMorphoCommonsStorage();
address priceFeed = address(_getBorrowLendingStorage().priceFeed);
return MorphoStrategyConfig({ morphoCommons: morphoCommons, priceFeed: priceFeed });
}
function _setMorphoCommonsStorage(MorphoStrategyConfig memory config) internal virtual {
MorphoCommonsStorage storage s = _getMorphoCommonsStorage();
if (address(config.morphoCommons.morpho) == address(0)) revert ZeroAddress();
if (config.priceFeed == address(0)) revert ZeroAddress();
s.marketParams = config.morphoCommons.marketParams;
s.morpho = config.morphoCommons.morpho;
_setBorrowLendingStorage(
BorrowLendingUtilStorage({
borrowToken: config.morphoCommons.marketParams.loanToken,
collateralToken: config.morphoCommons.marketParams.collateralToken,
priceFeed: IPriceFeed(config.priceFeed)
})
);
}
function _getMorphoCommonsStorage() internal pure virtual returns (MorphoCommonsStorage storage s) {
bytes32 slot = MORPHO_STORAGE_POSITION;
assembly {
s.slot := slot
}
}
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
import { IBorrowLendingUtils } from "./IBorrowLendingUtils.sol";
/// @dev Flash Loan Utility
abstract contract IFlashLoanUtils is IBorrowLendingUtils {
function _onFlashLoan(uint256 assets, bytes memory data) internal virtual;
/// @dev Use this function to payback complete borrowed amount
function _repayAll(address user, uint256 amount, address repayRecipent) internal virtual returns (uint256);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IVersionedVaultUtils } from "../../../interfaces/positions/IVaultStrategy.sol";
import { PermissionDenied, ZeroAddress } from "../../../utils/Helpers.sol";
/// @notice Stores version, deep copy and auto increment logic for the strategy
abstract contract VersionedVaultUtils is IVersionedVaultUtils, Ownable {
event PositionManagerUpdated(address sender, address newPositionManager, uint256 newVersion);
bytes32 constant VAULT_STRATEGY_STORAGE_POSITION = keccak256("vault.strategy.storage") & ~bytes32(uint256(0xff));
bytes32 constant CALLER_INFO_STORAGE_POSITION = keccak256("caller.info.storage") & ~bytes32(uint256(0xff));
modifier onlyPositionManager() {
if (msg.sender != _getVaultStrategyStorage().positionManager) revert PermissionDenied();
_;
}
modifier onlyDelegate() {
if (address(this) == _getCallerInfoStorage().self) revert PermissionDenied();
_;
}
function getConfig() external view returns (VaultStrategyStorage memory) {
VaultStrategyStorage memory config = _getVaultStrategyStorage();
return config;
}
function updatePositionManager(address newPositionManager) external onlyOwner {
if (newPositionManager == address(0)) revert ZeroAddress();
VaultStrategyStorage storage s = _getVaultStrategyStorage();
s.positionManager = newPositionManager;
s.version += 1;
emit PositionManagerUpdated(msg.sender, newPositionManager, s.version);
}
function _initVersionedVaultStrategyStorage(address positionManager) internal {
if (positionManager == address(0)) revert ZeroAddress();
VaultStrategyStorage storage s = _getVaultStrategyStorage();
CallerInfoStorage storage c = _getCallerInfoStorage();
s.version = 1;
s.positionManager = positionManager;
c.self = address(this);
}
function _setVaultStrategyStorage(VaultStrategyStorage memory config) internal {
VaultStrategyStorage storage s = _getVaultStrategyStorage();
s.version = config.version;
s.positionManager = config.positionManager;
}
function _getVaultStrategyStorage() internal pure returns (VaultStrategyStorage storage s) {
bytes32 slot = VAULT_STRATEGY_STORAGE_POSITION;
assembly {
s.slot := slot
}
}
function _getCallerInfoStorage() internal pure returns (CallerInfoStorage storage s) {
bytes32 slot = CALLER_INFO_STORAGE_POSITION;
assembly {
s.slot := slot
}
}
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ILoopingUtil } from "../../../../../interfaces/positions/ILoopingUtil.sol";
import { IVaultManager } from "../../../../../interfaces/positions/IVaultManager.sol";
import { IVaultStrategy } from "../../../../../interfaces/positions/IVaultStrategy.sol";
import { DepositActionParams, WithdrawActionParams } from "../../../../../interfaces/positions/ILoopingInternals.sol";
import { Constants } from "../../../../../positions/Constants.sol";
import { BaseLoopingFlashLoanablePreviewUtils } from "./BaseLoopingFlashLoanablePreviewUtils.sol";
abstract contract BaseLoopingFlashLoanableUtils is BaseLoopingFlashLoanablePreviewUtils {
/// @notice to be called when user deposits into the vault for first time
/// @param user address of the user on behalf of whom deposit takes place
/// @param _tokenAddress address of input token (hemiBTC, bfBTC)
/// @param _value value of deposit token
/// @param actionParams action parameters for the deposit
/// @param swapCalldata swap calldata for the flash loan
function _initialDeposit(
address user,
address _tokenAddress,
uint256 _value,
DepositActionParams memory actionParams,
bytes memory swapCalldata
)
internal
virtual
{
LoopingFlashLoanableCommonStorage memory s = _getLoopingFlashLoanableCommonStorage();
BorrowLendingUtilStorage memory b = _getBorrowLendingStorage();
DepositCoreParams memory coreParams = DepositCoreParams({
borrowToken: b.borrowToken, collateralToken: b.collateralToken, loopingUtil: s.loopingUtil
});
DepositResult memory result = _deposit(
DepositParams(
user,
_tokenAddress,
_value,
actionParams.flashLoanAmount,
actionParams.minCollateralSharesAfterSlippage,
true
),
swapCalldata
);
coreParams.loopingUtil.onDeposit(result.collateralAdded, result.amountBorrowed);
emit InitialDeposit(
user,
result.leverageInWAD,
_tokenAddress,
_value,
address(coreParams.collateralToken),
0,
result.collateralAdded,
coreParams.borrowToken,
0,
result.amountBorrowed
);
}
/// @notice called in any subsequent deposits, in cases where user wants to add more to their position
/// @dev since the deposit is made in ratios at the time of position creation, the weights remain unchanged
/// @param user address of the user on behalf of whom deposit takes place
/// @param _tokenAddress address of input token (hemiBTC, bfBTC)
/// @param _value value of deposit token
/// @param actionParams action parameters for the deposit
/// @param swapCalldata swap calldata for the flash loan
/// used to assert leverage is not reduced beyond the slippage
function _standardDeposit(
address user,
address _tokenAddress,
uint256 _value,
DepositActionParams memory actionParams,
bytes memory swapCalldata
)
internal
virtual
{
LoopingFlashLoanableCommonStorage memory s = _getLoopingFlashLoanableCommonStorage();
BorrowLendingUtilStorage memory b = _getBorrowLendingStorage();
DepositCoreParams memory coreParams = DepositCoreParams({
borrowToken: b.borrowToken, collateralToken: b.collateralToken, loopingUtil: s.loopingUtil
});
StandardDepositBalances memory balances = StandardDepositBalances({
preDepositCollateral: collateralBalance(user), preDepositBorrow: borrowBalance(user)
});
DepositResult memory result = _deposit(
DepositParams(
user,
_tokenAddress,
_value,
actionParams.flashLoanAmount,
actionParams.minCollateralSharesAfterSlippage,
false
),
swapCalldata
);
coreParams.loopingUtil.onDeposit(result.collateralAdded, result.amountBorrowed);
emit StandardDeposit(
user,
_tokenAddress,
_value,
address(coreParams.collateralToken),
balances.preDepositCollateral,
result.collateralAdded,
coreParams.borrowToken,
balances.preDepositBorrow,
result.amountBorrowed
);
}
/// @notice used to withdraw some funds from the position
/// @param user address of the user on behalf of whom withdrawal takes place
/// @param _value value of PT shares to be withdrawn
/// @param actionParams action parameters for the withdrawal
/// used to assert leverage is not reduced beyond the slippage
function _standardWithdraw(
address user,
uint256 _value,
IVaultManager.VaultStrategyConfig calldata userConfig,
WithdrawActionParams memory actionParams,
bytes memory swapCalldata
)
internal
{
LoopingFlashLoanableCommonStorage memory s = _getLoopingFlashLoanableCommonStorage();
BorrowLendingUtilStorage memory b = _getBorrowLendingStorage();
StandardWithdrawCoreParams memory coreParams = StandardWithdrawCoreParams({
borrowToken: b.borrowToken,
collateralToken: b.collateralToken,
primaryDepositToken: s.primaryDepositToken,
loopingUtil: s.loopingUtil
});
uint256 totalBorrow = borrowBalance(user);
uint256 totalCollateral = collateralBalance(user);
// encode the flash loan calldata
bytes memory data = abi.encode(
user,
Constants.TRANSACTION_CODE_FLASH_LOAN_WITHDRAW,
address(0),
actionParams.collateralToBePulled,
abi.encode(swapCalldata)
);
WithdrawResult memory withdrawResult;
if (actionParams.flashLoanAmount > 0) {
_onFlashLoan(actionParams.flashLoanAmount, data);
withdrawResult.sharesReceivedInPrimaryDepositToken = ERC20(coreParams.primaryDepositToken).balanceOf(user);
if (coreParams.borrowToken != coreParams.primaryDepositToken) {
withdrawResult.sharesReceivedInBorrowToken = ERC20(coreParams.borrowToken).balanceOf(user);
}
} else {
withdrawResult.sharesReceivedInPrimaryDepositToken = _pullAndSwapCollateral(user, _value, swapCalldata);
}
if (withdrawResult.sharesReceivedInPrimaryDepositToken < actionParams.minSharesReceivedInPrimaryDepositToken) {
revert SlippageExceeded();
}
if (withdrawResult.sharesReceivedInBorrowToken < actionParams.minSharesReceivedInBorrowToken) {
revert SlippageExceeded();
}
SafeERC20.safeTransfer(
IERC20(coreParams.primaryDepositToken), userConfig.user, withdrawResult.sharesReceivedInPrimaryDepositToken
);
if (coreParams.borrowToken != coreParams.primaryDepositToken) {
SafeERC20.safeTransfer(
IERC20(coreParams.borrowToken), userConfig.user, withdrawResult.sharesReceivedInBorrowToken
);
}
coreParams.loopingUtil.onWithdraw(totalCollateral - collateralBalance(user), totalBorrow - borrowBalance(user));
emit StandardWithdraw(
user,
address(coreParams.collateralToken),
_value,
address(coreParams.collateralToken),
totalCollateral,
coreParams.borrowToken,
totalBorrow,
withdrawResult.sharesReceivedInBorrowToken,
coreParams.primaryDepositToken,
withdrawResult.sharesReceivedInPrimaryDepositToken
);
}
/// @notice used to withdraw all the funds from the position
/// @param user address of the user on behalf of whom withdrawal takes place
/// @param actionParams action parameters for the withdrawal
function _withdrawAll(
address user,
IVaultManager.VaultStrategyConfig calldata userConfig,
WithdrawActionParams memory actionParams,
bytes memory swapCalldata
)
internal
{
LoopingFlashLoanableCommonStorage memory s = _getLoopingFlashLoanableCommonStorage();
BorrowLendingUtilStorage memory b = _getBorrowLendingStorage();
WithdrawAllCoreParams memory coreParams = WithdrawAllCoreParams({
borrowToken: b.borrowToken,
collateralToken: b.collateralToken,
primaryDepositToken: s.primaryDepositToken,
loopingUtil: s.loopingUtil
});
uint256 totalBorrow = borrowBalance(user);
uint256 totalCollateral = collateralBalance(user);
// encode the flash loan calldata
bytes memory data = abi.encode(
user,
Constants.TRANSACTION_CODE_FLASH_LOAN_WITHDRAW_ALL,
address(0),
actionParams.collateralToBePulled,
abi.encode(swapCalldata)
);
WithdrawResult memory withdrawResult;
if (totalBorrow > 0) {
_onFlashLoan(totalBorrow, data);
withdrawResult.sharesReceivedInPrimaryDepositToken = ERC20(coreParams.primaryDepositToken).balanceOf(user);
if (coreParams.borrowToken != coreParams.primaryDepositToken) {
withdrawResult.sharesReceivedInBorrowToken = ERC20(coreParams.borrowToken).balanceOf(user);
}
} else {
withdrawResult.sharesReceivedInPrimaryDepositToken =
_pullAndSwapCollateral(user, totalCollateral, swapCalldata);
}
if (withdrawResult.sharesReceivedInPrimaryDepositToken < actionParams.minSharesReceivedInPrimaryDepositToken) {
revert SlippageExceeded();
}
if (withdrawResult.sharesReceivedInBorrowToken < actionParams.minSharesReceivedInBorrowToken) {
revert SlippageExceeded();
}
if (borrowBalance(user) > 0 || collateralBalance(user) > 0) {
revert InsufficientWithdrawalLiquidity();
}
SafeERC20.safeTransfer(
IERC20(coreParams.primaryDepositToken), userConfig.user, withdrawResult.sharesReceivedInPrimaryDepositToken
);
if (coreParams.borrowToken != coreParams.primaryDepositToken) {
SafeERC20.safeTransfer(
IERC20(coreParams.borrowToken), userConfig.user, withdrawResult.sharesReceivedInBorrowToken
);
}
coreParams.loopingUtil.onWithdraw(totalCollateral, totalBorrow);
emit WithdrawAll(
user,
address(coreParams.collateralToken),
0,
address(coreParams.collateralToken),
totalCollateral,
coreParams.borrowToken,
totalBorrow,
withdrawResult.sharesReceivedInBorrowToken,
coreParams.primaryDepositToken,
withdrawResult.sharesReceivedInPrimaryDepositToken
);
}
/// @return (ptSharesBoughtOnDeposit, collateralAdded, amountBorrowed)
function _deposit(DepositParams memory params, bytes memory swapCalldata) private returns (DepositResult memory) {
uint256 totalCurrentCollateral = collateralBalance(params.user);
if (params.isInitial && totalCurrentCollateral > 0) revert InitialDepositAlreadyMade();
// encode the flash loan calldata
bytes memory data = abi.encode(
params.user,
Constants.TRANSACTION_CODE_FLASH_LOAN_DEPOSIT,
params._tokenAddress,
params._value,
abi.encode(params.isInitial, swapCalldata)
);
if (params._flashLoanAmount > 0) _onFlashLoan(params._flashLoanAmount, data);
else _depositWithoutFlashLoan(params.user, params._tokenAddress, params._value, params.isInitial);
uint256 leverageInWAD = _getLeverage(params.user);
uint256 collateralAdded = collateralBalance(params.user) - totalCurrentCollateral;
// Compute slippage bounds and return value
if (collateralAdded < params._leastCollateralSharesAfterSlippage) revert SlippageExceeded();
return DepositResult(leverageInWAD, collateralAdded, params._flashLoanAmount);
}
function _depositWithoutFlashLoan(
address user,
address _tokenAddress,
uint256 _value,
bool isInitial
)
internal
returns (uint256)
{
LoopingFlashLoanableCommonStorage memory s = _getLoopingFlashLoanableCommonStorage();
ILoopingUtil loopingUtil = s.loopingUtil;
uint256 collateralShares = _swapDepositToCollateral(user, _tokenAddress, _value, 0);
(uint256 collateralAdded,) = _drawDebt(user, collateralShares, 0);
if (isInitial) {
loopingUtil.pushWeightInfo(user, 0, collateralShares);
}
return collateralAdded;
}
/// @dev Add flash loan to collateral and pull flash loan equivalent amount from portfolio
function _onFlashLoanForDeposit(
address user,
uint256 flashLoanValue,
address tokenAddress,
uint256 _value,
bytes memory swapCalldata,
bool isInitial
)
internal
{
LoopingFlashLoanableCommonStorage memory s = _getLoopingFlashLoanableCommonStorage();
ILoopingUtil loopingUtil = s.loopingUtil;
FlashLoanDepositCalculations memory calc = FlashLoanDepositCalculations({
primaryDepositTokenShares: _swapBorrowToPrimaryDepositToken(user, flashLoanValue, 0, swapCalldata),
collateralShares: 0,
initialShares: 0
});
if (tokenAddress == s.primaryDepositToken) {
calc.collateralShares =
_swapDepositToCollateral(user, tokenAddress, _value + calc.primaryDepositTokenShares, 0);
calc.initialShares = Math.mulDiv(calc.collateralShares, _value, _value + calc.primaryDepositTokenShares);
} else {
calc.collateralShares = _swapDepositToCollateral(user, tokenAddress, _value, 0);
calc.initialShares = calc.collateralShares;
calc.collateralShares += _swapDepositToCollateral(
user, s.primaryDepositToken, calc.primaryDepositTokenShares, 0
);
}
_drawDebt(user, calc.collateralShares, flashLoanValue);
if (isInitial) {
loopingUtil.pushWeightInfo(user, flashLoanValue, calc.initialShares);
loopingUtil.pushWeightInfo(user, 0, calc.collateralShares - calc.initialShares);
}
}
function _pullAndSwapCollateral(
address user,
uint256 collateralToBePulled,
bytes memory swapCalldata
)
internal
returns (uint256)
{
(uint256 collateralPulled,) = _repayDebt(user, collateralToBePulled, 0, user);
return _swapCollateralToPrimaryDepositToken(user, collateralPulled, 0, swapCalldata);
}
/// @dev Use flash loan to repay borrow and pull collateral from portfolio
function _onFlashLoanForStandardWithdrawal(
address user,
uint256 collateralToBePulled,
uint256 flashLoanValue,
bytes memory swapCalldata
)
internal
{
_repayDebt(user, collateralToBePulled, flashLoanValue, user);
// Swap the collateral to borrow token for flash loan to be repaid back
_swapCollateralToBorrow(user, collateralToBePulled, flashLoanValue, swapCalldata);
}
/// @dev Use flash loan to repay borrow and pull collateral from portfolio
function _onFlashLoanForWithdrawAll(address user, uint256 flashLoanValue, bytes memory swapCalldata) internal {
uint256 collateralToPull = collateralBalance(user);
// Repay complete debt with flash loan
uint256 borrowRepaid = _repayAll(user, flashLoanValue, user);
// Pull complete collateral balance
_repayDebt(user, collateralToPull, 0, user);
// Swap the collateral to borrow token for flash loan to be repaid back
_swapCollateralToBorrow(user, collateralToPull, borrowRepaid, swapCalldata);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {Id} from "../../interfaces/IMorpho.sol";
/// @title MorphoStorageLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Helper library exposing getters to access Morpho storage variables' slot.
/// @dev This library is not used in Morpho itself and is intended to be used by integrators.
library MorphoStorageLib {
/* SLOTS */
uint256 internal constant OWNER_SLOT = 0;
uint256 internal constant FEE_RECIPIENT_SLOT = 1;
uint256 internal constant POSITION_SLOT = 2;
uint256 internal constant MARKET_SLOT = 3;
uint256 internal constant IS_IRM_ENABLED_SLOT = 4;
uint256 internal constant IS_LLTV_ENABLED_SLOT = 5;
uint256 internal constant IS_AUTHORIZED_SLOT = 6;
uint256 internal constant NONCE_SLOT = 7;
uint256 internal constant ID_TO_MARKET_PARAMS_SLOT = 8;
/* SLOT OFFSETS */
uint256 internal constant LOAN_TOKEN_OFFSET = 0;
uint256 internal constant COLLATERAL_TOKEN_OFFSET = 1;
uint256 internal constant ORACLE_OFFSET = 2;
uint256 internal constant IRM_OFFSET = 3;
uint256 internal constant LLTV_OFFSET = 4;
uint256 internal constant SUPPLY_SHARES_OFFSET = 0;
uint256 internal constant BORROW_SHARES_AND_COLLATERAL_OFFSET = 1;
uint256 internal constant TOTAL_SUPPLY_ASSETS_AND_SHARES_OFFSET = 0;
uint256 internal constant TOTAL_BORROW_ASSETS_AND_SHARES_OFFSET = 1;
uint256 internal constant LAST_UPDATE_AND_FEE_OFFSET = 2;
/* GETTERS */
function ownerSlot() internal pure returns (bytes32) {
return bytes32(OWNER_SLOT);
}
function feeRecipientSlot() internal pure returns (bytes32) {
return bytes32(FEE_RECIPIENT_SLOT);
}
function positionSupplySharesSlot(Id id, address user) internal pure returns (bytes32) {
return bytes32(
uint256(keccak256(abi.encode(user, keccak256(abi.encode(id, POSITION_SLOT))))) + SUPPLY_SHARES_OFFSET
);
}
function positionBorrowSharesAndCollateralSlot(Id id, address user) internal pure returns (bytes32) {
return bytes32(
uint256(keccak256(abi.encode(user, keccak256(abi.encode(id, POSITION_SLOT)))))
+ BORROW_SHARES_AND_COLLATERAL_OFFSET
);
}
function marketTotalSupplyAssetsAndSharesSlot(Id id) internal pure returns (bytes32) {
return bytes32(uint256(keccak256(abi.encode(id, MARKET_SLOT))) + TOTAL_SUPPLY_ASSETS_AND_SHARES_OFFSET);
}
function marketTotalBorrowAssetsAndSharesSlot(Id id) internal pure returns (bytes32) {
return bytes32(uint256(keccak256(abi.encode(id, MARKET_SLOT))) + TOTAL_BORROW_ASSETS_AND_SHARES_OFFSET);
}
function marketLastUpdateAndFeeSlot(Id id) internal pure returns (bytes32) {
return bytes32(uint256(keccak256(abi.encode(id, MARKET_SLOT))) + LAST_UPDATE_AND_FEE_OFFSET);
}
function isIrmEnabledSlot(address irm) internal pure returns (bytes32) {
return keccak256(abi.encode(irm, IS_IRM_ENABLED_SLOT));
}
function isLltvEnabledSlot(uint256 lltv) internal pure returns (bytes32) {
return keccak256(abi.encode(lltv, IS_LLTV_ENABLED_SLOT));
}
function isAuthorizedSlot(address authorizer, address authorizee) internal pure returns (bytes32) {
return keccak256(abi.encode(authorizee, keccak256(abi.encode(authorizer, IS_AUTHORIZED_SLOT))));
}
function nonceSlot(address authorizer) internal pure returns (bytes32) {
return keccak256(abi.encode(authorizer, NONCE_SLOT));
}
function idToLoanTokenSlot(Id id) internal pure returns (bytes32) {
return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + LOAN_TOKEN_OFFSET);
}
function idToCollateralTokenSlot(Id id) internal pure returns (bytes32) {
return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + COLLATERAL_TOKEN_OFFSET);
}
function idToOracleSlot(Id id) internal pure returns (bytes32) {
return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + ORACLE_OFFSET);
}
function idToIrmSlot(Id id) internal pure returns (bytes32) {
return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + IRM_OFFSET);
}
function idToLltvSlot(Id id) internal pure returns (bytes32) {
return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + LLTV_OFFSET);
}
}// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; uint256 constant WAD = 1e18; /// @title MathLib /// @author Morpho Labs /// @custom:contact [email protected] /// @notice Library to manage fixed-point arithmetic. library MathLib { /// @dev Returns (`x` * `y`) / `WAD` rounded down. function wMulDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, y, WAD); } /// @dev Returns (`x` * `WAD`) / `y` rounded down. function wDivDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, WAD, y); } /// @dev Returns (`x` * `WAD`) / `y` rounded up. function wDivUp(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivUp(x, WAD, y); } /// @dev Returns (`x` * `y`) / `d` rounded down. function mulDivDown(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) { return (x * y) / d; } /// @dev Returns (`x` * `y`) / `d` rounded up. function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) { return (x * y + (d - 1)) / d; } /// @dev Returns the sum of the first three non-zero terms of a Taylor expansion of e^(nx) - 1, to approximate a /// continuous compound interest rate. function wTaylorCompounded(uint256 x, uint256 n) internal pure returns (uint256) { uint256 firstTerm = x * n; uint256 secondTerm = mulDivDown(firstTerm, firstTerm, 2 * WAD); uint256 thirdTerm = mulDivDown(secondTerm, firstTerm, 3 * WAD); return firstTerm + secondTerm + thirdTerm; } }
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import {MarketParams, Market} from "./IMorpho.sol";
/// @title IIrm
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Interface that Interest Rate Models (IRMs) used by Morpho must implement.
interface IIrm {
/// @notice Returns the borrow rate per second (scaled by WAD) of the market `marketParams`.
/// @dev Assumes that `market` corresponds to `marketParams`.
function borrowRate(MarketParams memory marketParams, Market memory market) external returns (uint256);
/// @notice Returns the borrow rate per second (scaled by WAD) of the market `marketParams` without modifying any
/// storage.
/// @dev Assumes that `market` corresponds to `marketParams`.
function borrowRateView(MarketParams memory marketParams, Market memory market) external view returns (uint256);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {ErrorsLib} from "../libraries/ErrorsLib.sol";
/// @title UtilsLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Library exposing helpers.
/// @dev Inspired by https://github.com/morpho-org/morpho-utils.
library UtilsLib {
/// @dev Returns true if there is exactly one zero among `x` and `y`.
function exactlyOneZero(uint256 x, uint256 y) internal pure returns (bool z) {
assembly {
z := xor(iszero(x), iszero(y))
}
}
/// @dev Returns the min of `x` and `y`.
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
}
/// @dev Returns `x` safely cast to uint128.
function toUint128(uint256 x) internal pure returns (uint128) {
require(x <= type(uint128).max, ErrorsLib.MAX_UINT128_EXCEEDED);
return uint128(x);
}
/// @dev Returns max(0, x - y).
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, bytes memory returndata) = recipient.call{value: amount}("");
if (!success) {
_revert(returndata);
}
}
/**
* @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 or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* 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.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @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`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) 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
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
} else {
revert Errors.FailedCall();
}
}
}// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.28;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { IPriceFeed } from "../../../../../interfaces/shared/IPriceFeed.sol";
import {
InitialDepositEstimateResult,
StandardDepositEstimateResult,
StandardWithdrawEstimateResult,
WithdrawAllEstimateResult
} from "../../../../../interfaces/positions/ILoopingInternals.sol";
import { ILoopingUtil } from "../../../../../interfaces/positions/ILoopingUtil.sol";
import { IVaultStrategy } from "../../../../../interfaces/positions/IVaultStrategy.sol";
import { Constants } from "../../../../../positions/Constants.sol";
import { BaseLoopingFlashLoanableCommon } from "./BaseLoopingFlashLoanableCommon.sol";
abstract contract BaseLoopingFlashLoanablePreviewUtils is BaseLoopingFlashLoanableCommon {
function _previewInitialDeposit(
address _tokenAddress,
uint256 value,
uint256 leverageInWAD
)
internal
view
returns (InitialDepositEstimateResult memory)
{
return _previewDeposit(_tokenAddress, value, 0, 0, leverageInWAD);
}
function _previewStandardDeposit(
address user,
address _tokenAddress,
uint256 value
)
internal
view
returns (StandardDepositEstimateResult memory)
{
uint256 leverageInWAD = _getLeverage(user);
uint256 initialCollateral = collateralBalance(user);
uint256 totalBorrow = borrowBalance(user);
InitialDepositEstimateResult memory result =
_previewDeposit(_tokenAddress, value, totalBorrow, initialCollateral, leverageInWAD);
StandardDepositEstimateResult memory standardDepositResult;
standardDepositResult.totalCollateralBought = result.totalCollateral;
standardDepositResult.amountToBeSwapped = result.amountToBeSwapped;
standardDepositResult.flashLoanAmount = result.flashLoanAmount;
standardDepositResult.deadline = result.deadline;
standardDepositResult.risk = result.risk;
return standardDepositResult;
}
/// @notice preview in case of partial shares being withdrawn by the user
/// @param _shares Total PT shares users is willing to withdraw
/// @dev Since amount to be swapped could be less than amount received on selling PT.
/// @dev The user will receive the funds in two tokens, primary deposit token and borrow token.
function _previewStandardWithdraw(
address user,
uint256 _shares
)
internal
view
virtual
returns (StandardWithdrawEstimateResult memory)
{
LoopingFlashLoanableCommonStorage memory s = _getLoopingFlashLoanableCommonStorage();
uint256 actionDeadline = s.actionDeadline;
StandardWithdrawEstimateResult memory result;
if (_getLeverage(user) == Constants.WAD) {
result.totalSharesReceivedInPrimaryDepositToken = _previewSwapCollateralToPrimaryDepositToken(_shares);
result.deadline = block.timestamp + actionDeadline;
return result;
}
uint256 totalBorrow = borrowBalance(user);
uint256 totalCollateral = collateralBalance(user);
PreviewStandardWithdrawCalculations memory calc;
(calc.totalCollateralWithdrawn, calc.flashLoanAmount) =
_calculateWithdrawalAmountByShares(_shares, totalBorrow, totalCollateral);
if (calc.totalCollateralWithdrawn > totalCollateral) revert MaxCollateralSharesExceeded();
// Convert withdrawn collateral to primary deposit token
calc.collateralWithdrawnInPrimaryDepositToken =
_previewSwapCollateralToPrimaryDepositToken(calc.totalCollateralWithdrawn);
// Remove buffer from primary deposit token withdrawn to account for potential slippage
calc.collateralWithdrawnInPrimaryDepositTokenWithBuffer =
_getSwapAmountWithBuffer(calc.collateralWithdrawnInPrimaryDepositToken);
// Convert deposit token amount after removing buffer to borrow token to pay off flash loan,
calc.collateralWithdrawnInBorrowToken =
_previewSwapPrimaryDepositTokenToBorrow(calc.collateralWithdrawnInPrimaryDepositTokenWithBuffer);
if (calc.collateralWithdrawnInBorrowToken < calc.flashLoanAmount) revert WithdrawalBalanceExceeded();
// Use flash loan amount to repay borrow
totalBorrow -= calc.flashLoanAmount;
totalCollateral -= calc.totalCollateralWithdrawn;
result.risk = _previewRiskInternal(Constants.WAD, totalCollateral, totalBorrow);
result.totalSharesReceivedInBorrowToken = calc.collateralWithdrawnInBorrowToken - calc.flashLoanAmount;
result.totalSharesReceivedInPrimaryDepositToken =
calc.collateralWithdrawnInPrimaryDepositToken - calc.collateralWithdrawnInPrimaryDepositTokenWithBuffer;
result.amountToBeSwapped = calc.collateralWithdrawnInPrimaryDepositTokenWithBuffer;
result.collateralToBePulled = calc.totalCollateralWithdrawn;
result.flashLoanAmount = calc.flashLoanAmount;
result.minAmountOut = calc.flashLoanAmount;
result.deadline = block.timestamp + actionDeadline;
return result;
}
/// @notice preview shares received by users on complete withdrawal
/// @dev Since amount to be swapped could be less than amount received on selling PT.
/// @dev The user will receive the funds in two tokens, primary deposit token and borrow token.
function _previewWithdrawAll(address user) internal view virtual returns (WithdrawAllEstimateResult memory) {
LoopingFlashLoanableCommonStorage memory s = _getLoopingFlashLoanableCommonStorage();
uint256 actionDeadline = s.actionDeadline;
uint256 totalBorrow = borrowBalance(user);
uint256 totalCollateral = collateralBalance(user);
WithdrawAllEstimateResult memory result;
// repay complete borrow using flash loan and then pull out collateral to repay the flash loan
// assuming that flash loan amount is equivalent to total borrow balance
PreviewWithdrawAllCalculations memory calc = PreviewWithdrawAllCalculations({
collateralInPrimaryDepositToken: _previewSwapCollateralToPrimaryDepositToken(totalCollateral),
collateralInPrimaryDepositTokenWithBuffer: 0,
collateralInBorrowToken: 0
});
// Remove buffer from primary deposit token withdrawn to account for potential slippage
calc.collateralInPrimaryDepositTokenWithBuffer = _getSwapAmountWithBuffer(calc.collateralInPrimaryDepositToken);
// Convert deposit token amount after removing buffer to borrow token to pay off flash loan,
calc.collateralInBorrowToken =
_previewSwapPrimaryDepositTokenToBorrow(calc.collateralInPrimaryDepositTokenWithBuffer);
if (calc.collateralInBorrowToken < totalBorrow) revert InsufficientWithdrawalLiquidity();
result.totalSharesReceivedInBorrowToken = calc.collateralInBorrowToken - totalBorrow;
result.totalSharesReceivedInPrimaryDepositToken =
calc.collateralInPrimaryDepositToken - calc.collateralInPrimaryDepositTokenWithBuffer;
result.amountToBeSwapped = calc.collateralInPrimaryDepositTokenWithBuffer;
result.flashLoanAmount = _getFlashLoanAmountWithBuffer(totalBorrow);
result.minAmountOut = totalBorrow;
result.deadline = block.timestamp + actionDeadline;
return result;
}
/// @notice preview result of deposit being made by the user
/// @dev flash loan is always taken in terms of borrow token
function _previewDeposit(
address _tokenAddress,
uint256 value,
uint256 totalBorrow,
uint256 initialCollateral,
uint256 leverageInWAD
)
private
view
returns (InitialDepositEstimateResult memory)
{
LoopingFlashLoanableCommonStorage memory s = _getLoopingFlashLoanableCommonStorage();
BorrowLendingUtilStorage memory b = _getBorrowLendingStorage();
PreviewDepositCoreParams memory coreParams = PreviewDepositCoreParams({
priceFeed: s.priceFeed,
maxLeverage: s.maxLeverage,
actionDeadline: s.actionDeadline,
borrowToken: b.borrowToken
});
if (leverageInWAD < Constants.WAD || leverageInWAD > coreParams.maxLeverage) revert LeverageOutOfBounds();
InitialDepositEstimateResult memory result;
if (leverageInWAD == Constants.WAD) {
result.estimatedLeverage = Constants.WAD;
result.totalCollateral = _previewDepositToCollateral(_tokenAddress, value);
result.deadline = block.timestamp + coreParams.actionDeadline;
return result;
}
uint256 valueInBorrowToken =
coreParams.priceFeed.convertTokenBalance(_tokenAddress, coreParams.borrowToken, value);
uint256 flashLoanAmount = Math.mulDiv(valueInBorrowToken, leverageInWAD - Constants.WAD, Constants.WAD);
PreviewDepositCalculations memory calc = PreviewDepositCalculations({
valueInBorrowToken: valueInBorrowToken,
flashLoanAmount: flashLoanAmount,
collateralSharesOnDeposit: _previewDepositToCollateral(_tokenAddress, value),
collateralSharesOnFlashLoan: 0,
totalCollateralAdded: 0
});
calc.collateralSharesOnFlashLoan = _previewSwapBorrowToCollateral(calc.flashLoanAmount);
calc.totalCollateralAdded = calc.collateralSharesOnDeposit + calc.collateralSharesOnFlashLoan;
uint256 totalCollateral = initialCollateral + calc.totalCollateralAdded;
// Total Borrow Should increase by flash loan amount
totalBorrow += calc.flashLoanAmount;
uint256 riskPreviewed = _previewRiskInternal(Constants.WAD, totalCollateral, totalBorrow);
result.estimatedLeverage = Math.mulDiv(calc.totalCollateralAdded, Constants.WAD, calc.collateralSharesOnDeposit);
result.iteration = 0;
result.lendingThreshold = 0;
result.risk = riskPreviewed;
result.totalCollateral = calc.totalCollateralAdded;
result.deadline = block.timestamp + coreParams.actionDeadline;
// In case of deposit, flash loan amount will be swapped to primary deposit token
// This primary deposit token will be used to buy Yield Shares to be added as collateral
// From where we will borrow the amount to pay off the flash loan
result.flashLoanAmount = calc.flashLoanAmount;
result.amountToBeSwapped = calc.flashLoanAmount;
return result;
}
/// @notice max number of PT shares which can be withdrawn
function _balanceInWithdrawalToken(address user) internal view returns (uint256) {
uint256 totalBorrow = borrowBalance(user);
uint256 totalCollateral = collateralBalance(user);
return totalCollateral - _previewSwapBorrowToCollateral(totalBorrow);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; /// @title ErrorsLib /// @author Morpho Labs /// @custom:contact [email protected] /// @notice Library exposing error messages. library ErrorsLib { /// @notice Thrown when the caller is not the owner. string internal constant NOT_OWNER = "not owner"; /// @notice Thrown when the LLTV to enable exceeds the maximum LLTV. string internal constant MAX_LLTV_EXCEEDED = "max LLTV exceeded"; /// @notice Thrown when the fee to set exceeds the maximum fee. string internal constant MAX_FEE_EXCEEDED = "max fee exceeded"; /// @notice Thrown when the value is already set. string internal constant ALREADY_SET = "already set"; /// @notice Thrown when the IRM is not enabled at market creation. string internal constant IRM_NOT_ENABLED = "IRM not enabled"; /// @notice Thrown when the LLTV is not enabled at market creation. string internal constant LLTV_NOT_ENABLED = "LLTV not enabled"; /// @notice Thrown when the market is already created. string internal constant MARKET_ALREADY_CREATED = "market already created"; /// @notice Thrown when a token to transfer doesn't have code. string internal constant NO_CODE = "no code"; /// @notice Thrown when the market is not created. string internal constant MARKET_NOT_CREATED = "market not created"; /// @notice Thrown when not exactly one of the input amount is zero. string internal constant INCONSISTENT_INPUT = "inconsistent input"; /// @notice Thrown when zero assets is passed as input. string internal constant ZERO_ASSETS = "zero assets"; /// @notice Thrown when a zero address is passed as input. string internal constant ZERO_ADDRESS = "zero address"; /// @notice Thrown when the caller is not authorized to conduct an action. string internal constant UNAUTHORIZED = "unauthorized"; /// @notice Thrown when the collateral is insufficient to `borrow` or `withdrawCollateral`. string internal constant INSUFFICIENT_COLLATERAL = "insufficient collateral"; /// @notice Thrown when the liquidity is insufficient to `withdraw` or `borrow`. string internal constant INSUFFICIENT_LIQUIDITY = "insufficient liquidity"; /// @notice Thrown when the position to liquidate is healthy. string internal constant HEALTHY_POSITION = "position is healthy"; /// @notice Thrown when the authorization signature is invalid. string internal constant INVALID_SIGNATURE = "invalid signature"; /// @notice Thrown when the authorization signature is expired. string internal constant SIGNATURE_EXPIRED = "signature expired"; /// @notice Thrown when the nonce is invalid. string internal constant INVALID_NONCE = "invalid nonce"; /// @notice Thrown when a token transfer reverted. string internal constant TRANSFER_REVERTED = "transfer reverted"; /// @notice Thrown when a token transfer returned false. string internal constant TRANSFER_RETURNED_FALSE = "transfer returned false"; /// @notice Thrown when a token transferFrom reverted. string internal constant TRANSFER_FROM_REVERTED = "transferFrom reverted"; /// @notice Thrown when a token transferFrom returned false string internal constant TRANSFER_FROM_RETURNED_FALSE = "transferFrom returned false"; /// @notice Thrown when the maximum uint128 is exceeded. string internal constant MAX_UINT128_EXCEEDED = "max uint128 exceeded"; }
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}{
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@spectra-core/src/=lib/spectra-core/src/",
"@pythnetwork/pyth-sdk-solidity/=node_modules/@pythnetwork/pyth-sdk-solidity/",
"hardhat/=node_modules/hardhat/",
"@morpho-blue/=lib/morpho-blue/",
"ds-test/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"morpho-blue/=lib/morpho-blue/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"openzeppelin-erc20-basic/=lib/spectra-core/lib/openzeppelin-contracts/contracts/token/ERC20/",
"openzeppelin-erc20-extensions/=lib/spectra-core/lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/",
"openzeppelin-erc20/=lib/spectra-core/lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/",
"openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
"openzeppelin-math/=lib/spectra-core/lib/openzeppelin-contracts/contracts/utils/math/",
"openzeppelin-proxy/=lib/spectra-core/lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/",
"openzeppelin-utils/=lib/spectra-core/lib/openzeppelin-contracts/contracts/utils/",
"solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/",
"spectra-core/=lib/spectra-core/",
"v3-core/=lib/v3-core/"
],
"optimizer": {
"enabled": true,
"runs": 50
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": false
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"components":[{"components":[{"internalType":"contract IAuthorizedSwapRouter","name":"authorizedSwapRouter","type":"address"},{"internalType":"contract IERC4626","name":"avKatVault","type":"address"}],"internalType":"struct IAvKatMorphoFlashLoanableCommons.LoopingStrategyStorage","name":"loopingStrategyStorage","type":"tuple"},{"components":[{"components":[{"components":[{"internalType":"address","name":"loanToken","type":"address"},{"internalType":"address","name":"collateralToken","type":"address"},{"internalType":"address","name":"oracle","type":"address"},{"internalType":"address","name":"irm","type":"address"},{"internalType":"uint256","name":"lltv","type":"uint256"}],"internalType":"struct MarketParams","name":"marketParams","type":"tuple"},{"internalType":"contract IMorpho","name":"morpho","type":"address"}],"internalType":"struct IMorphoCommons.MorphoCommonsStorage","name":"morphoCommons","type":"tuple"},{"internalType":"address","name":"priceFeed","type":"address"}],"internalType":"struct IMorphoCommons.MorphoStrategyConfig","name":"morphoStrategyConfig","type":"tuple"},{"components":[{"internalType":"uint256","name":"amountToBeSwappedBufferInWAD","type":"uint256"},{"internalType":"uint256","name":"withdrawAllBufferInWAD","type":"uint256"},{"internalType":"uint256","name":"actionDeadline","type":"uint256"},{"internalType":"uint256","name":"maxLeverage","type":"uint256"},{"internalType":"address","name":"primaryDepositToken","type":"address"},{"internalType":"contract ILoopingUtil","name":"loopingUtil","type":"address"},{"internalType":"contract IPriceFeed","name":"priceFeed","type":"address"},{"internalType":"address","name":"flashLoanCaller","type":"address"}],"internalType":"struct ILoopingFlashLoanableCommons.LoopingFlashLoanableCommonStorage","name":"loopingFlashLoanableCommonStorage","type":"tuple"}],"internalType":"struct IAvKatMorphoFlashLoanableCommons.LoopingStrategyConfig","name":"config","type":"tuple"},{"internalType":"address","name":"positionManager","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"DeadlineExceeded","type":"error"},{"inputs":[],"name":"DivideByZeroError","type":"error"},{"inputs":[],"name":"InitialDepositAlreadyMade","type":"error"},{"inputs":[],"name":"InsufficientWithdrawalLiquidity","type":"error"},{"inputs":[],"name":"InvalidSwapParams","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"InvalidToken","type":"error"},{"inputs":[{"internalType":"uint256","name":"code","type":"uint256"}],"name":"InvalidTransactionCode","type":"error"},{"inputs":[],"name":"InvalidUserConfig","type":"error"},{"inputs":[],"name":"LeverageOutOfBounds","type":"error"},{"inputs":[],"name":"MaxCollateralSharesExceeded","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"PermissionDenied","type":"error"},{"inputs":[],"name":"PreviewRiskExceeded","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"SlippageExceeded","type":"error"},{"inputs":[],"name":"StrategyLoopingNotEnabled","type":"error"},{"inputs":[],"name":"WithdrawalBalanceExceeded","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"leverageInWAD","type":"uint256"},{"indexed":false,"internalType":"address","name":"_tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":false,"internalType":"address","name":"_collateralAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"preDepositCollateral","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"collateralAdded","type":"uint256"},{"indexed":false,"internalType":"address","name":"_borrowAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"preDepositBorrow","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountBorrowed","type":"uint256"}],"name":"InitialDeposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"address","name":"newPositionManager","type":"address"},{"indexed":false,"internalType":"uint256","name":"newVersion","type":"uint256"}],"name":"PositionManagerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"address","name":"_tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":false,"internalType":"address","name":"_collateralAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"preDepositCollateral","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"collateralAdded","type":"uint256"},{"indexed":false,"internalType":"address","name":"_borrowAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"preDepositBorrow","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountBorrowed","type":"uint256"}],"name":"StandardDeposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"address","name":"_tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":false,"internalType":"address","name":"_collateralAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"preWithdrawCollateral","type":"uint256"},{"indexed":false,"internalType":"address","name":"_borrowAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"preWithdrawBorrow","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"sharesReceivedInBorrowToken","type":"uint256"},{"indexed":false,"internalType":"address","name":"_primaryDepositTokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"sharesReceivedInPrimaryDepositToken","type":"uint256"}],"name":"StandardWithdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"address","name":"_tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"},{"indexed":false,"internalType":"address","name":"_collateralAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"preWithdrawCollateral","type":"uint256"},{"indexed":false,"internalType":"address","name":"_borrowAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"preWithdrawBorrow","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"sharesReceivedInBorrowToken","type":"uint256"},{"indexed":false,"internalType":"address","name":"_primaryDepositTokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"sharesReceivedInPrimaryDepositToken","type":"uint256"}],"name":"WithdrawAll","type":"event"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"balance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"balanceInDepositToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"balanceInUSD","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"balanceInWithdrawalToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"borrowBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"collateralBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint64","name":"transactionCode","type":"uint64"},{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"},{"components":[{"internalType":"address","name":"underlying","type":"address"},{"internalType":"address","name":"primaryDepositToken","type":"address"},{"internalType":"address","name":"primaryWithdrawalToken","type":"address"},{"internalType":"bool","name":"depositEnabled","type":"bool"},{"internalType":"bool","name":"loopingEnabled","type":"bool"}],"internalType":"struct IStrategyManager.StrategyConfig","name":"","type":"tuple"},{"components":[{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"strategy","type":"address"},{"internalType":"uint64","name":"iteration","type":"uint64"},{"internalType":"uint256","name":"lendingThreshold","type":"uint256"},{"internalType":"bool","name":"depositEnabled","type":"bool"}],"internalType":"struct IVaultManager.VaultStrategyConfig","name":"","type":"tuple"},{"internalType":"bytes","name":"_extras","type":"bytes"}],"name":"deposit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint256","name":"flashLoanAmount","type":"uint256"},{"internalType":"uint256","name":"minCollateralSharesAfterSlippage","type":"uint256"}],"internalType":"struct DepositActionParams","name":"actionParams","type":"tuple"},{"internalType":"bytes","name":"swapCalldata","type":"bytes"}],"name":"encodeConfigForDeposit","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"pure","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint256","name":"flashLoanAmount","type":"uint256"},{"internalType":"uint256","name":"collateralToBePulled","type":"uint256"},{"internalType":"uint256","name":"minSharesReceivedInPrimaryDepositToken","type":"uint256"},{"internalType":"uint256","name":"minSharesReceivedInBorrowToken","type":"uint256"}],"internalType":"struct WithdrawActionParams","name":"actionParams","type":"tuple"},{"internalType":"bytes","name":"swapCalldata","type":"bytes"}],"name":"encodeConfigForWithdraw","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getConfig","outputs":[{"components":[{"internalType":"uint256","name":"version","type":"uint256"},{"internalType":"address","name":"positionManager","type":"address"}],"internalType":"struct IVersionedVaultUtils.VaultStrategyStorage","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLoopingFlashLoanableConfig","outputs":[{"components":[{"components":[{"components":[{"internalType":"contract IAuthorizedSwapRouter","name":"authorizedSwapRouter","type":"address"},{"internalType":"contract IERC4626","name":"avKatVault","type":"address"}],"internalType":"struct IAvKatMorphoFlashLoanableCommons.LoopingStrategyStorage","name":"loopingStrategyStorage","type":"tuple"},{"components":[{"components":[{"components":[{"internalType":"address","name":"loanToken","type":"address"},{"internalType":"address","name":"collateralToken","type":"address"},{"internalType":"address","name":"oracle","type":"address"},{"internalType":"address","name":"irm","type":"address"},{"internalType":"uint256","name":"lltv","type":"uint256"}],"internalType":"struct MarketParams","name":"marketParams","type":"tuple"},{"internalType":"contract IMorpho","name":"morpho","type":"address"}],"internalType":"struct IMorphoCommons.MorphoCommonsStorage","name":"morphoCommons","type":"tuple"},{"internalType":"address","name":"priceFeed","type":"address"}],"internalType":"struct IMorphoCommons.MorphoStrategyConfig","name":"morphoStrategyConfig","type":"tuple"},{"components":[{"internalType":"uint256","name":"amountToBeSwappedBufferInWAD","type":"uint256"},{"internalType":"uint256","name":"withdrawAllBufferInWAD","type":"uint256"},{"internalType":"uint256","name":"actionDeadline","type":"uint256"},{"internalType":"uint256","name":"maxLeverage","type":"uint256"},{"internalType":"address","name":"primaryDepositToken","type":"address"},{"internalType":"contract ILoopingUtil","name":"loopingUtil","type":"address"},{"internalType":"contract IPriceFeed","name":"priceFeed","type":"address"},{"internalType":"address","name":"flashLoanCaller","type":"address"}],"internalType":"struct ILoopingFlashLoanableCommons.LoopingFlashLoanableCommonStorage","name":"loopingFlashLoanableCommonStorage","type":"tuple"}],"internalType":"struct IAvKatMorphoFlashLoanableCommons.LoopingStrategyConfig","name":"loopingStrategyConfig","type":"tuple"},{"components":[{"internalType":"uint256","name":"version","type":"uint256"},{"internalType":"address","name":"positionManager","type":"address"}],"internalType":"struct IVersionedVaultUtils.VaultStrategyStorage","name":"vaultStrategyConfig","type":"tuple"}],"internalType":"struct IAvKatMorphoFlashLoanableConfigFetcher.LoopingStrategyVersionedConfig","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"leverage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint64","name":"transactionCode","type":"uint64"},{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"},{"internalType":"uint256","name":"flashLoanAmount","type":"uint256"},{"internalType":"bytes","name":"_extras","type":"bytes"}],"name":"onFlashLoan","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"previewAvKatVaultDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"},{"internalType":"uint256","name":"_leverage","type":"uint256"}],"name":"previewInitialDeposit","outputs":[{"components":[{"internalType":"uint256","name":"totalCollateral","type":"uint256"},{"internalType":"uint256","name":"estimatedLeverage","type":"uint256"},{"internalType":"uint256","name":"risk","type":"uint256"},{"internalType":"uint256","name":"flashLoanAmount","type":"uint256"},{"internalType":"uint256","name":"amountToBeSwapped","type":"uint256"},{"internalType":"uint256","name":"lendingThreshold","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint64","name":"iteration","type":"uint64"}],"internalType":"struct InitialDepositEstimateResult","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"previewStandardDeposit","outputs":[{"components":[{"internalType":"uint256","name":"totalCollateralBought","type":"uint256"},{"internalType":"uint256","name":"flashLoanAmount","type":"uint256"},{"internalType":"uint256","name":"amountToBeSwapped","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint256","name":"risk","type":"uint256"}],"internalType":"struct StandardDepositEstimateResult","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"_shares","type":"uint256"}],"name":"previewStandardWithdraw","outputs":[{"components":[{"internalType":"uint256","name":"totalSharesReceivedInPrimaryDepositToken","type":"uint256"},{"internalType":"uint256","name":"totalSharesReceivedInBorrowToken","type":"uint256"},{"internalType":"uint256","name":"flashLoanAmount","type":"uint256"},{"internalType":"uint256","name":"amountToBeSwapped","type":"uint256"},{"internalType":"uint256","name":"collateralToBePulled","type":"uint256"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint256","name":"risk","type":"uint256"}],"internalType":"struct StandardWithdrawEstimateResult","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"previewWithdrawAll","outputs":[{"components":[{"internalType":"uint256","name":"totalSharesReceivedInPrimaryDepositToken","type":"uint256"},{"internalType":"uint256","name":"totalSharesReceivedInBorrowToken","type":"uint256"},{"internalType":"uint256","name":"flashLoanAmount","type":"uint256"},{"internalType":"uint256","name":"amountToBeSwapped","type":"uint256"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct WithdrawAllEstimateResult","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"baseValue","type":"uint256"}],"name":"risk","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"strategy","type":"address"}],"name":"setConfig","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newPositionManager","type":"address"}],"name":"updatePositionManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint64","name":"","type":"uint64"},{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"components":[{"internalType":"address","name":"underlying","type":"address"},{"internalType":"address","name":"primaryDepositToken","type":"address"},{"internalType":"address","name":"primaryWithdrawalToken","type":"address"},{"internalType":"bool","name":"depositEnabled","type":"bool"},{"internalType":"bool","name":"loopingEnabled","type":"bool"}],"internalType":"struct IStrategyManager.StrategyConfig","name":"","type":"tuple"},{"components":[{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"strategy","type":"address"},{"internalType":"uint64","name":"iteration","type":"uint64"},{"internalType":"uint256","name":"lendingThreshold","type":"uint256"},{"internalType":"bool","name":"depositEnabled","type":"bool"}],"internalType":"struct IVaultManager.VaultStrategyConfig","name":"","type":"tuple"},{"internalType":"bytes","name":"_extras","type":"bytes"}],"name":"validatePreDeposit","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint64","name":"transactionCode","type":"uint64"},{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"},{"components":[{"internalType":"address","name":"underlying","type":"address"},{"internalType":"address","name":"primaryDepositToken","type":"address"},{"internalType":"address","name":"primaryWithdrawalToken","type":"address"},{"internalType":"bool","name":"depositEnabled","type":"bool"},{"internalType":"bool","name":"loopingEnabled","type":"bool"}],"internalType":"struct IStrategyManager.StrategyConfig","name":"","type":"tuple"},{"components":[{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"strategy","type":"address"},{"internalType":"uint64","name":"iteration","type":"uint64"},{"internalType":"uint256","name":"lendingThreshold","type":"uint256"},{"internalType":"bool","name":"depositEnabled","type":"bool"}],"internalType":"struct IVaultManager.VaultStrategyConfig","name":"userConfig","type":"tuple"},{"internalType":"bytes","name":"_extras","type":"bytes"}],"name":"withdraw","outputs":[],"stateMutability":"payable","type":"function"}]Contract Creation Code
608060405234801561000f575f5ffd5b5060405161679b38038061679b83398101604081905261002e916107e5565b338061005357604051631e4fbdf760e01b81525f600482015260240160405180910390fd5b61005c81610076565b50610066816100c5565b61006f8261017a565b505061093d565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6001600160a01b0381166100ec5760405163d92e233d60e01b815260040160405180910390fd5b60017ff65cb96943ab62245d9268299b185bd2de6ad06e4548b70ef169cd307ee3ae00557ff65cb96943ab62245d9268299b185bd2de6ad06e4548b70ef169cd307ee3ae0180546001600160a01b03929092166001600160a01b03199283161790557f77dfe5000ebf9e003c57377ca58618c48c4cbb3e849c5aac4b8be634c98fc800805490911630179055565b60208101516101889061020a565b60408101516101969061033c565b5180517f0fe9e9f123d1aa01efa0fffed6d343d93a178788b8b649377f34007145c3670080546001600160a01b03199081166001600160a01b03938416179091556020909201517f0fe9e9f123d1aa01efa0fffed6d343d93a178788b8b649377f34007145c3670180549093169116179055565b8051602001517ffa8cd390214ee76f5bb8c7ea1b63ea1107ccbd7e4761fc37eee7155261967100906001600160a01b03166102585760405163d92e233d60e01b815260040160405180910390fd5b60208201516001600160a01b03166102835760405163d92e233d60e01b815260040160405180910390fd5b81518051805183546001600160a01b03199081166001600160a01b039283161785556020808401516001870180548416918516919091179055604080850151600288018054851691861691909117905560608086015160038901805486169187169190911790556080909501516004880155948101516005870180549093169084161790915583519283018452855151518216835285515181015182168382015285015116918101919091526103389061058a565b5050565b670de0b6b3a76400008160600151101561036957604051631ca8aa2560e11b815260040160405180910390fd5b60808101516001600160a01b03166103945760405163d92e233d60e01b815260040160405180910390fd5b60e08101516001600160a01b03166103bf5760405163d92e233d60e01b815260040160405180910390fd5b60c08101516001600160a01b03166103ea5760405163d92e233d60e01b815260040160405180910390fd5b60a08101516001600160a01b03166104155760405163d92e233d60e01b815260040160405180910390fd5b80517f7b4a7240fdadb5a1d32a369adb1b782af3728c5ec7e87b32ade3ba494bab7b005560208101517f7b4a7240fdadb5a1d32a369adb1b782af3728c5ec7e87b32ade3ba494bab7b015560408101517f7b4a7240fdadb5a1d32a369adb1b782af3728c5ec7e87b32ade3ba494bab7b025560608101517f7b4a7240fdadb5a1d32a369adb1b782af3728c5ec7e87b32ade3ba494bab7b035560808101517f7b4a7240fdadb5a1d32a369adb1b782af3728c5ec7e87b32ade3ba494bab7b0480546001600160a01b03199081166001600160a01b039384161790915560e08301517f7b4a7240fdadb5a1d32a369adb1b782af3728c5ec7e87b32ade3ba494bab7b078054831691841691909117905560a08301517f7b4a7240fdadb5a1d32a369adb1b782af3728c5ec7e87b32ade3ba494bab7b058054831691841691909117905560c0909201517f7b4a7240fdadb5a1d32a369adb1b782af3728c5ec7e87b32ade3ba494bab7b0680549093169116179055565b80517fa2cb2ed7d820b5d5e467fcfe3a5dc1cfa81ba017c457bb1d2da9519a43ed1f00906001600160a01b03166105d45760405163d92e233d60e01b815260040160405180910390fd5b60208201516001600160a01b03166105ff5760405163d92e233d60e01b815260040160405180910390fd5b60408201516001600160a01b031661062a5760405163d92e233d60e01b815260040160405180910390fd5b815181546001600160a01b03199081166001600160a01b0392831617835560208401516001840180548316918416919091179055604090930151600290920180549093169116179055565b60405161010081016001600160401b03811182821017156106a457634e487b7160e01b5f52604160045260245ffd5b60405290565b604051606081016001600160401b03811182821017156106a457634e487b7160e01b5f52604160045260245ffd5b604080519081016001600160401b03811182821017156106a457634e487b7160e01b5f52604160045260245ffd5b60405160a081016001600160401b03811182821017156106a457634e487b7160e01b5f52604160045260245ffd5b6001600160a01b0381168114610748575f5ffd5b50565b805161075681610734565b919050565b5f610100828403121561076c575f5ffd5b610774610675565b8251815260208084015190820152604080840151908201526060808401519082015260808301519091506107a781610734565b60808201526107b860a0830161074b565b60a08201526107c960c0830161074b565b60c08201526107da60e0830161074b565b60e082015292915050565b5f5f8284036102408112156107f8575f5ffd5b610220811215610806575f5ffd5b61080e6106aa565b604082121561081b575f5ffd5b6108236106d8565b855161082e81610734565b8152602086015161083e81610734565b60208201528152603f19919091019060e082121561085a575f5ffd5b6108626106d8565b60c083121561086f575f5ffd5b6108776106d8565b60a0841215610884575f5ffd5b61088c610706565b9350604087015161089c81610734565b845260608701516108ac81610734565b602085015260808701516108bf81610734565b604085015260a08701516108d281610734565b606085015260c087015160808501528381526108f060e0880161074b565b60208201528152610904610100870161074b565b60208201528060208301525061091e86610120870161075b565b604082015292506109349050610220840161074b565b90509250929050565b615e518061094a5f395ff3fe60806040526004361061014a575f3560e01c8063985fe064116100ba578063985fe064146102f5578063a1bf28401461035f578063b0a322c41461037e578063b7f9b17c1461039d578063b8d19933146103bc578063be5ad555146103db578063c3f909d4146103fa578063c40832311461041b578063c9205df21461049a578063d542477014610522578063e3d670d71461014e578063eaded52c14610541578063eae0673c14610554578063f2fde38b14610567575f5ffd5b806312f3c34c1461014e57806320e3dbd4146101805780632869056b146101a1578063299e537e146101c0578063318ee870146101d357806341930337146101ff5780634d73e9ba1461022b57806354fd4d501461024a5780636881d8cb1461025e578063715018a61461027d57806378ca61ca1461029157806381e8bf0b146102b25780638da5cb5b146102d1575b5f5ffd5b348015610159575f5ffd5b5061016d610168366004614c10565b610586565b6040519081526020015b60405180910390f35b34801561018b575f5ffd5b5061019f61019a366004614c10565b610632565b005b3480156101ac575f5ffd5b5061016d6101bb366004614c2b565b6106fc565b61019f6101ce366004614ca6565b610710565b3480156101de575f5ffd5b506101f26101ed366004614e70565b6108cb565b6040516101779190614eed565b34801561020a575f5ffd5b5061021e610219366004614eff565b6108fb565b6040516101779190614f6d565b348015610236575f5ffd5b5061016d610245366004614c10565b61090e565b348015610255575f5ffd5b5061016d610981565b348015610269575f5ffd5b5061019f610278366004614c10565b610990565b348015610288575f5ffd5b5061019f610a40565b34801561029c575f5ffd5b506102a5610a53565b6040516101779190615049565b3480156102bd575f5ffd5b506101f26102cc36600461510b565b610aa9565b3480156102dc575f5ffd5b505f546001600160a01b03166040516101779190615141565b348015610300575f5ffd5b5061031461030f366004614c10565b610ac0565b60405161017791905f60c082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015292915050565b34801561036a575f5ffd5b5061016d610379366004614c10565b610ad1565b348015610389575f5ffd5b5061019f61039836600461516b565b610b56565b3480156103a8575f5ffd5b5061016d6103b7366004614c10565b610b79565b3480156103c7575f5ffd5b5061016d6103d6366004614c2b565b610cb9565b3480156103e6575f5ffd5b5061016d6103f5366004614c10565b610cc4565b348015610405575f5ffd5b5061040e610cce565b604051610177919061520f565b348015610426575f5ffd5b5061043a610435366004614c2b565b610d12565b60405161017791905f61010082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015260e083015160e083015292915050565b3480156104a5575f5ffd5b506104b96104b436600461521d565b610d24565b60405161017791905f61010082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c08301526001600160401b0360e08401511660e083015292915050565b34801561052d575f5ffd5b5061016d61053c366004614c10565b610d37565b61019f61054f36600461516b565b610d41565b61019f61056236600461516b565b610e04565b348015610572575f5ffd5b5061019f610581366004614c10565b610e91565b5f5f610590610ece565b90505f61059b610ef2565b6002810154600182015460048501549293506001600160a01b039182169263f35cc24e9291821691166105cd88610f16565b6040518463ffffffff1660e01b81526004016105eb9392919061524f565b602060405180830381865afa158015610606573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061062a9190615273565b949350505050565b7f77dfe5000ebf9e003c57377ca58618c48c4cbb3e849c5aac4b8be634c98fc800546001600160a01b0316300361067c57604051630782484160e21b815260040160405180910390fd5b5f816001600160a01b03166378ca61ca6040518163ffffffff1660e01b815260040161026060405180830381865afa1580156106ba573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106de919061535c565b90506106ed8160200151610fee565b80516106f890611027565b5050565b5f6107078383611086565b90505b92915050565b5f610719610ece565b60078101549091506001600160a01b0316331461074957604051630782484160e21b815260040160405180910390fd5b5f610752610ece565b604080516101008101825282548152600183015460208201526002830154918101919091526003820154606082015260048201546001600160a01b0390811660808301526005830154811660a08301526006830154811660c083015260079092015490911660e082015290505f6107c7610ef2565b6040805180820190915281546001600160a01b03908116825260e0850151166020820152909150610bb8196001600160401b038b1601610826575f5f61080d88886111cf565b9150915061081f8d8a8d8d85876111ea565b50506108ac565b610bb9196001600160401b038b1601610858575f610844878761140d565b90506108528c8a8a8461141b565b506108ac565b610bba196001600160401b038b1601610883575f610876878761140d565b90506108528c898361143c565b6040516331a2947960e11b81526001600160401b038b1660048201526024015b60405180910390fd5b6108be815f0151826020015189611478565b5050505050505050505050565b60608383836040516020016108e2939291906154e8565b60405160208183030381529060405290505b9392505050565b610903614a25565b61062a848484611540565b5f5f6109186115c1565b60058101546040805160a08101825283546001600160a01b03908116825260018501548116602083015260028501548116928201929092526003840154821660608201526004840154608082015292935016905f6109778383886115e5565b9695505050505050565b5f61098a611637565b54919050565b61099861165b565b6001600160a01b0381166109bf5760405163d92e233d60e01b815260040160405180910390fd5b5f6109c8611637565b600181810180546001600160a01b0319166001600160a01b03861617905581549192509082905f906109fb90849061551c565b909155505080546040517fec07f803439eafbb5e1976432b2a5907b419652cd86b296cebe5a6725363beaa91610a34913391869161524f565b60405180910390a15050565b610a4861165b565b610a515f611687565b565b610a5b614a4f565b5f610a646116d6565b90505f610a6f611637565b604080518082018252825481526001909201546001600160a01b031660208084019190915281518083019092529381529283015250919050565b60608383836040516020016108e29392919061552f565b610ac8614a85565b61070a826117b1565b5f5f610adb6115c1565b60058101546040805160a08101825283546001600160a01b0390811682526001850154811660208301526002850154811692820192909252600384015482166060820152600484015460808201529293501690610b4d610b3c8260a0902090565b6001600160a01b03841690876118e7565b95945050505050565b5f610b618383611993565b509050610b6e87826119c2565b505050505050505050565b5f5f610b83610ef2565b6040805160608101825282546001600160a01b0390811682526001840154811660208301526002909301549092169082015290505f610bc0610ece565b60408051610100810182528254815260018301546020808301919091526002840154828401526003840154606083015260048401546001600160a01b0390811660808401526005850154811660a08401526006850154811660c08401908152600790950154811660e08401528351808501909452935184168084528682015190941690830181905290935090919063c2d4eda090610c5d88610f16565b6040518363ffffffff1660e01b8152600401610c7a92919061555d565b602060405180830381865afa158015610c95573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b4d9190615273565b5f6107078383611aa4565b5f61070a82611bf0565b604080518082019091525f80825260208201525f610cea611637565b60408051808201909152815481526001909101546001600160a01b0316602082015292915050565b610d1a614ab5565b6107078383611cb7565b610d2c614af2565b61062a848484611ec3565b5f61070a82611ed8565b610d49611637565b600101546001600160a01b03163314610d7557604051630782484160e21b815260040160405180910390fd5b5f5f610d818484611993565b91509150610d8f88836119c2565b6103eb196001600160401b038a1601610db657610daf8a89898585611f04565b5050610dfa565b6103e8196001600160401b038a1601610dd657610daf8a8989858561214b565b6040516331a2947960e11b81526001600160401b038a1660048201526024016108a3565b5050505050505050565b610e0c611637565b600101546001600160a01b03163314610e3857604051630782484160e21b815260040160405180910390fd5b5f5f610e4484846123c5565b91509150610e528883612400565b6107d0196001600160401b038a1601610e7257610daf8a88878585612462565b6107d9196001600160401b038a1601610dd657610daf8a868484612888565b610e9961165b565b6001600160a01b038116610ec2575f604051631e4fbdf760e01b81526004016108a39190615141565b610ecb81611687565b50565b7f7b4a7240fdadb5a1d32a369adb1b782af3728c5ec7e87b32ade3ba494bab7b0090565b7fa2cb2ed7d820b5d5e467fcfe3a5dc1cfa81ba017c457bb1d2da9519a43ed1f0090565b5f5f610f20610ef2565b6002810154600182015482549293506001600160a01b039182169290821691165f610f4a87610ad1565b90505f610f568861090e565b90505f856001600160a01b031663f35cc24e8587856040518463ffffffff1660e01b8152600401610f899392919061524f565b602060405180830381865afa158015610fa4573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fc89190615273565b9050808311610fd7575f610fe1565b610fe18184615576565b9998505050505050505050565b5f610ff7611637565b82518155602090920151600190920180546001600160a01b0319166001600160a01b039093169290921790915550565b6110348160200151612ca7565b6110418160400151612dbf565b5f61104a612f2e565b9151805183546001600160a01b03199081166001600160a01b039283161785556020909201516001909401805490921693169290921790915550565b5f5f6110906115c1565b60058101546040805160a08101825283546001600160a01b03908116825260018501548116602080840191909152600286015482168385018190526003870154831660608501526004808801546080860152855163501ad8ff60e11b81529551979850929095169592945f94909363a035b1fe9382810193928290030181865afa158015611120573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111449190615273565b90505f6111666111558460a0902090565b6001600160a01b038616908a6118e7565b90505f61117d6001600160a01b038616858b6115e5565b90505f61119983856a0c097ce7bc90715b34b9f160241b612f52565b90505f6111b3828760800151670de0b6b3a7640000612f52565b90506111c0838b83612f52565b9b9a5050505050505050505050565b5f60606111de83850185615601565b915091505b9250929050565b5f6111f3610ece565b60408051610100810182528254815260018301546020820152600283015481830152600383015460608083019190915260048401546001600160a01b0390811660808401526005850154811660a084018190526006860154821660c08501526007909501541660e0830152825190810190925292505f90808981526020015f81526020015f815250905082608001516001600160a01b0316876001600160a01b0316036112dd576112b48988835f0151896112ae919061551c565b5f613002565b6020820181905281516112d3919088906112ce908261551c565b612f52565b604082015261131d565b6112e98988885f613002565b60208201819052604082015260808301518151611308918b915f613002565b81602001818151611319919061551c565b9052505b61132c8982602001518a613170565b50508315610b6e57604080820151905162af986360e01b81526001600160a01b0384169162af986391611366918d918d9190600401615651565b5f604051808303815f87803b15801561137d575f5ffd5b505af115801561138f573d5f5f3e3d5ffd5b50505050816001600160a01b031662af98638a5f846040015185602001516113b79190615576565b6040518463ffffffff1660e01b81526004016113d593929190615651565b5f604051808303815f87803b1580156113ec575f5ffd5b505af11580156113fe573d5f5f3e3d5ffd5b50505050505050505050505050565b606061070782840184615672565b611427848484876132e3565b505061143584848484613505565b5050505050565b5f61144684610ad1565b90505f6114548585876135de565b905061146285835f886132e3565b505061147085838386613505565b505050505050565b5f836001600160a01b031663095ea7b3848460405160240161149b92919061555d565b604051602081830303815290604052915060e01b6020820180516001600160e01b03838183161783525050505090506114d4848261373a565b61153a5761153084856001600160a01b031663095ea7b3865f6040516024016114fe92919061555d565b604051602081830303815290604052915060e01b6020820180516001600160e01b03838183161783525050505061377f565b61153a848261377f565b50505050565b611548614a25565b5f61155285611bf0565b90505f61155e86610ad1565b90505f61156a8761090e565b90505f61157a87878486886137e2565b9050611584614a25565b81518152608080830151604080840191909152606080850151602085015260c0850151908401529092015191810191909152979650505050505050565b7ffa8cd390214ee76f5bb8c7ea1b63ea1107ccbd7e4761fc37eee715526196710090565b5f5f6115f28460a0902090565b90505f6116096001600160a01b0387168386613afb565b90505f5f6116178888613ba8565b909450925061162b91508490508383613e23565b98975050505050505050565b7ff65cb96943ab62245d9268299b185bd2de6ad06e4548b70ef169cd307ee3ae0090565b5f546001600160a01b03163314610a51573360405163118cdaa760e01b81526004016108a39190615141565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6116de614b38565b5f6116e7613e47565b90505f6116f2612f2e565b6040805180820190915281546001600160a01b039081168252600190920154909116602082015290505f611724610ece565b6040805161010081018252825481526001830154602080830191909152600284015482840152600384015460608084019190915260048501546001600160a01b0390811660808501526005860154811660a08501526006860154811660c085015260079095015490941660e083015282519384018352948352938201949094529283019190915250919050565b6117b9614a85565b5f6117c2610ece565b6040805161010081018252825481526001830154602082015260028301549181018290526003830154606082015260048301546001600160a01b0390811660808301526005840154811660a08301526006840154811660c083015260079093015490921660e08301529091505f6118388561090e565b90505f61184486610ad1565b90505f604051806060016040528061185b84613ee2565b81526020015f81526020015f8152509050611878815f0151613eec565b6020820181905283111561189f5760405163ce07f32960e01b815260040160405180910390fd5b8281602001516118af9190615576565b8652606086018290526118c183613f13565b6040870152608086018390526118d7844261551c565b60a0870152509395945050505050565b5f5f6118fb6118f68585613f3b565b613fa5565b90506080856001600160a01b0316637784c685836040518263ffffffff1660e01b815260040161192b91906156a3565b5f60405180830381865afa158015611945573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261196c91908101906156e5565b5f8151811061197d5761197d61578f565b6020026020010151901c5f1c9150509392505050565b6119b460405180606001604052805f81526020015f81526020015f81525090565b60606111de838501856157a3565b5f6119cb612f2e565b60018101549091506001600160a01b03848116911614801590611a755750806001015f9054906101000a90046001600160a01b03166001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a3b573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a5f91906157d8565b6001600160a01b0316836001600160a01b031614155b15611a95578260405163961c9a4f60e01b81526004016108a39190615141565b611a9f8383613fee565b505050565b5f5f611aae612f2e565b60018101549091506001600160a01b0390811690851603611ad2578291505061070a565b806001015f9054906101000a90046001600160a01b03166001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b24573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b4891906157d8565b6001600160a01b0316846001600160a01b031603611bd557600181015460405163ef8b30f760e01b8152600481018590526001600160a01b039091169063ef8b30f790602401602060405180830381865afa158015611ba9573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611bcd9190615273565b91505061070a565b8360405163961c9a4f60e01b81526004016108a39190615141565b5f5f611bfa610ece565b60058101546040516315d8faf960e11b81526001600160a01b0386811660048301525f6024830181905293945090911691908290632bb1f5f29060440160c060405180830381865afa158015611c52573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c7691906157f3565b905080602001515f03611c9c576040516347d960dd60e11b815260040160405180910390fd5b610b4d8160600151670de0b6b3a76400008360200151612f52565b611cbf614ab5565b5f611cc8610ece565b604080516101008101825282548152600183015460208201526002830154918101919091526003820154606082015260048201546001600160a01b0390811660808301526005830154811660a08301526006830154811660c083015260079092015490911660e08201529050670de0b6b3a7640000611d4685611bf0565b03611d775760608201839052611d5b83613ee2565b82526040810151611d6c904261551c565b60c08301525061070a565b5f611d818561090e565b90505f611d8d86610ad1565b9050611dbc6040518060a001604052805f81526020015f81526020015f81526020015f81526020015f81525090565b611dc7868484614010565b6020830152808252821015611def576040516329d8bc6560e01b815260040160405180910390fd5b8051611dfa90613ee2565b60408201819052611e0a90613eec565b6060820181905260208201511115611e3557604051637640d81960e11b815260040160405180910390fd5b6020810151611e449084615576565b8151909350611e539083615576565b9150611e68670de0b6b3a7640000838561416f565b60e086015260208101516060820151611e819190615576565b85528051608086018190526060860152602081018051604080880191909152905160a0870152840151611eb4904261551c565b60c08601525050505092915050565b611ecb614af2565b61062a84845f5f866137e2565b5f5f611ee38361090e565b90505f611eef84610ad1565b9050611efa8261426b565b61062a9082615576565b5f611f0d610ece565b604080516101008101825282548152600183015460208201526002830154918101919091526003820154606082015260048201546001600160a01b0390811660808301526005830154811660a08301526006830154811660c083015260079092015490911660e082015290505f611f82610ef2565b604080516060808201835283546001600160a01b0390811683526001808601548216602080860191825260029097015483168587015285518085018752855184168152905183168188015260a0808a0151841682880152865160c0810188528f85168152938e16848901528387018d9052968b015193830193909352938901516080820152938401929092529250905f9061201d90866142e4565b905081604001516001600160a01b03166303004b47826020015183604001516040518363ffffffff1660e01b8152600401612062929190918252602082015260400190565b5f604051808303815f87803b158015612079575f5ffd5b505af115801561208b573d5f5f3e3d5ffd5b505050507f379b944cc5e5dcecb69673a04f085f89a235716bdf4faff51ef6cda15b06063089825f01518a8a86602001515f8760200151895f01515f8a604001516040516121389a999897969594939291906001600160a01b039a8b168152602081019990995296891660408901526060880195909552928716608087015260a086019190915260c085015290931660e08301526101008201929092526101208101919091526101400190565b60405180910390a1505050505050505050565b5f612154610ece565b604080516101008101825282548152600183015460208201526002830154918101919091526003820154606082015260048201546001600160a01b0390811660808301526005830154811660a08301526006830154811660c083015260079092015490911660e082015290505f6121c9610ef2565b604080516060808201835283546001600160a01b039081168352600185015481166020808501918252600290960154821684860152845192830185528351821683525181169482019490945260a086015190931683830152815180830190925292505f90806122378b610ad1565b81526020016122458b61090e565b81525090505f61229d6040518060c001604052808c6001600160a01b031681526020018b6001600160a01b031681526020018a815260200189602001518152602001896040015181526020015f1515815250876142e4565b905082604001516001600160a01b03166303004b47826020015183604001516040518363ffffffff1660e01b81526004016122e2929190918252602082015260400190565b5f604051808303815f87803b1580156122f9575f5ffd5b505af115801561230b573d5f5f3e3d5ffd5b505050507fb6f3b90a749b43aed5c7575dfceb3dc53de99cc166c0091ce9079bcfa92204198a8a8a8660200151865f01518660200151895f0151896020015189604001516040516123b1999897969594939291906001600160a01b03998a168152978916602089015260408801969096529387166060870152608086019290925260a085015290931660c083015260e08201929092526101008101919091526101200190565b60405180910390a150505050505050505050565b6123f26040518060a001604052805f81526020015f81526020015f81526020015f81526020015f81525090565b60606111de8385018561585c565b5f612409610ef2565b60018101549091506001600160a01b039081169084168114612440578360405163961c9a4f60e01b81526004016108a39190615141565b825142111561153a5760405163559895a360e01b815260040160405180910390fd5b5f61246b610ece565b604080516101008101825282548152600183015460208201526002830154918101919091526003820154606082015260048201546001600160a01b0390811660808301526005830154811660a08301526006830154811660c083015260079092015490911660e082015290505f6124e0610ef2565b604080516060808201835283546001600160a01b039081168352600185015481166020808501918252600290960154821684860152845160808082018752855184168252915183169681019690965287015181169385019390935260a08601519092169183019190915291505f6125568961090e565b90505f6125628a610ad1565b90505f8a610bba5f8a604001518a6040516020016125809190614eed565b60408051601f19818403018152908290526125a19594939291602001615891565b60408051601f198184030181528282019091525f808352602083015291506020890151156126da576125d7896020015183614452565b84604001516001600160a01b03166370a082318d6040518263ffffffff1660e01b81526004016126079190615141565b602060405180830381865afa158015612622573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906126469190615273565b8152604085015185516001600160a01b039081169116146126d55784516040516370a0823160e01b81526001600160a01b03909116906370a0823190612690908f90600401615141565b602060405180830381865afa1580156126ab573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906126cf9190615273565b60208201525b6126e8565b6126e58c8c8a6144db565b81525b60608901518151101561270e57604051638199f5f360e01b815260040160405180910390fd5b88608001518160200151101561273757604051638199f5f360e01b815260040160405180910390fd5b60408501516127549061274d60208d018d614c10565b83516144f8565b84604001516001600160a01b0316855f01516001600160a01b0316146127915784516127919061278760208d018d614c10565b83602001516144f8565b84606001516001600160a01b031663bef26de06127ad8e610ad1565b6127b79086615576565b6127c08f61090e565b6127ca9088615576565b6040516001600160e01b031960e085901b168152600481019290925260248201526044015f604051808303815f87803b158015612805575f5ffd5b505af1158015612817573d5f5f3e3d5ffd5b505050507f752b07e36bcb434ad5d933fe9d5b99988d8314bc6d350ef03b996714cfb97e3d8c86602001518d8860200151878a5f01518a88602001518d604001518a5f01516040516128729a999897969594939291906158d2565b60405180910390a1505050505050505050505050565b5f612891610ece565b604080516101008101825282548152600183015460208201526002830154918101919091526003820154606082015260048201546001600160a01b0390811660808301526005830154811660a08301526006830154811660c083015260079092015490911660e082015290505f612906610ef2565b604080516060808201835283546001600160a01b039081168352600185015481166020808501918252600290960154821684860152845160808082018752855184168252915183169681019690965287015181169385019390935260a08601519092169183019190915291505f61297c8861090e565b90505f61298889610ad1565b90505f89610bbb5f8a604001518a6040516020016129a69190614eed565b60408051601f19818403018152908290526129c79594939291602001615891565b60408051601f198184030181528282019091525f808352602083015291508315612af8576129f58483614452565b84604001516001600160a01b03166370a082318c6040518263ffffffff1660e01b8152600401612a259190615141565b602060405180830381865afa158015612a40573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612a649190615273565b8152604085015185516001600160a01b03908116911614612af35784516040516370a0823160e01b81526001600160a01b03909116906370a0823190612aae908e90600401615141565b602060405180830381865afa158015612ac9573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612aed9190615273565b60208201525b612b06565b612b038b848a6144db565b81525b606089015181511015612b2c57604051638199f5f360e01b815260040160405180910390fd5b886080015181602001511015612b5557604051638199f5f360e01b815260040160405180910390fd5b5f612b5f8c61090e565b1180612b7257505f612b708c610ad1565b115b15612b905760405163ce07f32960e01b815260040160405180910390fd5b6040850151612ba69061274d60208d018d614c10565b84604001516001600160a01b0316855f01516001600160a01b031614612bd9578451612bd99061278760208d018d614c10565b60608501516040516305f7936f60e51b815260048101859052602481018690526001600160a01b039091169063bef26de0906044015f604051808303815f87803b158015612c25575f5ffd5b505af1158015612c37573d5f5f3e3d5ffd5b505050507f22b4f0c8d32b8805fe1a159b4bc68f4fb1047c443cb81736313981230ab103068b86602001515f8860200151878a5f01518a88602001518d604001518a5f0151604051612c929a999897969594939291906158d2565b60405180910390a15050505050505050505050565b5f612cb06115c1565b8251602001519091506001600160a01b0316612cdf5760405163d92e233d60e01b815260040160405180910390fd5b60208201516001600160a01b0316612d0a5760405163d92e233d60e01b815260040160405180910390fd5b81518051805183546001600160a01b03199081166001600160a01b039283161785556020808401516001870180548416918516919091179055604080850151600288018054851691861691909117905560608086015160038901805486169187169190911790556080909501516004880155948101516005870180549093169084161790915583519283018452855151518216835285515181015182168382015285015116918101919091526106f89061451e565b670de0b6b3a764000081606001511015612dec57604051631ca8aa2560e11b815260040160405180910390fd5b60808101516001600160a01b0316612e175760405163d92e233d60e01b815260040160405180910390fd5b60e08101516001600160a01b0316612e425760405163d92e233d60e01b815260040160405180910390fd5b60c08101516001600160a01b0316612e6d5760405163d92e233d60e01b815260040160405180910390fd5b60a08101516001600160a01b0316612e985760405163d92e233d60e01b815260040160405180910390fd5b5f612ea1610ece565b8251815560208301516001820155604083015160028201556060830151600382015560808301516004820180546001600160a01b03199081166001600160a01b039384161790915560e0850151600784018054831691841691909117905560a0850151600584018054831691841691909117905560c0909401516006909201805490941691161790915550565b7f0fe9e9f123d1aa01efa0fffed6d343d93a178788b8b649377f34007145c3670090565b5f5f5f612f5f86866145f3565b91509150815f03612f8357838181612f7957612f7961592a565b04925050506108f4565b818411612f9a57612f9a600385150260111861460f565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010185841190960395909502919093039390930492909217029150509392505050565b5f5f61300c612f2e565b9050806001015f9054906101000a90046001600160a01b03166001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613060573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061308491906157d8565b6001600160a01b0316856001600160a01b0316036131345760018101546130b69086906001600160a01b031686611478565b6001810154604051636e553f6560e01b8152600481018690526001600160a01b03888116602483015290911690636e553f65906044016020604051808303815f875af1158015613108573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061312c9190615273565b91505061062a565b60018101546001600160a01b0390811690861603613155578391505061062a565b8460405163961c9a4f60e01b81526004016108a39190615141565b5f5f5f61317b6115c1565b90505f613186610ef2565b60058301546040805160a08101825285546001600160a01b039081168252600187015481166020830152600287015481169282019290925260038601548216606082015260048601546080820152929350169087156132575760018301546001600160a01b03166131f881848b611478565b60405163238d657960e01b81526001600160a01b0384169063238d6579906132289085908d908f9060040161593e565b5f604051808303815f87803b15801561323f575f5ffd5b505af1158015613251573d5f5f3e3d5ffd5b50505050505b5f87156132d557826001600160a01b03166350d8cd4b838a5f8e8f6040518663ffffffff1660e01b8152600401613292959493929190615976565b60408051808303815f875af11580156132ad573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906132d191906159b2565b5090505b979997985050505050505050565b5f5f5f6132ee6115c1565b90505f6132f9610ef2565b604080516060808201835260058601546001600160a01b039081168352835160a08101855287548216815260018801548216602082810191909152600289015483168287015260038901548316938201939093526004808901546080830152928401819052855482168486015283519451630a8e0d6f60e11b8152959650929493169263151c1ade9261338e929091016159d4565b5f604051808303815f87803b1580156133a5575f5ffd5b505af11580156133b7573d5f5f3e3d5ffd5b505f9250508815905061348c57602082015182515f916133e1916001600160a01b0316908d6115e5565b90508089106133fc576133f58b8a8a6135de565b915061348a565b61340e8360400151845f01518b611478565b825f01516001600160a01b03166320b76e8184602001518b5f8f6040518563ffffffff1660e01b815260040161344794939291906159e2565b60408051808303815f875af1158015613462573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061348691906159b2565b5091505b505b88156132d55781516020830151604051638720316d60e01b81526001600160a01b0390921691638720316d916134ca918d908f908190600401615a23565b5f604051808303815f87803b1580156134e1575f5ffd5b505af11580156134f3573d5f5f3e3d5ffd5b50505050979997985050505050505050565b5f835f0361351457505f61062a565b5f61351d612f2e565b80549091506001600160a01b03165f808061353787614620565b925092509250613547838961469f565b6001850154613560906001600160a01b0316858b611478565b6040516338a0e33160e01b81526001600160a01b038516906338a0e3319061359090869086908690600401615a57565b6020604051808303815f875af11580156135ac573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906135d09190615273565b9a9950505050505050505050565b5f5f6135e86115c1565b90505f6135f3610ef2565b805460058401549192506001600160a01b03908116916136169183911688611478565b6040805160a0808201835285546001600160a01b03908116835260018701548116602084015260028701548116938301939093526003860154909216606082015260048501546080820152205f9061367d9060058601546001600160a01b0316908a613afb565b60058501546040516320b76e8160e01b81529192506001600160a01b0316906320b76e81906136b69087905f9086908e90600401615ae4565b60408051808303815f875af11580156136d1573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906136f591906159b2565b5060058501549095506137139083906001600160a01b03165f611478565b8487111561372f5761372f828761372a888b615576565b6144f8565b505050509392505050565b5f5f5f5f60205f8651602088015f8a5af192503d91505f5190508280156109775750811561376b5780600114610977565b50505050506001600160a01b03163b151590565b5f5f60205f8451602086015f885af18061379e576040513d5f823e3d81fd5b50505f513d915081156137b55780600114156137c2565b6001600160a01b0384163b155b1561153a5783604051635274afe760e01b81526004016108a39190615141565b6137ea614af2565b5f6137f3610ece565b604080516101008101825282548152600183015460208201526002830154918101919091526003820154606082015260048201546001600160a01b0390811660808301526005830154811660a08301526006830154811660c083015260079092015490911660e082015290505f613868610ef2565b604080516060808201835283546001600160a01b03908116835260018501548116602080850191909152600290950154811683850152835160808101855260c088015182168152878301519581019590955286840151938501939093528151909216918301919091529150670de0b6b3a76400008510806138ec5750806020015185115b1561390a57604051631ca8aa2560e11b815260040160405180910390fd5b613912614af2565b670de0b6b3a7640000860361395a57670de0b6b3a764000060208201526139398a8a611aa4565b8152604082015161394a904261551c565b60c08201529350610b4d92505050565b815160608301516040516379ae612760e11b81525f926001600160a01b03169163f35cc24e91613990918f918f9060040161524f565b602060405180830381865afa1580156139ab573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906139cf9190615273565b90505f6139f6826139e8670de0b6b3a76400008b615576565b670de0b6b3a7640000612f52565b90505f6040518060a00160405280848152602001838152602001613a1a8f8f611aa4565b81526020015f81526020015f8152509050613a38816020015161426b565b606082018190526040820151613a4e919061551c565b608082018190525f90613a61908c61551c565b905081602001518c613a73919061551c565b9b505f613a89670de0b6b3a7640000838f61416f565b9050613aa68360800151670de0b6b3a76400008560400151612f52565b60208701525f60e0870181905260a0870152604080870182905260808401518752870151613ad4904261551c565b60c087015250506020018051606085015251608084015250909a9950505050505050505050565b5f5f613b0a6118f68585613f3b565b604051637784c68560e01b81529091506001600160a01b03861690637784c68590613b399084906004016156a3565b5f60405180830381865afa158015613b53573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052613b7a91908101906156e5565b5f81518110613b8b57613b8b61578f565b60200260200101515f1c6001600160801b03169150509392505050565b5f5f5f5f5f613bb88660a0902090565b604051632e3071cd60e11b8152600481018290529091505f906001600160a01b03891690635c60e39a9060240160c060405180830381865afa158015613c00573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613c249190615b74565b90505f81608001516001600160801b031642613c409190615576565b90508015801590613c5d575060408201516001600160801b031615155b8015613c75575060608801516001600160a01b031615155b15613def576060880151604051638c00bf6b60e01b81525f916001600160a01b031690638c00bf6b90613cae908c908790600401615be9565b602060405180830381865afa158015613cc9573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ced9190615273565b90505f613d11613cfd83856147b0565b60408601516001600160801b03169061480e565b9050613d1c81614822565b84604001818151613d2d9190615c53565b6001600160801b0316905250613d4281614822565b84518590613d51908390615c53565b6001600160801b0390811690915260a086015116159050613dec575f613d8d8560a001516001600160801b03168361480e90919063ffffffff16565b90505f613dc182875f01516001600160801b0316613dab9190615576565b60208801518491906001600160801b031661487e565b9050613dcc81614822565b86602001818151613ddd9190615c53565b6001600160801b031690525050505b50505b508051602082015160408301516060909301516001600160801b039283169b9183169a509282169850911695509350505050565b5f61062a613e3260018561551c565b613e3f620f42408561551c565b8691906148a2565b613e4f614ba7565b5f613e586115c1565b6040805160e08101825282546001600160a01b039081169282019283526001840154811660608301526002840154811660808301526003840154811660a0830152600484015460c083015291815260059092015416602082015290505f613ebd610ef2565b60020154604080518082019091529283526001600160a01b0316602083015250919050565b5f61070a826148cd565b5f5f613ef6610ece565b90506108f483825f0154670de0b6b3a76400006139e89190615576565b5f5f613f1d610ece565b90506108f4838260010154670de0b6b3a76400006139e8919061551c565b5f600182846002604051602001613f5c929190918252602082015260400190565b60405160208183030381529060405280519060200120604051602001613f8392919061555d565b604051602081830303815290604052805190602001205f1c610707919061551c565b6040805160018082528183019092526060915f91906020808301908036833701905050905082815f81518110613fdd57613fdd61578f565b602090810291909101015292915050565b80514211156106f85760405163559895a360e01b815260040160405180910390fd5b5f5f845f03614032576040516347d960dd60e11b815260040160405180910390fd5b5f6040518060600160405280614047886148cd565b8152602001614055866148cd565b81526020015f815250905080602001515f03614084576040516347d960dd60e11b815260040160405180910390fd5b61409b85670de0b6b3a76400008360200151612f52565b60408201819052670de0b6b3a7640000116140ef5760405162461bcd60e51b81526020600482015260146024820152735269736b20526174696f2065786365656473203160601b60448201526064016108a3565b8051604082015161410d91906112ce81670de0b6b3a7640000615576565b91506141188261426b565b614122908761551c565b92508482111561414557604051637640d81960e11b815260040160405180910390fd5b83831115614166576040516329d8bc6560e01b815260040160405180910390fd5b50935093915050565b5f5f6141796115c1565b6040805160a08101825282546001600160a01b0390811682526001840154811660208084019190915260028501548216838501819052600386015490921660608401526004808601546080850152845163501ad8ff60e11b81529451959650929491935f93859363a035b1fe93838301939092908290030181865afa158015614204573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906142289190615273565b90505f61424488836a0c097ce7bc90715b34b9f160241b612f52565b90505f61425e828660800151670de0b6b3a7640000612f52565b90506135d0888b83612f52565b5f5f614275612f2e565b600181015460405163ef8b30f760e01b8152600481018690529192506001600160a01b03169063ef8b30f7906024015b602060405180830381865afa1580156142c0573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108f49190615273565b61430560405180606001604052805f81526020015f81526020015f81525090565b5f614312845f0151610ad1565b90508360a00151801561432457505f81115b1561434257604051630d66e4af60e21b815260040160405180910390fd5b5f845f0151610bb9866020015187604001518860a001518860405160200161436b929190615c72565b60408051601f198184030181529082905261438c9594939291602001615891565b60405160208183030381529060405290505f856060015111156143bc576143b7856060015182614452565b6143d9565b6143d7855f0151866020015187604001518860a0015161490b565b505b5f6143e6865f0151611bf0565b90505f836143f6885f0151610ad1565b6144009190615576565b9050866080015181101561442757604051638199f5f360e01b815260040160405180910390fd5b6040518060600160405280838152602001828152602001886060015181525094505050505092915050565b5f61445b6115c1565b90505f614466610ef2565b6005830154815460405163701195a160e11b81529293506001600160a01b0391821692911690829063e0232b42906144a69084908a908a90600401615c8c565b5f604051808303815f87803b1580156144bd575f5ffd5b505af11580156144cf573d5f5f3e3d5ffd5b50505050505050505050565b5f5f6144e985855f886132e3565b509050610b4d85825f86614a0c565b611a9f83846001600160a01b031663a9059cbb85856040516024016114fe92919061555d565b5f614527610ef2565b82519091506001600160a01b03166145525760405163d92e233d60e01b815260040160405180910390fd5b60208201516001600160a01b031661457d5760405163d92e233d60e01b815260040160405180910390fd5b60408201516001600160a01b03166145a85760405163d92e233d60e01b815260040160405180910390fd5b815181546001600160a01b03199081166001600160a01b0392831617835560208401516001840180548316918416919091179055604090930151600290920180549093169116179055565b5f805f1983850993909202808410938190039390930393915050565b634e487b715f52806020526024601cfd5b61467b6040518061010001604052805f6001600160a01b031681526020015f6001600160a01b031681526020015f6001600160a01b031681526020015f81526020015f81526020015f81526020015f81526020015f81525090565b606080838060200190518101906146929190615cff565b9250925092509193909250565b5f6146a8612f2e565b600181015460208501519192506001600160a01b039182169116146146e057604051635037072d60e01b815260040160405180910390fd5b806001015f9054906101000a90046001600160a01b03166001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015614732573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061475691906157d8565b6001600160a01b031683604001516001600160a01b03161461478b57604051635037072d60e01b815260040160405180910390fd5b8183608001511015611a9f57604051635037072d60e01b815260040160405180910390fd5b5f806147bc8385615de5565b90505f6147dc82806147d7670de0b6b3a76400006002615de5565b614a19565b90505f6147f782846147d7670de0b6b3a76400006003615de5565b905080614804838561551c565b610977919061551c565b5f6107078383670de0b6b3a7640000614a19565b6040805180820190915260148152731b585e081d5a5b9d0c4c8e08195e18d95959195960621b60208201525f906001600160801b038311156148775760405162461bcd60e51b81526004016108a39190614eed565b5090919050565b5f61062a61488f620f42408461551c565b61489a60018661551c565b869190614a19565b5f816148af600182615576565b6148b98587615de5565b6148c3919061551c565b61062a9190615dfc565b5f5f6148d7612f2e565b600181015460405163266d6a8360e11b8152600481018690529192506001600160a01b031690634cdad506906024016142a5565b5f5f614915610ece565b604080516101008101825282548152600183015460208201526002830154918101919091526003820154606082015260048201546001600160a01b0390811660808301526005830154811660a083018190526006840154821660c08401526007909301541660e082015291505f61498e88888884613002565b90505f61499c89835f613170565b509050851561162b5760405162af986360e01b81526001600160a01b0384169062af9863906149d3908c905f908790600401615651565b5f604051808303815f87803b1580156149ea575f5ffd5b505af11580156149fc573d5f5f3e3d5ffd5b5050505098975050505050505050565b5f610b4d85858585613505565b5f816148c38486615de5565b6040518060a001604052805f81526020015f81526020015f81526020015f81526020015f81525090565b6040518060400160405280614a62614b38565b8152602001614a80604080518082019091525f808252602082015290565b905290565b6040518060c001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b6040518061010001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b6040518061010001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f6001600160401b031681525090565b6040805160a081019091525f606082018181526080830191909152815260208101614b61614ba7565b815260408051610100810182525f8082526020828101829052928201819052606082018190526080820181905260a0820181905260c0820181905260e082015291015290565b6040518060400160405280614bba614bc6565b81525f60209091015290565b6040805160e0810182525f918101828152606082018390526080820183905260a0820183905260c0820192909252908190614bba565b6001600160a01b0381168114610ecb575f5ffd5b5f60208284031215614c20575f5ffd5b81356108f481614bfc565b5f5f60408385031215614c3c575f5ffd5b8235614c4781614bfc565b946020939093013593505050565b6001600160401b0381168114610ecb575f5ffd5b5f5f83601f840112614c79575f5ffd5b5081356001600160401b03811115614c8f575f5ffd5b6020830191508360208285010111156111e3575f5ffd5b5f5f5f5f5f5f5f60c0888a031215614cbc575f5ffd5b8735614cc781614bfc565b96506020880135614cd781614c55565b95506040880135614ce781614bfc565b9450606088013593506080880135925060a08801356001600160401b03811115614d0f575f5ffd5b614d1b8a828b01614c69565b989b979a50959850939692959293505050565b634e487b7160e01b5f52604160045260245ffd5b60405160a081016001600160401b0381118282101715614d6457614d64614d2e565b60405290565b604051606081016001600160401b0381118282101715614d6457614d64614d2e565b60405161010081016001600160401b0381118282101715614d6457614d64614d2e565b604080519081016001600160401b0381118282101715614d6457614d64614d2e565b60405160c081016001600160401b0381118282101715614d6457614d64614d2e565b604051601f8201601f191681016001600160401b0381118282101715614e1b57614e1b614d2e565b604052919050565b5f60a08284031215614e33575f5ffd5b614e3b614d42565b823581526020808401359082015260408084013590820152606080840135908201526080928301359281019290925250919050565b5f5f5f60c08486031215614e82575f5ffd5b614e8c8585614e23565b925060a08401356001600160401b03811115614ea6575f5ffd5b614eb286828701614c69565b9497909650939450505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f6107076020830184614ebf565b5f5f5f60608486031215614f11575f5ffd5b8335614f1c81614bfc565b92506020840135614f2c81614bfc565b929592945050506040919091013590565b80518252602081015160208301526040810151604083015260608101516060830152608081015160808301525050565b60a0810161070a8284614f3d565b6001600160a01b03169052565b80516001600160a01b03908116835260208083015182169084015260408083015182169084015260608083015190911690830152608090810151910152565b8051825260208101516020830152604081015160408301526060810151606083015260018060a01b03608082015116608083015260018060a01b0360a08201511660a083015260018060a01b0360c08201511660c083015260e0810151611a9f60e0840182614f7b565b805182526020908101516001600160a01b0316910152565b8151805180516001600160a01b039081168452602091820151168184015281015180518051610260850193929190615085906040870190614f88565b6020908101516001600160a01b0390811660e087015291015116610100840152604001516150b7610120840182614fc7565b5060208301516150cb610220840182615031565b5092915050565b5f606082840312156150e2575f5ffd5b6150ea614d6a565b82358152602080840135908201526040928301359281019290925250919050565b5f5f5f6080848603121561511d575f5ffd5b61512785856150d2565b925060608401356001600160401b03811115614ea6575f5ffd5b6001600160a01b0391909116815260200190565b5f60a08284031215615165575f5ffd5b50919050565b5f5f5f5f5f5f5f5f6101e0898b031215615183575f5ffd5b883561518e81614bfc565b9750602089013561519e81614c55565b965060408901356151ae81614bfc565b9550606089013594506151c48a60808b01615155565b93506151d48a6101208b01615155565b92506101c08901356001600160401b038111156151ef575f5ffd5b6151fb8b828c01614c69565b999c989b5096995094979396929594505050565b6040810161070a8284615031565b5f5f5f6060848603121561522f575f5ffd5b833561523a81614bfc565b95602085013595506040909401359392505050565b6001600160a01b039384168152919092166020820152604081019190915260600190565b5f60208284031215615283575f5ffd5b5051919050565b805161529581614bfc565b919050565b5f61010082840312156152ab575f5ffd5b6152b3614d8c565b8251815260208084015190820152604080840151908201526060808401519082015260808301519091506152e681614bfc565b60808201526152f760a0830161528a565b60a082015261530860c0830161528a565b60c082015261531960e0830161528a565b60e082015292915050565b5f60408284031215615334575f5ffd5b61533c614daf565b82518152602083015190915061535181614bfc565b602082015292915050565b5f8183036102608112801561536f575f5ffd5b50615378614daf565b610220821215615386575f5ffd5b61538e614d6a565b604083121561539b575f5ffd5b6153a3614daf565b85516153ae81614bfc565b815260208601516153be81614bfc565b60208201528152603f19929092019160e08312156153da575f5ffd5b6153e2614daf565b60c08412156153ef575f5ffd5b6153f7614daf565b60a0851215615404575f5ffd5b61540c614d42565b9450604087015161541c81614bfc565b8552606087015161542c81614bfc565b6020860152608087015161543f81614bfc565b604086015260a087015161545281614bfc565b606086015260c0870151608086015284815261547060e0880161528a565b60208201528152615484610100870161528a565b60208201528060208301525061549e86610120870161529a565b604082015281526154b3856102208601615324565b6020820152949350505050565b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b6154f28185614f3d565b60c060a08201525f610b4d60c0830184866154c0565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561070a5761070a615508565b835181526020840151602082015260408401516040820152608060608201525f610b4d6080830184866154c0565b6001600160a01b03929092168252602082015260400190565b8181038181111561070a5761070a615508565b5f6001600160401b038211156155a1576155a1614d2e565b50601f01601f191660200190565b5f82601f8301126155be575f5ffd5b81356155d16155cc82615589565b614df3565b8181528460208386010111156155e5575f5ffd5b816020850160208301375f918101602001919091529392505050565b5f5f60408385031215615612575f5ffd5b82358015158114615621575f5ffd5b915060208301356001600160401b0381111561563b575f5ffd5b615647858286016155af565b9150509250929050565b6001600160a01b039390931683526020830191909152604082015260600190565b5f60208284031215615682575f5ffd5b81356001600160401b03811115615697575f5ffd5b61062a848285016155af565b602080825282518282018190525f918401906040840190835b818110156156da5783518352602093840193909201916001016156bc565b509095945050505050565b5f602082840312156156f5575f5ffd5b81516001600160401b0381111561570a575f5ffd5b8201601f8101841361571a575f5ffd5b80516001600160401b0381111561573357615733614d2e565b8060051b61574360208201614df3565b9182526020818401810192908101908784111561575e575f5ffd5b6020850194505b8385101561578457845180835260209586019590935090910190615765565b979650505050505050565b634e487b7160e01b5f52603260045260245ffd5b5f5f608083850312156157b4575f5ffd5b6157be84846150d2565b915060608301356001600160401b0381111561563b575f5ffd5b5f602082840312156157e8575f5ffd5b81516108f481614bfc565b5f60c0828403128015615804575f5ffd5b5061580d614dd1565b82518152602080840151908201526040808401519082015260608084015190820152608083015161583d81614c55565b608082015260a083015161585081614c55565b60a08201529392505050565b5f5f60c0838503121561586d575f5ffd5b6158778484614e23565b915060a08301356001600160401b0381111561563b575f5ffd5b6001600160a01b0386811682526001600160401b0386166020830152841660408201526060810183905260a0608082018190525f9061578490830184614ebf565b6001600160a01b039a8b168152988a1660208a015260408901979097529488166060880152608087019390935290861660a086015260c085015260e08401529092166101008201526101208101919091526101400190565b634e487b7160e01b5f52601260045260245ffd5b6159488185614f88565b60a08101929092526001600160a01b031660c082015261010060e082018190525f9082015261012001919050565b61012081016159858288614f88565b60a082019590955260c08101939093526001600160a01b0391821660e08401521661010090910152919050565b5f5f604083850312156159c3575f5ffd5b505080516020909101519092909150565b60a0810161070a8284614f88565b6159ec8186614f88565b60a081019390935260c08301919091526001600160a01b031660e082015261012061010082018190525f9082015261014001919050565b6101008101615a328287614f88565b60a08201949094526001600160a01b0392831660c0820152911660e090910152919050565b60018060a01b03845116815260018060a01b03602085015116602082015260018060a01b036040850151166040820152606084015160608201526080840151608082015260a084015160a082015260c084015160c082015260e084015160e08201526101406101008201525f615ad1610140830185614ebf565b8281036101208401526109778185614ebf565b84546001600160a01b03908116825260018601548116602083015260028601548116604083015260038601545f9116615b206060840182614f7b565b50600486015460808301528460a08301528360c0830152615b4460e0830184614f7b565b61012061010083015261097761012083015f815260200190565b80516001600160801b0381168114615295575f5ffd5b5f60c0828403128015615b85575f5ffd5b50615b8e614dd1565b615b9783615b5e565b8152615ba560208401615b5e565b6020820152615bb660408401615b5e565b6040820152615bc760608401615b5e565b6060820152615bd860808401615b5e565b608082015261585060a08401615b5e565b6101608101615bf88285614f88565b82516001600160801b0390811660a0848101919091526020850151821660c08501526040850151821660e085015260608501518216610100850152608085015182166101208501529093015190921661014090910152919050565b6001600160801b03818116838216019081111561070a5761070a615508565b8215158152604060208201525f61062a6040830184614ebf565b60018060a01b0384168152826020820152606060408201525f610b4d6060830184614ebf565b5f82601f830112615cc1575f5ffd5b8151615ccf6155cc82615589565b818152846020838601011115615ce3575f5ffd5b8160208501602083015e5f918101602001919091529392505050565b5f5f5f838503610140811215615d13575f5ffd5b610100811215615d21575f5ffd5b50615d2a614d8c565b8451615d3581614bfc565b8152615d436020860161528a565b6020820152615d546040860161528a565b6040820152606085810151908201526080808601519082015260a0808601519082015260c0808601519082015260e080860151908201526101008501519093506001600160401b03811115615da7575f5ffd5b615db386828701615cb2565b9250506101208401516001600160401b03811115615dcf575f5ffd5b615ddb86828701615cb2565b9150509250925092565b808202811582820484141761070a5761070a615508565b5f82615e1657634e487b7160e01b5f52601260045260245ffd5b50049056fea2646970667358221220e0c5f8ce1215dcb42c8ccf2a9521e55ad6e35780c888043ea572cb2fcb5f69f164736f6c634300081c0033000000000000000000000000c7eaefecbb57b7bca1292b6df285486c2873d143000000000000000000000000297612c171fc8adce32ac333085a9ee1f2bcc1da000000000000000000000000cd6863bb697d7cee5b7ed8dea7d803374f7e4aa6000000000000000000000000297612c171fc8adce32ac333085a9ee1f2bcc1da0000000000000000000000001cb453f8d5565643fb20f5d005454db88dc088be0000000000000000000000004f708c0ae7ded3d74736594c2109c2e3c065b4280000000000000000000000000000000000000000000000000bef55718ad60000000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc000000000000000000000000ab162c41ad27df8614edd43f886857bb2054c23e000000000000000000000000000000000000000000000000002386f26fc10000000000000000000000000000000000000000000000000000002386f26fc1000000000000000000000000000000000000000000000000000000000000000000780000000000000000000000000000000000000000000000006f05b59d3b200000000000000000000000000000cd6863bb697d7cee5b7ed8dea7d803374f7e4aa6000000000000000000000000f6f3c8ff7bac29e6a19f9fc1ca1826426f7e2866000000000000000000000000ab162c41ad27df8614edd43f886857bb2054c23e000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc0000000000000000000000005477b94198f12e4e5faab2c8d95b807c061797c5
Deployed Bytecode
0x60806040526004361061014a575f3560e01c8063985fe064116100ba578063985fe064146102f5578063a1bf28401461035f578063b0a322c41461037e578063b7f9b17c1461039d578063b8d19933146103bc578063be5ad555146103db578063c3f909d4146103fa578063c40832311461041b578063c9205df21461049a578063d542477014610522578063e3d670d71461014e578063eaded52c14610541578063eae0673c14610554578063f2fde38b14610567575f5ffd5b806312f3c34c1461014e57806320e3dbd4146101805780632869056b146101a1578063299e537e146101c0578063318ee870146101d357806341930337146101ff5780634d73e9ba1461022b57806354fd4d501461024a5780636881d8cb1461025e578063715018a61461027d57806378ca61ca1461029157806381e8bf0b146102b25780638da5cb5b146102d1575b5f5ffd5b348015610159575f5ffd5b5061016d610168366004614c10565b610586565b6040519081526020015b60405180910390f35b34801561018b575f5ffd5b5061019f61019a366004614c10565b610632565b005b3480156101ac575f5ffd5b5061016d6101bb366004614c2b565b6106fc565b61019f6101ce366004614ca6565b610710565b3480156101de575f5ffd5b506101f26101ed366004614e70565b6108cb565b6040516101779190614eed565b34801561020a575f5ffd5b5061021e610219366004614eff565b6108fb565b6040516101779190614f6d565b348015610236575f5ffd5b5061016d610245366004614c10565b61090e565b348015610255575f5ffd5b5061016d610981565b348015610269575f5ffd5b5061019f610278366004614c10565b610990565b348015610288575f5ffd5b5061019f610a40565b34801561029c575f5ffd5b506102a5610a53565b6040516101779190615049565b3480156102bd575f5ffd5b506101f26102cc36600461510b565b610aa9565b3480156102dc575f5ffd5b505f546001600160a01b03166040516101779190615141565b348015610300575f5ffd5b5061031461030f366004614c10565b610ac0565b60405161017791905f60c082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015292915050565b34801561036a575f5ffd5b5061016d610379366004614c10565b610ad1565b348015610389575f5ffd5b5061019f61039836600461516b565b610b56565b3480156103a8575f5ffd5b5061016d6103b7366004614c10565b610b79565b3480156103c7575f5ffd5b5061016d6103d6366004614c2b565b610cb9565b3480156103e6575f5ffd5b5061016d6103f5366004614c10565b610cc4565b348015610405575f5ffd5b5061040e610cce565b604051610177919061520f565b348015610426575f5ffd5b5061043a610435366004614c2b565b610d12565b60405161017791905f61010082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015260e083015160e083015292915050565b3480156104a5575f5ffd5b506104b96104b436600461521d565b610d24565b60405161017791905f61010082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c08301526001600160401b0360e08401511660e083015292915050565b34801561052d575f5ffd5b5061016d61053c366004614c10565b610d37565b61019f61054f36600461516b565b610d41565b61019f61056236600461516b565b610e04565b348015610572575f5ffd5b5061019f610581366004614c10565b610e91565b5f5f610590610ece565b90505f61059b610ef2565b6002810154600182015460048501549293506001600160a01b039182169263f35cc24e9291821691166105cd88610f16565b6040518463ffffffff1660e01b81526004016105eb9392919061524f565b602060405180830381865afa158015610606573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061062a9190615273565b949350505050565b7f77dfe5000ebf9e003c57377ca58618c48c4cbb3e849c5aac4b8be634c98fc800546001600160a01b0316300361067c57604051630782484160e21b815260040160405180910390fd5b5f816001600160a01b03166378ca61ca6040518163ffffffff1660e01b815260040161026060405180830381865afa1580156106ba573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106de919061535c565b90506106ed8160200151610fee565b80516106f890611027565b5050565b5f6107078383611086565b90505b92915050565b5f610719610ece565b60078101549091506001600160a01b0316331461074957604051630782484160e21b815260040160405180910390fd5b5f610752610ece565b604080516101008101825282548152600183015460208201526002830154918101919091526003820154606082015260048201546001600160a01b0390811660808301526005830154811660a08301526006830154811660c083015260079092015490911660e082015290505f6107c7610ef2565b6040805180820190915281546001600160a01b03908116825260e0850151166020820152909150610bb8196001600160401b038b1601610826575f5f61080d88886111cf565b9150915061081f8d8a8d8d85876111ea565b50506108ac565b610bb9196001600160401b038b1601610858575f610844878761140d565b90506108528c8a8a8461141b565b506108ac565b610bba196001600160401b038b1601610883575f610876878761140d565b90506108528c898361143c565b6040516331a2947960e11b81526001600160401b038b1660048201526024015b60405180910390fd5b6108be815f0151826020015189611478565b5050505050505050505050565b60608383836040516020016108e2939291906154e8565b60405160208183030381529060405290505b9392505050565b610903614a25565b61062a848484611540565b5f5f6109186115c1565b60058101546040805160a08101825283546001600160a01b03908116825260018501548116602083015260028501548116928201929092526003840154821660608201526004840154608082015292935016905f6109778383886115e5565b9695505050505050565b5f61098a611637565b54919050565b61099861165b565b6001600160a01b0381166109bf5760405163d92e233d60e01b815260040160405180910390fd5b5f6109c8611637565b600181810180546001600160a01b0319166001600160a01b03861617905581549192509082905f906109fb90849061551c565b909155505080546040517fec07f803439eafbb5e1976432b2a5907b419652cd86b296cebe5a6725363beaa91610a34913391869161524f565b60405180910390a15050565b610a4861165b565b610a515f611687565b565b610a5b614a4f565b5f610a646116d6565b90505f610a6f611637565b604080518082018252825481526001909201546001600160a01b031660208084019190915281518083019092529381529283015250919050565b60608383836040516020016108e29392919061552f565b610ac8614a85565b61070a826117b1565b5f5f610adb6115c1565b60058101546040805160a08101825283546001600160a01b0390811682526001850154811660208301526002850154811692820192909252600384015482166060820152600484015460808201529293501690610b4d610b3c8260a0902090565b6001600160a01b03841690876118e7565b95945050505050565b5f610b618383611993565b509050610b6e87826119c2565b505050505050505050565b5f5f610b83610ef2565b6040805160608101825282546001600160a01b0390811682526001840154811660208301526002909301549092169082015290505f610bc0610ece565b60408051610100810182528254815260018301546020808301919091526002840154828401526003840154606083015260048401546001600160a01b0390811660808401526005850154811660a08401526006850154811660c08401908152600790950154811660e08401528351808501909452935184168084528682015190941690830181905290935090919063c2d4eda090610c5d88610f16565b6040518363ffffffff1660e01b8152600401610c7a92919061555d565b602060405180830381865afa158015610c95573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b4d9190615273565b5f6107078383611aa4565b5f61070a82611bf0565b604080518082019091525f80825260208201525f610cea611637565b60408051808201909152815481526001909101546001600160a01b0316602082015292915050565b610d1a614ab5565b6107078383611cb7565b610d2c614af2565b61062a848484611ec3565b5f61070a82611ed8565b610d49611637565b600101546001600160a01b03163314610d7557604051630782484160e21b815260040160405180910390fd5b5f5f610d818484611993565b91509150610d8f88836119c2565b6103eb196001600160401b038a1601610db657610daf8a89898585611f04565b5050610dfa565b6103e8196001600160401b038a1601610dd657610daf8a8989858561214b565b6040516331a2947960e11b81526001600160401b038a1660048201526024016108a3565b5050505050505050565b610e0c611637565b600101546001600160a01b03163314610e3857604051630782484160e21b815260040160405180910390fd5b5f5f610e4484846123c5565b91509150610e528883612400565b6107d0196001600160401b038a1601610e7257610daf8a88878585612462565b6107d9196001600160401b038a1601610dd657610daf8a868484612888565b610e9961165b565b6001600160a01b038116610ec2575f604051631e4fbdf760e01b81526004016108a39190615141565b610ecb81611687565b50565b7f7b4a7240fdadb5a1d32a369adb1b782af3728c5ec7e87b32ade3ba494bab7b0090565b7fa2cb2ed7d820b5d5e467fcfe3a5dc1cfa81ba017c457bb1d2da9519a43ed1f0090565b5f5f610f20610ef2565b6002810154600182015482549293506001600160a01b039182169290821691165f610f4a87610ad1565b90505f610f568861090e565b90505f856001600160a01b031663f35cc24e8587856040518463ffffffff1660e01b8152600401610f899392919061524f565b602060405180830381865afa158015610fa4573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fc89190615273565b9050808311610fd7575f610fe1565b610fe18184615576565b9998505050505050505050565b5f610ff7611637565b82518155602090920151600190920180546001600160a01b0319166001600160a01b039093169290921790915550565b6110348160200151612ca7565b6110418160400151612dbf565b5f61104a612f2e565b9151805183546001600160a01b03199081166001600160a01b039283161785556020909201516001909401805490921693169290921790915550565b5f5f6110906115c1565b60058101546040805160a08101825283546001600160a01b03908116825260018501548116602080840191909152600286015482168385018190526003870154831660608501526004808801546080860152855163501ad8ff60e11b81529551979850929095169592945f94909363a035b1fe9382810193928290030181865afa158015611120573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111449190615273565b90505f6111666111558460a0902090565b6001600160a01b038616908a6118e7565b90505f61117d6001600160a01b038616858b6115e5565b90505f61119983856a0c097ce7bc90715b34b9f160241b612f52565b90505f6111b3828760800151670de0b6b3a7640000612f52565b90506111c0838b83612f52565b9b9a5050505050505050505050565b5f60606111de83850185615601565b915091505b9250929050565b5f6111f3610ece565b60408051610100810182528254815260018301546020820152600283015481830152600383015460608083019190915260048401546001600160a01b0390811660808401526005850154811660a084018190526006860154821660c08501526007909501541660e0830152825190810190925292505f90808981526020015f81526020015f815250905082608001516001600160a01b0316876001600160a01b0316036112dd576112b48988835f0151896112ae919061551c565b5f613002565b6020820181905281516112d3919088906112ce908261551c565b612f52565b604082015261131d565b6112e98988885f613002565b60208201819052604082015260808301518151611308918b915f613002565b81602001818151611319919061551c565b9052505b61132c8982602001518a613170565b50508315610b6e57604080820151905162af986360e01b81526001600160a01b0384169162af986391611366918d918d9190600401615651565b5f604051808303815f87803b15801561137d575f5ffd5b505af115801561138f573d5f5f3e3d5ffd5b50505050816001600160a01b031662af98638a5f846040015185602001516113b79190615576565b6040518463ffffffff1660e01b81526004016113d593929190615651565b5f604051808303815f87803b1580156113ec575f5ffd5b505af11580156113fe573d5f5f3e3d5ffd5b50505050505050505050505050565b606061070782840184615672565b611427848484876132e3565b505061143584848484613505565b5050505050565b5f61144684610ad1565b90505f6114548585876135de565b905061146285835f886132e3565b505061147085838386613505565b505050505050565b5f836001600160a01b031663095ea7b3848460405160240161149b92919061555d565b604051602081830303815290604052915060e01b6020820180516001600160e01b03838183161783525050505090506114d4848261373a565b61153a5761153084856001600160a01b031663095ea7b3865f6040516024016114fe92919061555d565b604051602081830303815290604052915060e01b6020820180516001600160e01b03838183161783525050505061377f565b61153a848261377f565b50505050565b611548614a25565b5f61155285611bf0565b90505f61155e86610ad1565b90505f61156a8761090e565b90505f61157a87878486886137e2565b9050611584614a25565b81518152608080830151604080840191909152606080850151602085015260c0850151908401529092015191810191909152979650505050505050565b7ffa8cd390214ee76f5bb8c7ea1b63ea1107ccbd7e4761fc37eee715526196710090565b5f5f6115f28460a0902090565b90505f6116096001600160a01b0387168386613afb565b90505f5f6116178888613ba8565b909450925061162b91508490508383613e23565b98975050505050505050565b7ff65cb96943ab62245d9268299b185bd2de6ad06e4548b70ef169cd307ee3ae0090565b5f546001600160a01b03163314610a51573360405163118cdaa760e01b81526004016108a39190615141565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6116de614b38565b5f6116e7613e47565b90505f6116f2612f2e565b6040805180820190915281546001600160a01b039081168252600190920154909116602082015290505f611724610ece565b6040805161010081018252825481526001830154602080830191909152600284015482840152600384015460608084019190915260048501546001600160a01b0390811660808501526005860154811660a08501526006860154811660c085015260079095015490941660e083015282519384018352948352938201949094529283019190915250919050565b6117b9614a85565b5f6117c2610ece565b6040805161010081018252825481526001830154602082015260028301549181018290526003830154606082015260048301546001600160a01b0390811660808301526005840154811660a08301526006840154811660c083015260079093015490921660e08301529091505f6118388561090e565b90505f61184486610ad1565b90505f604051806060016040528061185b84613ee2565b81526020015f81526020015f8152509050611878815f0151613eec565b6020820181905283111561189f5760405163ce07f32960e01b815260040160405180910390fd5b8281602001516118af9190615576565b8652606086018290526118c183613f13565b6040870152608086018390526118d7844261551c565b60a0870152509395945050505050565b5f5f6118fb6118f68585613f3b565b613fa5565b90506080856001600160a01b0316637784c685836040518263ffffffff1660e01b815260040161192b91906156a3565b5f60405180830381865afa158015611945573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261196c91908101906156e5565b5f8151811061197d5761197d61578f565b6020026020010151901c5f1c9150509392505050565b6119b460405180606001604052805f81526020015f81526020015f81525090565b60606111de838501856157a3565b5f6119cb612f2e565b60018101549091506001600160a01b03848116911614801590611a755750806001015f9054906101000a90046001600160a01b03166001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a3b573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a5f91906157d8565b6001600160a01b0316836001600160a01b031614155b15611a95578260405163961c9a4f60e01b81526004016108a39190615141565b611a9f8383613fee565b505050565b5f5f611aae612f2e565b60018101549091506001600160a01b0390811690851603611ad2578291505061070a565b806001015f9054906101000a90046001600160a01b03166001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b24573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b4891906157d8565b6001600160a01b0316846001600160a01b031603611bd557600181015460405163ef8b30f760e01b8152600481018590526001600160a01b039091169063ef8b30f790602401602060405180830381865afa158015611ba9573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611bcd9190615273565b91505061070a565b8360405163961c9a4f60e01b81526004016108a39190615141565b5f5f611bfa610ece565b60058101546040516315d8faf960e11b81526001600160a01b0386811660048301525f6024830181905293945090911691908290632bb1f5f29060440160c060405180830381865afa158015611c52573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c7691906157f3565b905080602001515f03611c9c576040516347d960dd60e11b815260040160405180910390fd5b610b4d8160600151670de0b6b3a76400008360200151612f52565b611cbf614ab5565b5f611cc8610ece565b604080516101008101825282548152600183015460208201526002830154918101919091526003820154606082015260048201546001600160a01b0390811660808301526005830154811660a08301526006830154811660c083015260079092015490911660e08201529050670de0b6b3a7640000611d4685611bf0565b03611d775760608201839052611d5b83613ee2565b82526040810151611d6c904261551c565b60c08301525061070a565b5f611d818561090e565b90505f611d8d86610ad1565b9050611dbc6040518060a001604052805f81526020015f81526020015f81526020015f81526020015f81525090565b611dc7868484614010565b6020830152808252821015611def576040516329d8bc6560e01b815260040160405180910390fd5b8051611dfa90613ee2565b60408201819052611e0a90613eec565b6060820181905260208201511115611e3557604051637640d81960e11b815260040160405180910390fd5b6020810151611e449084615576565b8151909350611e539083615576565b9150611e68670de0b6b3a7640000838561416f565b60e086015260208101516060820151611e819190615576565b85528051608086018190526060860152602081018051604080880191909152905160a0870152840151611eb4904261551c565b60c08601525050505092915050565b611ecb614af2565b61062a84845f5f866137e2565b5f5f611ee38361090e565b90505f611eef84610ad1565b9050611efa8261426b565b61062a9082615576565b5f611f0d610ece565b604080516101008101825282548152600183015460208201526002830154918101919091526003820154606082015260048201546001600160a01b0390811660808301526005830154811660a08301526006830154811660c083015260079092015490911660e082015290505f611f82610ef2565b604080516060808201835283546001600160a01b0390811683526001808601548216602080860191825260029097015483168587015285518085018752855184168152905183168188015260a0808a0151841682880152865160c0810188528f85168152938e16848901528387018d9052968b015193830193909352938901516080820152938401929092529250905f9061201d90866142e4565b905081604001516001600160a01b03166303004b47826020015183604001516040518363ffffffff1660e01b8152600401612062929190918252602082015260400190565b5f604051808303815f87803b158015612079575f5ffd5b505af115801561208b573d5f5f3e3d5ffd5b505050507f379b944cc5e5dcecb69673a04f085f89a235716bdf4faff51ef6cda15b06063089825f01518a8a86602001515f8760200151895f01515f8a604001516040516121389a999897969594939291906001600160a01b039a8b168152602081019990995296891660408901526060880195909552928716608087015260a086019190915260c085015290931660e08301526101008201929092526101208101919091526101400190565b60405180910390a1505050505050505050565b5f612154610ece565b604080516101008101825282548152600183015460208201526002830154918101919091526003820154606082015260048201546001600160a01b0390811660808301526005830154811660a08301526006830154811660c083015260079092015490911660e082015290505f6121c9610ef2565b604080516060808201835283546001600160a01b039081168352600185015481166020808501918252600290960154821684860152845192830185528351821683525181169482019490945260a086015190931683830152815180830190925292505f90806122378b610ad1565b81526020016122458b61090e565b81525090505f61229d6040518060c001604052808c6001600160a01b031681526020018b6001600160a01b031681526020018a815260200189602001518152602001896040015181526020015f1515815250876142e4565b905082604001516001600160a01b03166303004b47826020015183604001516040518363ffffffff1660e01b81526004016122e2929190918252602082015260400190565b5f604051808303815f87803b1580156122f9575f5ffd5b505af115801561230b573d5f5f3e3d5ffd5b505050507fb6f3b90a749b43aed5c7575dfceb3dc53de99cc166c0091ce9079bcfa92204198a8a8a8660200151865f01518660200151895f0151896020015189604001516040516123b1999897969594939291906001600160a01b03998a168152978916602089015260408801969096529387166060870152608086019290925260a085015290931660c083015260e08201929092526101008101919091526101200190565b60405180910390a150505050505050505050565b6123f26040518060a001604052805f81526020015f81526020015f81526020015f81526020015f81525090565b60606111de8385018561585c565b5f612409610ef2565b60018101549091506001600160a01b039081169084168114612440578360405163961c9a4f60e01b81526004016108a39190615141565b825142111561153a5760405163559895a360e01b815260040160405180910390fd5b5f61246b610ece565b604080516101008101825282548152600183015460208201526002830154918101919091526003820154606082015260048201546001600160a01b0390811660808301526005830154811660a08301526006830154811660c083015260079092015490911660e082015290505f6124e0610ef2565b604080516060808201835283546001600160a01b039081168352600185015481166020808501918252600290960154821684860152845160808082018752855184168252915183169681019690965287015181169385019390935260a08601519092169183019190915291505f6125568961090e565b90505f6125628a610ad1565b90505f8a610bba5f8a604001518a6040516020016125809190614eed565b60408051601f19818403018152908290526125a19594939291602001615891565b60408051601f198184030181528282019091525f808352602083015291506020890151156126da576125d7896020015183614452565b84604001516001600160a01b03166370a082318d6040518263ffffffff1660e01b81526004016126079190615141565b602060405180830381865afa158015612622573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906126469190615273565b8152604085015185516001600160a01b039081169116146126d55784516040516370a0823160e01b81526001600160a01b03909116906370a0823190612690908f90600401615141565b602060405180830381865afa1580156126ab573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906126cf9190615273565b60208201525b6126e8565b6126e58c8c8a6144db565b81525b60608901518151101561270e57604051638199f5f360e01b815260040160405180910390fd5b88608001518160200151101561273757604051638199f5f360e01b815260040160405180910390fd5b60408501516127549061274d60208d018d614c10565b83516144f8565b84604001516001600160a01b0316855f01516001600160a01b0316146127915784516127919061278760208d018d614c10565b83602001516144f8565b84606001516001600160a01b031663bef26de06127ad8e610ad1565b6127b79086615576565b6127c08f61090e565b6127ca9088615576565b6040516001600160e01b031960e085901b168152600481019290925260248201526044015f604051808303815f87803b158015612805575f5ffd5b505af1158015612817573d5f5f3e3d5ffd5b505050507f752b07e36bcb434ad5d933fe9d5b99988d8314bc6d350ef03b996714cfb97e3d8c86602001518d8860200151878a5f01518a88602001518d604001518a5f01516040516128729a999897969594939291906158d2565b60405180910390a1505050505050505050505050565b5f612891610ece565b604080516101008101825282548152600183015460208201526002830154918101919091526003820154606082015260048201546001600160a01b0390811660808301526005830154811660a08301526006830154811660c083015260079092015490911660e082015290505f612906610ef2565b604080516060808201835283546001600160a01b039081168352600185015481166020808501918252600290960154821684860152845160808082018752855184168252915183169681019690965287015181169385019390935260a08601519092169183019190915291505f61297c8861090e565b90505f61298889610ad1565b90505f89610bbb5f8a604001518a6040516020016129a69190614eed565b60408051601f19818403018152908290526129c79594939291602001615891565b60408051601f198184030181528282019091525f808352602083015291508315612af8576129f58483614452565b84604001516001600160a01b03166370a082318c6040518263ffffffff1660e01b8152600401612a259190615141565b602060405180830381865afa158015612a40573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612a649190615273565b8152604085015185516001600160a01b03908116911614612af35784516040516370a0823160e01b81526001600160a01b03909116906370a0823190612aae908e90600401615141565b602060405180830381865afa158015612ac9573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612aed9190615273565b60208201525b612b06565b612b038b848a6144db565b81525b606089015181511015612b2c57604051638199f5f360e01b815260040160405180910390fd5b886080015181602001511015612b5557604051638199f5f360e01b815260040160405180910390fd5b5f612b5f8c61090e565b1180612b7257505f612b708c610ad1565b115b15612b905760405163ce07f32960e01b815260040160405180910390fd5b6040850151612ba69061274d60208d018d614c10565b84604001516001600160a01b0316855f01516001600160a01b031614612bd9578451612bd99061278760208d018d614c10565b60608501516040516305f7936f60e51b815260048101859052602481018690526001600160a01b039091169063bef26de0906044015f604051808303815f87803b158015612c25575f5ffd5b505af1158015612c37573d5f5f3e3d5ffd5b505050507f22b4f0c8d32b8805fe1a159b4bc68f4fb1047c443cb81736313981230ab103068b86602001515f8860200151878a5f01518a88602001518d604001518a5f0151604051612c929a999897969594939291906158d2565b60405180910390a15050505050505050505050565b5f612cb06115c1565b8251602001519091506001600160a01b0316612cdf5760405163d92e233d60e01b815260040160405180910390fd5b60208201516001600160a01b0316612d0a5760405163d92e233d60e01b815260040160405180910390fd5b81518051805183546001600160a01b03199081166001600160a01b039283161785556020808401516001870180548416918516919091179055604080850151600288018054851691861691909117905560608086015160038901805486169187169190911790556080909501516004880155948101516005870180549093169084161790915583519283018452855151518216835285515181015182168382015285015116918101919091526106f89061451e565b670de0b6b3a764000081606001511015612dec57604051631ca8aa2560e11b815260040160405180910390fd5b60808101516001600160a01b0316612e175760405163d92e233d60e01b815260040160405180910390fd5b60e08101516001600160a01b0316612e425760405163d92e233d60e01b815260040160405180910390fd5b60c08101516001600160a01b0316612e6d5760405163d92e233d60e01b815260040160405180910390fd5b60a08101516001600160a01b0316612e985760405163d92e233d60e01b815260040160405180910390fd5b5f612ea1610ece565b8251815560208301516001820155604083015160028201556060830151600382015560808301516004820180546001600160a01b03199081166001600160a01b039384161790915560e0850151600784018054831691841691909117905560a0850151600584018054831691841691909117905560c0909401516006909201805490941691161790915550565b7f0fe9e9f123d1aa01efa0fffed6d343d93a178788b8b649377f34007145c3670090565b5f5f5f612f5f86866145f3565b91509150815f03612f8357838181612f7957612f7961592a565b04925050506108f4565b818411612f9a57612f9a600385150260111861460f565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010185841190960395909502919093039390930492909217029150509392505050565b5f5f61300c612f2e565b9050806001015f9054906101000a90046001600160a01b03166001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613060573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061308491906157d8565b6001600160a01b0316856001600160a01b0316036131345760018101546130b69086906001600160a01b031686611478565b6001810154604051636e553f6560e01b8152600481018690526001600160a01b03888116602483015290911690636e553f65906044016020604051808303815f875af1158015613108573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061312c9190615273565b91505061062a565b60018101546001600160a01b0390811690861603613155578391505061062a565b8460405163961c9a4f60e01b81526004016108a39190615141565b5f5f5f61317b6115c1565b90505f613186610ef2565b60058301546040805160a08101825285546001600160a01b039081168252600187015481166020830152600287015481169282019290925260038601548216606082015260048601546080820152929350169087156132575760018301546001600160a01b03166131f881848b611478565b60405163238d657960e01b81526001600160a01b0384169063238d6579906132289085908d908f9060040161593e565b5f604051808303815f87803b15801561323f575f5ffd5b505af1158015613251573d5f5f3e3d5ffd5b50505050505b5f87156132d557826001600160a01b03166350d8cd4b838a5f8e8f6040518663ffffffff1660e01b8152600401613292959493929190615976565b60408051808303815f875af11580156132ad573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906132d191906159b2565b5090505b979997985050505050505050565b5f5f5f6132ee6115c1565b90505f6132f9610ef2565b604080516060808201835260058601546001600160a01b039081168352835160a08101855287548216815260018801548216602082810191909152600289015483168287015260038901548316938201939093526004808901546080830152928401819052855482168486015283519451630a8e0d6f60e11b8152959650929493169263151c1ade9261338e929091016159d4565b5f604051808303815f87803b1580156133a5575f5ffd5b505af11580156133b7573d5f5f3e3d5ffd5b505f9250508815905061348c57602082015182515f916133e1916001600160a01b0316908d6115e5565b90508089106133fc576133f58b8a8a6135de565b915061348a565b61340e8360400151845f01518b611478565b825f01516001600160a01b03166320b76e8184602001518b5f8f6040518563ffffffff1660e01b815260040161344794939291906159e2565b60408051808303815f875af1158015613462573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061348691906159b2565b5091505b505b88156132d55781516020830151604051638720316d60e01b81526001600160a01b0390921691638720316d916134ca918d908f908190600401615a23565b5f604051808303815f87803b1580156134e1575f5ffd5b505af11580156134f3573d5f5f3e3d5ffd5b50505050979997985050505050505050565b5f835f0361351457505f61062a565b5f61351d612f2e565b80549091506001600160a01b03165f808061353787614620565b925092509250613547838961469f565b6001850154613560906001600160a01b0316858b611478565b6040516338a0e33160e01b81526001600160a01b038516906338a0e3319061359090869086908690600401615a57565b6020604051808303815f875af11580156135ac573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906135d09190615273565b9a9950505050505050505050565b5f5f6135e86115c1565b90505f6135f3610ef2565b805460058401549192506001600160a01b03908116916136169183911688611478565b6040805160a0808201835285546001600160a01b03908116835260018701548116602084015260028701548116938301939093526003860154909216606082015260048501546080820152205f9061367d9060058601546001600160a01b0316908a613afb565b60058501546040516320b76e8160e01b81529192506001600160a01b0316906320b76e81906136b69087905f9086908e90600401615ae4565b60408051808303815f875af11580156136d1573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906136f591906159b2565b5060058501549095506137139083906001600160a01b03165f611478565b8487111561372f5761372f828761372a888b615576565b6144f8565b505050509392505050565b5f5f5f5f60205f8651602088015f8a5af192503d91505f5190508280156109775750811561376b5780600114610977565b50505050506001600160a01b03163b151590565b5f5f60205f8451602086015f885af18061379e576040513d5f823e3d81fd5b50505f513d915081156137b55780600114156137c2565b6001600160a01b0384163b155b1561153a5783604051635274afe760e01b81526004016108a39190615141565b6137ea614af2565b5f6137f3610ece565b604080516101008101825282548152600183015460208201526002830154918101919091526003820154606082015260048201546001600160a01b0390811660808301526005830154811660a08301526006830154811660c083015260079092015490911660e082015290505f613868610ef2565b604080516060808201835283546001600160a01b03908116835260018501548116602080850191909152600290950154811683850152835160808101855260c088015182168152878301519581019590955286840151938501939093528151909216918301919091529150670de0b6b3a76400008510806138ec5750806020015185115b1561390a57604051631ca8aa2560e11b815260040160405180910390fd5b613912614af2565b670de0b6b3a7640000860361395a57670de0b6b3a764000060208201526139398a8a611aa4565b8152604082015161394a904261551c565b60c08201529350610b4d92505050565b815160608301516040516379ae612760e11b81525f926001600160a01b03169163f35cc24e91613990918f918f9060040161524f565b602060405180830381865afa1580156139ab573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906139cf9190615273565b90505f6139f6826139e8670de0b6b3a76400008b615576565b670de0b6b3a7640000612f52565b90505f6040518060a00160405280848152602001838152602001613a1a8f8f611aa4565b81526020015f81526020015f8152509050613a38816020015161426b565b606082018190526040820151613a4e919061551c565b608082018190525f90613a61908c61551c565b905081602001518c613a73919061551c565b9b505f613a89670de0b6b3a7640000838f61416f565b9050613aa68360800151670de0b6b3a76400008560400151612f52565b60208701525f60e0870181905260a0870152604080870182905260808401518752870151613ad4904261551c565b60c087015250506020018051606085015251608084015250909a9950505050505050505050565b5f5f613b0a6118f68585613f3b565b604051637784c68560e01b81529091506001600160a01b03861690637784c68590613b399084906004016156a3565b5f60405180830381865afa158015613b53573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052613b7a91908101906156e5565b5f81518110613b8b57613b8b61578f565b60200260200101515f1c6001600160801b03169150509392505050565b5f5f5f5f5f613bb88660a0902090565b604051632e3071cd60e11b8152600481018290529091505f906001600160a01b03891690635c60e39a9060240160c060405180830381865afa158015613c00573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613c249190615b74565b90505f81608001516001600160801b031642613c409190615576565b90508015801590613c5d575060408201516001600160801b031615155b8015613c75575060608801516001600160a01b031615155b15613def576060880151604051638c00bf6b60e01b81525f916001600160a01b031690638c00bf6b90613cae908c908790600401615be9565b602060405180830381865afa158015613cc9573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ced9190615273565b90505f613d11613cfd83856147b0565b60408601516001600160801b03169061480e565b9050613d1c81614822565b84604001818151613d2d9190615c53565b6001600160801b0316905250613d4281614822565b84518590613d51908390615c53565b6001600160801b0390811690915260a086015116159050613dec575f613d8d8560a001516001600160801b03168361480e90919063ffffffff16565b90505f613dc182875f01516001600160801b0316613dab9190615576565b60208801518491906001600160801b031661487e565b9050613dcc81614822565b86602001818151613ddd9190615c53565b6001600160801b031690525050505b50505b508051602082015160408301516060909301516001600160801b039283169b9183169a509282169850911695509350505050565b5f61062a613e3260018561551c565b613e3f620f42408561551c565b8691906148a2565b613e4f614ba7565b5f613e586115c1565b6040805160e08101825282546001600160a01b039081169282019283526001840154811660608301526002840154811660808301526003840154811660a0830152600484015460c083015291815260059092015416602082015290505f613ebd610ef2565b60020154604080518082019091529283526001600160a01b0316602083015250919050565b5f61070a826148cd565b5f5f613ef6610ece565b90506108f483825f0154670de0b6b3a76400006139e89190615576565b5f5f613f1d610ece565b90506108f4838260010154670de0b6b3a76400006139e8919061551c565b5f600182846002604051602001613f5c929190918252602082015260400190565b60405160208183030381529060405280519060200120604051602001613f8392919061555d565b604051602081830303815290604052805190602001205f1c610707919061551c565b6040805160018082528183019092526060915f91906020808301908036833701905050905082815f81518110613fdd57613fdd61578f565b602090810291909101015292915050565b80514211156106f85760405163559895a360e01b815260040160405180910390fd5b5f5f845f03614032576040516347d960dd60e11b815260040160405180910390fd5b5f6040518060600160405280614047886148cd565b8152602001614055866148cd565b81526020015f815250905080602001515f03614084576040516347d960dd60e11b815260040160405180910390fd5b61409b85670de0b6b3a76400008360200151612f52565b60408201819052670de0b6b3a7640000116140ef5760405162461bcd60e51b81526020600482015260146024820152735269736b20526174696f2065786365656473203160601b60448201526064016108a3565b8051604082015161410d91906112ce81670de0b6b3a7640000615576565b91506141188261426b565b614122908761551c565b92508482111561414557604051637640d81960e11b815260040160405180910390fd5b83831115614166576040516329d8bc6560e01b815260040160405180910390fd5b50935093915050565b5f5f6141796115c1565b6040805160a08101825282546001600160a01b0390811682526001840154811660208084019190915260028501548216838501819052600386015490921660608401526004808601546080850152845163501ad8ff60e11b81529451959650929491935f93859363a035b1fe93838301939092908290030181865afa158015614204573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906142289190615273565b90505f61424488836a0c097ce7bc90715b34b9f160241b612f52565b90505f61425e828660800151670de0b6b3a7640000612f52565b90506135d0888b83612f52565b5f5f614275612f2e565b600181015460405163ef8b30f760e01b8152600481018690529192506001600160a01b03169063ef8b30f7906024015b602060405180830381865afa1580156142c0573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108f49190615273565b61430560405180606001604052805f81526020015f81526020015f81525090565b5f614312845f0151610ad1565b90508360a00151801561432457505f81115b1561434257604051630d66e4af60e21b815260040160405180910390fd5b5f845f0151610bb9866020015187604001518860a001518860405160200161436b929190615c72565b60408051601f198184030181529082905261438c9594939291602001615891565b60405160208183030381529060405290505f856060015111156143bc576143b7856060015182614452565b6143d9565b6143d7855f0151866020015187604001518860a0015161490b565b505b5f6143e6865f0151611bf0565b90505f836143f6885f0151610ad1565b6144009190615576565b9050866080015181101561442757604051638199f5f360e01b815260040160405180910390fd5b6040518060600160405280838152602001828152602001886060015181525094505050505092915050565b5f61445b6115c1565b90505f614466610ef2565b6005830154815460405163701195a160e11b81529293506001600160a01b0391821692911690829063e0232b42906144a69084908a908a90600401615c8c565b5f604051808303815f87803b1580156144bd575f5ffd5b505af11580156144cf573d5f5f3e3d5ffd5b50505050505050505050565b5f5f6144e985855f886132e3565b509050610b4d85825f86614a0c565b611a9f83846001600160a01b031663a9059cbb85856040516024016114fe92919061555d565b5f614527610ef2565b82519091506001600160a01b03166145525760405163d92e233d60e01b815260040160405180910390fd5b60208201516001600160a01b031661457d5760405163d92e233d60e01b815260040160405180910390fd5b60408201516001600160a01b03166145a85760405163d92e233d60e01b815260040160405180910390fd5b815181546001600160a01b03199081166001600160a01b0392831617835560208401516001840180548316918416919091179055604090930151600290920180549093169116179055565b5f805f1983850993909202808410938190039390930393915050565b634e487b715f52806020526024601cfd5b61467b6040518061010001604052805f6001600160a01b031681526020015f6001600160a01b031681526020015f6001600160a01b031681526020015f81526020015f81526020015f81526020015f81526020015f81525090565b606080838060200190518101906146929190615cff565b9250925092509193909250565b5f6146a8612f2e565b600181015460208501519192506001600160a01b039182169116146146e057604051635037072d60e01b815260040160405180910390fd5b806001015f9054906101000a90046001600160a01b03166001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015614732573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061475691906157d8565b6001600160a01b031683604001516001600160a01b03161461478b57604051635037072d60e01b815260040160405180910390fd5b8183608001511015611a9f57604051635037072d60e01b815260040160405180910390fd5b5f806147bc8385615de5565b90505f6147dc82806147d7670de0b6b3a76400006002615de5565b614a19565b90505f6147f782846147d7670de0b6b3a76400006003615de5565b905080614804838561551c565b610977919061551c565b5f6107078383670de0b6b3a7640000614a19565b6040805180820190915260148152731b585e081d5a5b9d0c4c8e08195e18d95959195960621b60208201525f906001600160801b038311156148775760405162461bcd60e51b81526004016108a39190614eed565b5090919050565b5f61062a61488f620f42408461551c565b61489a60018661551c565b869190614a19565b5f816148af600182615576565b6148b98587615de5565b6148c3919061551c565b61062a9190615dfc565b5f5f6148d7612f2e565b600181015460405163266d6a8360e11b8152600481018690529192506001600160a01b031690634cdad506906024016142a5565b5f5f614915610ece565b604080516101008101825282548152600183015460208201526002830154918101919091526003820154606082015260048201546001600160a01b0390811660808301526005830154811660a083018190526006840154821660c08401526007909301541660e082015291505f61498e88888884613002565b90505f61499c89835f613170565b509050851561162b5760405162af986360e01b81526001600160a01b0384169062af9863906149d3908c905f908790600401615651565b5f604051808303815f87803b1580156149ea575f5ffd5b505af11580156149fc573d5f5f3e3d5ffd5b5050505098975050505050505050565b5f610b4d85858585613505565b5f816148c38486615de5565b6040518060a001604052805f81526020015f81526020015f81526020015f81526020015f81525090565b6040518060400160405280614a62614b38565b8152602001614a80604080518082019091525f808252602082015290565b905290565b6040518060c001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b6040518061010001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b6040518061010001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f6001600160401b031681525090565b6040805160a081019091525f606082018181526080830191909152815260208101614b61614ba7565b815260408051610100810182525f8082526020828101829052928201819052606082018190526080820181905260a0820181905260c0820181905260e082015291015290565b6040518060400160405280614bba614bc6565b81525f60209091015290565b6040805160e0810182525f918101828152606082018390526080820183905260a0820183905260c0820192909252908190614bba565b6001600160a01b0381168114610ecb575f5ffd5b5f60208284031215614c20575f5ffd5b81356108f481614bfc565b5f5f60408385031215614c3c575f5ffd5b8235614c4781614bfc565b946020939093013593505050565b6001600160401b0381168114610ecb575f5ffd5b5f5f83601f840112614c79575f5ffd5b5081356001600160401b03811115614c8f575f5ffd5b6020830191508360208285010111156111e3575f5ffd5b5f5f5f5f5f5f5f60c0888a031215614cbc575f5ffd5b8735614cc781614bfc565b96506020880135614cd781614c55565b95506040880135614ce781614bfc565b9450606088013593506080880135925060a08801356001600160401b03811115614d0f575f5ffd5b614d1b8a828b01614c69565b989b979a50959850939692959293505050565b634e487b7160e01b5f52604160045260245ffd5b60405160a081016001600160401b0381118282101715614d6457614d64614d2e565b60405290565b604051606081016001600160401b0381118282101715614d6457614d64614d2e565b60405161010081016001600160401b0381118282101715614d6457614d64614d2e565b604080519081016001600160401b0381118282101715614d6457614d64614d2e565b60405160c081016001600160401b0381118282101715614d6457614d64614d2e565b604051601f8201601f191681016001600160401b0381118282101715614e1b57614e1b614d2e565b604052919050565b5f60a08284031215614e33575f5ffd5b614e3b614d42565b823581526020808401359082015260408084013590820152606080840135908201526080928301359281019290925250919050565b5f5f5f60c08486031215614e82575f5ffd5b614e8c8585614e23565b925060a08401356001600160401b03811115614ea6575f5ffd5b614eb286828701614c69565b9497909650939450505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f6107076020830184614ebf565b5f5f5f60608486031215614f11575f5ffd5b8335614f1c81614bfc565b92506020840135614f2c81614bfc565b929592945050506040919091013590565b80518252602081015160208301526040810151604083015260608101516060830152608081015160808301525050565b60a0810161070a8284614f3d565b6001600160a01b03169052565b80516001600160a01b03908116835260208083015182169084015260408083015182169084015260608083015190911690830152608090810151910152565b8051825260208101516020830152604081015160408301526060810151606083015260018060a01b03608082015116608083015260018060a01b0360a08201511660a083015260018060a01b0360c08201511660c083015260e0810151611a9f60e0840182614f7b565b805182526020908101516001600160a01b0316910152565b8151805180516001600160a01b039081168452602091820151168184015281015180518051610260850193929190615085906040870190614f88565b6020908101516001600160a01b0390811660e087015291015116610100840152604001516150b7610120840182614fc7565b5060208301516150cb610220840182615031565b5092915050565b5f606082840312156150e2575f5ffd5b6150ea614d6a565b82358152602080840135908201526040928301359281019290925250919050565b5f5f5f6080848603121561511d575f5ffd5b61512785856150d2565b925060608401356001600160401b03811115614ea6575f5ffd5b6001600160a01b0391909116815260200190565b5f60a08284031215615165575f5ffd5b50919050565b5f5f5f5f5f5f5f5f6101e0898b031215615183575f5ffd5b883561518e81614bfc565b9750602089013561519e81614c55565b965060408901356151ae81614bfc565b9550606089013594506151c48a60808b01615155565b93506151d48a6101208b01615155565b92506101c08901356001600160401b038111156151ef575f5ffd5b6151fb8b828c01614c69565b999c989b5096995094979396929594505050565b6040810161070a8284615031565b5f5f5f6060848603121561522f575f5ffd5b833561523a81614bfc565b95602085013595506040909401359392505050565b6001600160a01b039384168152919092166020820152604081019190915260600190565b5f60208284031215615283575f5ffd5b5051919050565b805161529581614bfc565b919050565b5f61010082840312156152ab575f5ffd5b6152b3614d8c565b8251815260208084015190820152604080840151908201526060808401519082015260808301519091506152e681614bfc565b60808201526152f760a0830161528a565b60a082015261530860c0830161528a565b60c082015261531960e0830161528a565b60e082015292915050565b5f60408284031215615334575f5ffd5b61533c614daf565b82518152602083015190915061535181614bfc565b602082015292915050565b5f8183036102608112801561536f575f5ffd5b50615378614daf565b610220821215615386575f5ffd5b61538e614d6a565b604083121561539b575f5ffd5b6153a3614daf565b85516153ae81614bfc565b815260208601516153be81614bfc565b60208201528152603f19929092019160e08312156153da575f5ffd5b6153e2614daf565b60c08412156153ef575f5ffd5b6153f7614daf565b60a0851215615404575f5ffd5b61540c614d42565b9450604087015161541c81614bfc565b8552606087015161542c81614bfc565b6020860152608087015161543f81614bfc565b604086015260a087015161545281614bfc565b606086015260c0870151608086015284815261547060e0880161528a565b60208201528152615484610100870161528a565b60208201528060208301525061549e86610120870161529a565b604082015281526154b3856102208601615324565b6020820152949350505050565b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b6154f28185614f3d565b60c060a08201525f610b4d60c0830184866154c0565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561070a5761070a615508565b835181526020840151602082015260408401516040820152608060608201525f610b4d6080830184866154c0565b6001600160a01b03929092168252602082015260400190565b8181038181111561070a5761070a615508565b5f6001600160401b038211156155a1576155a1614d2e565b50601f01601f191660200190565b5f82601f8301126155be575f5ffd5b81356155d16155cc82615589565b614df3565b8181528460208386010111156155e5575f5ffd5b816020850160208301375f918101602001919091529392505050565b5f5f60408385031215615612575f5ffd5b82358015158114615621575f5ffd5b915060208301356001600160401b0381111561563b575f5ffd5b615647858286016155af565b9150509250929050565b6001600160a01b039390931683526020830191909152604082015260600190565b5f60208284031215615682575f5ffd5b81356001600160401b03811115615697575f5ffd5b61062a848285016155af565b602080825282518282018190525f918401906040840190835b818110156156da5783518352602093840193909201916001016156bc565b509095945050505050565b5f602082840312156156f5575f5ffd5b81516001600160401b0381111561570a575f5ffd5b8201601f8101841361571a575f5ffd5b80516001600160401b0381111561573357615733614d2e565b8060051b61574360208201614df3565b9182526020818401810192908101908784111561575e575f5ffd5b6020850194505b8385101561578457845180835260209586019590935090910190615765565b979650505050505050565b634e487b7160e01b5f52603260045260245ffd5b5f5f608083850312156157b4575f5ffd5b6157be84846150d2565b915060608301356001600160401b0381111561563b575f5ffd5b5f602082840312156157e8575f5ffd5b81516108f481614bfc565b5f60c0828403128015615804575f5ffd5b5061580d614dd1565b82518152602080840151908201526040808401519082015260608084015190820152608083015161583d81614c55565b608082015260a083015161585081614c55565b60a08201529392505050565b5f5f60c0838503121561586d575f5ffd5b6158778484614e23565b915060a08301356001600160401b0381111561563b575f5ffd5b6001600160a01b0386811682526001600160401b0386166020830152841660408201526060810183905260a0608082018190525f9061578490830184614ebf565b6001600160a01b039a8b168152988a1660208a015260408901979097529488166060880152608087019390935290861660a086015260c085015260e08401529092166101008201526101208101919091526101400190565b634e487b7160e01b5f52601260045260245ffd5b6159488185614f88565b60a08101929092526001600160a01b031660c082015261010060e082018190525f9082015261012001919050565b61012081016159858288614f88565b60a082019590955260c08101939093526001600160a01b0391821660e08401521661010090910152919050565b5f5f604083850312156159c3575f5ffd5b505080516020909101519092909150565b60a0810161070a8284614f88565b6159ec8186614f88565b60a081019390935260c08301919091526001600160a01b031660e082015261012061010082018190525f9082015261014001919050565b6101008101615a328287614f88565b60a08201949094526001600160a01b0392831660c0820152911660e090910152919050565b60018060a01b03845116815260018060a01b03602085015116602082015260018060a01b036040850151166040820152606084015160608201526080840151608082015260a084015160a082015260c084015160c082015260e084015160e08201526101406101008201525f615ad1610140830185614ebf565b8281036101208401526109778185614ebf565b84546001600160a01b03908116825260018601548116602083015260028601548116604083015260038601545f9116615b206060840182614f7b565b50600486015460808301528460a08301528360c0830152615b4460e0830184614f7b565b61012061010083015261097761012083015f815260200190565b80516001600160801b0381168114615295575f5ffd5b5f60c0828403128015615b85575f5ffd5b50615b8e614dd1565b615b9783615b5e565b8152615ba560208401615b5e565b6020820152615bb660408401615b5e565b6040820152615bc760608401615b5e565b6060820152615bd860808401615b5e565b608082015261585060a08401615b5e565b6101608101615bf88285614f88565b82516001600160801b0390811660a0848101919091526020850151821660c08501526040850151821660e085015260608501518216610100850152608085015182166101208501529093015190921661014090910152919050565b6001600160801b03818116838216019081111561070a5761070a615508565b8215158152604060208201525f61062a6040830184614ebf565b60018060a01b0384168152826020820152606060408201525f610b4d6060830184614ebf565b5f82601f830112615cc1575f5ffd5b8151615ccf6155cc82615589565b818152846020838601011115615ce3575f5ffd5b8160208501602083015e5f918101602001919091529392505050565b5f5f5f838503610140811215615d13575f5ffd5b610100811215615d21575f5ffd5b50615d2a614d8c565b8451615d3581614bfc565b8152615d436020860161528a565b6020820152615d546040860161528a565b6040820152606085810151908201526080808601519082015260a0808601519082015260c0808601519082015260e080860151908201526101008501519093506001600160401b03811115615da7575f5ffd5b615db386828701615cb2565b9250506101208401516001600160401b03811115615dcf575f5ffd5b615ddb86828701615cb2565b9150509250925092565b808202811582820484141761070a5761070a615508565b5f82615e1657634e487b7160e01b5f52601260045260245ffd5b50049056fea2646970667358221220e0c5f8ce1215dcb42c8ccf2a9521e55ad6e35780c888043ea572cb2fcb5f69f164736f6c634300081c0033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
000000000000000000000000c7eaefecbb57b7bca1292b6df285486c2873d143000000000000000000000000297612c171fc8adce32ac333085a9ee1f2bcc1da000000000000000000000000cd6863bb697d7cee5b7ed8dea7d803374f7e4aa6000000000000000000000000297612c171fc8adce32ac333085a9ee1f2bcc1da0000000000000000000000001cb453f8d5565643fb20f5d005454db88dc088be0000000000000000000000004f708c0ae7ded3d74736594c2109c2e3c065b4280000000000000000000000000000000000000000000000000bef55718ad60000000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc000000000000000000000000ab162c41ad27df8614edd43f886857bb2054c23e000000000000000000000000000000000000000000000000002386f26fc10000000000000000000000000000000000000000000000000000002386f26fc1000000000000000000000000000000000000000000000000000000000000000000780000000000000000000000000000000000000000000000006f05b59d3b200000000000000000000000000000cd6863bb697d7cee5b7ed8dea7d803374f7e4aa6000000000000000000000000f6f3c8ff7bac29e6a19f9fc1ca1826426f7e2866000000000000000000000000ab162c41ad27df8614edd43f886857bb2054c23e000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc0000000000000000000000005477b94198f12e4e5faab2c8d95b807c061797c5
-----Decoded View---------------
Arg [0] : config (tuple):
Arg [1] : loopingStrategyStorage (tuple):
Arg [1] : authorizedSwapRouter (address): 0xc7eaEfECBb57B7bCA1292B6DF285486C2873d143
Arg [2] : avKatVault (address): 0x297612c171fc8ADce32ac333085a9Ee1F2BCC1Da
Arg [2] : morphoStrategyConfig (tuple):
Arg [1] : morphoCommons (tuple):
Arg [1] : marketParams (tuple):
Arg [1] : loanToken (address): 0xCD6863bB697d7CEE5b7Ed8deA7D803374F7e4Aa6
Arg [2] : collateralToken (address): 0x297612c171fc8ADce32ac333085a9Ee1F2BCC1Da
Arg [3] : oracle (address): 0x1cB453F8d5565643fb20F5d005454DB88dC088Be
Arg [4] : irm (address): 0x4F708C0ae7deD3d74736594C2109C2E3c065B428
Arg [5] : lltv (uint256): 860000000000000000
Arg [2] : morpho (address): 0xD50F2DffFd62f94Ee4AEd9ca05C61d0753268aBc
Arg [2] : priceFeed (address): 0xaB162c41Ad27DF8614eDd43F886857Bb2054C23e
Arg [3] : loopingFlashLoanableCommonStorage (tuple):
Arg [1] : amountToBeSwappedBufferInWAD (uint256): 10000000000000000
Arg [2] : withdrawAllBufferInWAD (uint256): 10000000000000000
Arg [3] : actionDeadline (uint256): 120
Arg [4] : maxLeverage (uint256): 8000000000000000000
Arg [5] : primaryDepositToken (address): 0xCD6863bB697d7CEE5b7Ed8deA7D803374F7e4Aa6
Arg [6] : loopingUtil (address): 0xf6F3C8FF7bac29E6a19f9FC1CA1826426f7E2866
Arg [7] : priceFeed (address): 0xaB162c41Ad27DF8614eDd43F886857Bb2054C23e
Arg [8] : flashLoanCaller (address): 0xD50F2DffFd62f94Ee4AEd9ca05C61d0753268aBc
Arg [1] : positionManager (address): 0x5477B94198f12E4E5fAab2c8D95B807C061797C5
-----Encoded View---------------
18 Constructor Arguments found :
Arg [0] : 000000000000000000000000c7eaefecbb57b7bca1292b6df285486c2873d143
Arg [1] : 000000000000000000000000297612c171fc8adce32ac333085a9ee1f2bcc1da
Arg [2] : 000000000000000000000000cd6863bb697d7cee5b7ed8dea7d803374f7e4aa6
Arg [3] : 000000000000000000000000297612c171fc8adce32ac333085a9ee1f2bcc1da
Arg [4] : 0000000000000000000000001cb453f8d5565643fb20f5d005454db88dc088be
Arg [5] : 0000000000000000000000004f708c0ae7ded3d74736594c2109c2e3c065b428
Arg [6] : 0000000000000000000000000000000000000000000000000bef55718ad60000
Arg [7] : 000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc
Arg [8] : 000000000000000000000000ab162c41ad27df8614edd43f886857bb2054c23e
Arg [9] : 000000000000000000000000000000000000000000000000002386f26fc10000
Arg [10] : 000000000000000000000000000000000000000000000000002386f26fc10000
Arg [11] : 0000000000000000000000000000000000000000000000000000000000000078
Arg [12] : 0000000000000000000000000000000000000000000000006f05b59d3b200000
Arg [13] : 000000000000000000000000cd6863bb697d7cee5b7ed8dea7d803374f7e4aa6
Arg [14] : 000000000000000000000000f6f3c8ff7bac29e6a19f9fc1ca1826426f7e2866
Arg [15] : 000000000000000000000000ab162c41ad27df8614edd43f886857bb2054c23e
Arg [16] : 000000000000000000000000d50f2dfffd62f94ee4aed9ca05c61d0753268abc
Arg [17] : 0000000000000000000000005477b94198f12e4e5faab2c8d95b807c061797c5
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 34 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
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.