{"file_path":"contracts/lending/credit-market/AltoConvexCreditLineMarket.sol","creation_status":"success","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {AltoBaseMarket} from \"@alto/lending/AltoBaseMarket.sol\";\nimport {AltoConvexCreditLineLib} from \"./AltoConvexCreditLineLib.sol\";\nimport {AssetShareConversionMath} from \"@alto/lending/libraries/AssetShareConversionMath.sol\";\nimport {Uint128Converter} from \"@alto/lending/libraries/Uint128Converter.sol\";\nimport {\n    CreditMarketInitParams,\n    IAltoConvexCreditLineMarketBase,\n    ConvexCreditLineInitParams,\n    IAltoConvexCreditLineMarketStaticTypes\n} from \"@alto/lending/interfaces/IAltoConvexCreditLineMarket.sol\";\nimport {IIrm} from \"@alto/lending/interfaces/IIrm.sol\";\nimport {BaseMarketInitParams, IMarketBase, MarketType, Position} from \"@alto/lending/interfaces/IMarket.sol\";\nimport {IMintableERC20} from \"@alto/lending/interfaces/IMintableERC20.sol\";\nimport {IConvexRewardPool} from \"@alto/lending/interfaces/vendor/IConvexRewardPool.sol\";\n\nimport {PAUSE_TYPE} from \"@alto/utils/Constants.sol\";\nimport {FixedPointMath, MATH_PRECISION} from \"@alto/utils/FixedPointMath.sol\";\nimport {ILendingOracle, LENDING_ORACLE_PRICE_PRECISION} from \"@alto/oracles/interfaces/IOracle.sol\";\n\n/// @title Alto Convex Credit Line Market\n/// @author GPM\n/// @custom:contact security@altofoundation.org\n/// @notice A single-account revolving DUSD credit line backed by Curve LP staked through Convex\n/// @dev `totalSupply.assets` is the credit capacity shared by active debt and unsettled bad debt.\n/// Supply shares stay zero. Interest and opening fees accrue to `claimableFeesAssets`.\n/// DUSD is intentionally unsupported as a reward token. This integration must not use DUSD reward incentives.\n/// Any DUSD rewards received remain in the market, which exposes no DUSD reward-forwarding or sweep function.\ncontract AltoConvexCreditLineMarket is AltoBaseMarket, IAltoConvexCreditLineMarketStaticTypes {\n    using FixedPointMath for uint256;\n    using AssetShareConversionMath for uint256;\n    using Uint128Converter for uint256;\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    address public creditAccount;\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    uint256 public foreclosureLtv;\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    uint128 public claimableFeesAssets;\n\n    /// @notice The borrow opening fee in MATH_PRECISION\n    uint256 private _borrowOpeningFee;\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    address public convexBooster;\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    uint256 public convexPoolId;\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    address public convexRewardPool;\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    address public rewardRecipient;\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    bool public convexActive;\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    address[] public rewardToken;\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    mapping(address => bool) public isRewardToken;\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    uint256 public badDebtAssets;\n\n    /// @custom:oz-upgrades-unsafe-allow constructor\n    constructor() {\n        _disableInitializers();\n    }\n\n    /// @notice Initializes the credit market and Convex pool\n    /// @param _initParams The credit market and Convex initialization parameters\n    function initialize(ConvexCreditLineInitParams memory _initParams) external initializer {\n        _initializeCreditMarket(_initParams.creditMarketInitParams);\n        _initializeConvex(_initParams);\n    }\n\n    /// @inheritdoc AltoBaseMarket\n    function borrowOpeningFee() public view override(AltoBaseMarket, IMarketBase) returns (uint256) {\n        return _borrowOpeningFee;\n    }\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    function setCreditAccount(address _newCreditAccount) external onlyOwner {\n        _requireNonZeroAddress(_newCreditAccount);\n\n        Position storage creditPosition = position[creditAccount];\n        if (creditPosition.borrowShares != 0 || creditPosition.collateralAssets != 0) {\n            revert AltoCreditMarketPositionNotEmpty();\n        }\n\n        emit SetCreditAccount(creditAccount, _newCreditAccount);\n        creditAccount = _newCreditAccount;\n    }\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    function setCreditLimit(uint256 _newCreditLimit) external onlyOwner {\n        if (!paused[PAUSE_TYPE]) {\n            _accrueInterest();\n        }\n        if (uint256(totalBorrowed.assets) + badDebtAssets > _newCreditLimit) {\n            revert AltoBaseMarketInsufficientMarketLiquidity();\n        }\n\n        uint256 oldCreditLimit = totalSupply.assets;\n        totalSupply.assets = _newCreditLimit.toUint128();\n        emit SetCreditLimit(oldCreditLimit, _newCreditLimit);\n    }\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    function setForeclosureLtv(uint256 _newForeclosureLtv) external onlyOwner {\n        if (_newForeclosureLtv <= maxLtv || _newForeclosureLtv > MATH_PRECISION) {\n            revert AltoCreditMarketInvalidInput();\n        }\n\n        emit SetForeclosureLtv(foreclosureLtv, _newForeclosureLtv);\n        foreclosureLtv = _newForeclosureLtv;\n    }\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    function setBorrowOpeningFee(uint256 _newBorrowOpeningFee) external onlyOwner {\n        if (_newBorrowOpeningFee > MATH_PRECISION) {\n            revert AltoCreditMarketInvalidInput();\n        }\n\n        emit SetBorrowOpeningFee(_borrowOpeningFee, _newBorrowOpeningFee);\n        _borrowOpeningFee = _newBorrowOpeningFee;\n    }\n\n    /// @inheritdoc IMarketBase\n    function setFeeRecipient(address _feeRecipient) external override onlyOwner {\n        _requireNonZeroAddress(_feeRecipient);\n\n        emit SetFeeRecipient(feeRecipient, _feeRecipient);\n        feeRecipient = _feeRecipient;\n    }\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    function claimInterest(uint256 interest) external whenNotPaused returns (uint256) {\n        _requireNonZeroAddress(feeRecipient);\n        if (interest > claimableFeesAssets) {\n            revert AltoCreditMarketInvalidInput();\n        }\n\n        return _claimInterest(interest);\n    }\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    function settleBadDebt(uint256 assets) external onlyOwner {\n        if (assets == 0) {\n            revert AltoCreditMarketInvalidInput();\n        }\n\n        badDebtAssets -= assets;\n        _sendBorrowToken(msg.sender, address(this), assets);\n\n        emit BadDebtSettled(assets);\n    }\n\n    /// @inheritdoc AltoBaseMarket\n    /// @dev Foreclosure is available only after debt strictly exceeds the foreclosure LTV.\n    /// All active debt becomes bad debt and all recorded collateral goes to the owner. Claimable fees remain\n    /// unchanged. Collateral withdrawal does not claim rewards, which remain payable to `rewardRecipient`.\n    /// LP recovery and swaps happen separately. `settleBadDebt` burns recovered DUSD through this market.\n    function governanceLiquidate(address borrower, bool skipAccrueInterest)\n        external\n        override(AltoBaseMarket, IMarketBase)\n        nonReentrant\n        onlyOwner\n        returns (uint256 collateralAmount, uint256 badDebtAmount)\n    {\n        _requireCreditAccount(borrower);\n        if (!paused[PAUSE_TYPE] && !skipAccrueInterest) {\n            _accrueInterest();\n        }\n\n        if (!_isLiquidatable(borrower)) {\n            revert AltoCreditMarketPositionNotForeclosable();\n        }\n\n        Position storage borrowerPosition = position[borrower];\n        collateralAmount = borrowerPosition.collateralAssets;\n        uint128 badDebtShares = borrowerPosition.borrowShares;\n        badDebtAmount = totalBorrowed.assets;\n\n        totalBorrowed.assets = 0;\n        totalBorrowed.shares = 0;\n\n        badDebtAssets += badDebtAmount;\n        emit BadDebtAccrued(badDebtAmount);\n\n        borrowerPosition.borrowShares = 0;\n        borrowerPosition.collateralAssets = 0;\n\n        if (collateralAmount != 0) {\n            _sendCollateral(msg.sender, collateralAmount);\n        }\n\n        emit GovernanceLiquidation(borrower, msg.sender, collateralAmount, badDebtAmount, badDebtShares);\n    }\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    function claimRewards() external nonReentrant returns (uint256[] memory claimedAmounts) {\n        return AltoConvexCreditLineLib.claimRewards(convexRewardPool, rewardRecipient, rewardToken);\n    }\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    function setRewardRecipient(address _newRecipient) external {\n        _requireCreditAccount(msg.sender);\n        _requireNonZeroAddress(_newRecipient);\n\n        emit SetRewardRecipient(rewardRecipient, _newRecipient);\n        rewardRecipient = _newRecipient;\n    }\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    function addRewardToken(address _token) external onlyOwner {\n        _addRewardToken(_token);\n    }\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    function removeRewardToken(address _token) external onlyOwner {\n        AltoConvexCreditLineLib.removeRewardToken(rewardToken, isRewardToken, convexRewardPool, _token);\n\n        emit RewardTokenRemoved(_token);\n    }\n\n    /// @inheritdoc IAltoConvexCreditLineMarketBase\n    function emergencyExitConvex() external onlyOwner returns (uint256 assets) {\n        if (!paused[PAUSE_TYPE]) {\n            revert AltoConvexCreditLineMustBePaused();\n        }\n        if (!convexActive) {\n            revert AltoConvexCreditLineStrategyInactive();\n        }\n\n        convexActive = false;\n        assets = AltoConvexCreditLineLib.emergencyWithdraw(convexRewardPool);\n\n        emit ConvexEmergencyExit(assets);\n    }\n\n    /// @dev Initializes the Base market and then initializes Credit state.\n    function _initializeCreditMarket(CreditMarketInitParams memory _initParams) internal onlyInitializing {\n        BaseMarketInitParams memory baseMarketInitParams = _initParams.baseMarketInitParams;\n\n        _requireNonZeroAddress(_initParams.creditAccount);\n        _requireNonZeroAddress(baseMarketInitParams.feeRecipient);\n        _requireNonZeroAddress(baseMarketInitParams.irm);\n        if (\n            _initParams.creditLimit == 0 || _initParams.initialBorrowOpeningFee > MATH_PRECISION\n                || baseMarketInitParams.maxLtv >= _initParams.foreclosureLtv\n                || _initParams.foreclosureLtv > MATH_PRECISION\n        ) {\n            revert AltoCreditMarketInvalidInput();\n        }\n\n        __UUPSUpgradeable_init();\n        __AltoBaseMarket_init(baseMarketInitParams, MarketType.CREDIT_MINT);\n\n        foreclosureLtv = _initParams.foreclosureLtv;\n        emit SetForeclosureLtv(0, _initParams.foreclosureLtv);\n\n        creditAccount = _initParams.creditAccount;\n        emit SetCreditAccount(address(0), _initParams.creditAccount);\n\n        totalSupply.assets = _initParams.creditLimit.toUint128();\n        emit SetCreditLimit(0, _initParams.creditLimit);\n\n        _borrowOpeningFee = _initParams.initialBorrowOpeningFee;\n        emit SetBorrowOpeningFee(0, _initParams.initialBorrowOpeningFee);\n    }\n\n    /// @inheritdoc AltoBaseMarket\n    /// @dev Unlike `AltoBaseMarket`, the IRM must be nonzero.\n    function _setIrm(address _irm, bool _skipAccrueInterest) internal override {\n        _requireNonZeroAddress(_irm);\n        if (_irm == irm) {\n            revert AltoCreditMarketInvalidInput();\n        }\n\n        super._setIrm(_irm, _skipAccrueInterest);\n    }\n\n    /// @inheritdoc AltoBaseMarket\n    function _setMaxLtv(uint256 _maxLtv) internal override {\n        if (_maxLtv >= foreclosureLtv) {\n            revert AltoCreditMarketInvalidInput();\n        }\n\n        emit SetMaxLtv(maxLtv, _maxLtv);\n        maxLtv = _maxLtv;\n    }\n\n    /// @dev Disabled because this market does not support a liquidation engine.\n    function _setLiquidationEngine(address) internal pure override {\n        revert AltoCreditMarketUnsupportedOperation();\n    }\n\n    /// @dev Disabled because this market does not support a liquidation periphery.\n    function _setAuthorizedLiquidationPeriphery(address, bool) internal pure override {\n        revert AltoCreditMarketUnsupportedOperation();\n    }\n\n    /// @dev Disabled because borrow and collateral-removal callbacks are unsupported.\n    function _setAuthorizedCallback(address, bool) internal pure override {\n        revert AltoCreditMarketUnsupportedOperation();\n    }\n\n    /// @dev Disabled because this market does not support lender supply.\n    function _addSupply(uint256, uint256, address) internal pure override returns (uint256, uint256) {\n        revert AltoCreditMarketUnsupportedOperation();\n    }\n\n    /// @dev Disabled because this market does not support lender supply.\n    function _removeSupply(uint256, uint256, address, address) internal pure override returns (uint256, uint256) {\n        revert AltoCreditMarketUnsupportedOperation();\n    }\n\n    /// @inheritdoc AltoBaseMarket\n    /// @dev Only the exact `creditAccount` may call and receive collateral. Authorized delegates cannot add collateral.\n    /// The collateral is deposited into Convex.\n    function _addCollateral(uint256 assets, address onBehalf) internal override nonReentrant returns (uint256) {\n        _requireCreditAccount(msg.sender);\n        _requireCreditAccount(onBehalf);\n        return super._addCollateral(assets, onBehalf);\n    }\n\n    /// @inheritdoc AltoBaseMarket\n    function _receiveCollateral(uint256 assets) internal override {\n        if (!convexActive) {\n            revert AltoCreditMarketInvalidInput();\n        }\n\n        super._receiveCollateral(assets);\n        AltoConvexCreditLineLib.depositCollateralToConvex(collateralToken, convexBooster, convexPoolId, assets);\n    }\n\n    /// @inheritdoc AltoBaseMarket\n    /// @dev Callbacks are unsupported. Active collateral is unwrapped from Convex, while collateral recovered by an\n    /// emergency exit is transferred from idle custody. The remaining position must be solvent.\n    function _removeCollateral(uint256 assets, address onBehalf, address receiver, bytes calldata swapParams)\n        internal\n        override\n        returns (uint256)\n    {\n        _requireNonZeroAddress(receiver);\n        if (swapParams.length != 0) {\n            revert AltoCreditMarketCallbacksUnsupported();\n        }\n        _requireCreditAccount(onBehalf);\n\n        return super._removeCollateral(assets, onBehalf, receiver, swapParams);\n    }\n\n    /// @inheritdoc AltoBaseMarket\n    function _sendCollateral(address receiver, uint256 assets) internal override {\n        if (convexActive) {\n            AltoConvexCreditLineLib.withdrawAndUnwrapCollateral(convexRewardPool, assets);\n            emit CollateralUnstaked(receiver, assets);\n        }\n\n        super._sendCollateral(receiver, assets);\n    }\n\n    /// @inheritdoc AltoBaseMarket\n    /// @dev Debt may only be assigned to `creditAccount`; it or an authorized delegate may call. Callbacks are unsupported.\n    function _borrow(uint256 assets, uint256 shares, address onBehalf, address receiver, bytes calldata swapParams)\n        internal\n        override\n        returns (uint256, uint256, uint256)\n    {\n        _requireCreditAccount(onBehalf);\n        if (swapParams.length != 0) {\n            revert AltoCreditMarketCallbacksUnsupported();\n        }\n\n        uint256 openingFeeAssets;\n        (assets, shares, openingFeeAssets) = super._borrow(assets, shares, onBehalf, receiver, swapParams);\n\n        if (uint256(totalBorrowed.assets) + badDebtAssets > totalSupply.assets) {\n            revert AltoBaseMarketInsufficientMarketLiquidity();\n        }\n\n        return (assets, shares, openingFeeAssets);\n    }\n\n    /// @dev Adds the opening fee to `claimableFeesAssets` without creating fee-recipient supply shares.\n    /// @param openingFeeAssets The opening fee added to the claimable balance.\n    /// @return Always zero because this market has no lender supply shares.\n    function _applyBorrowOpeningFee(uint256 openingFeeAssets) internal override returns (uint256) {\n        claimableFeesAssets += openingFeeAssets.toUint128();\n\n        return 0;\n    }\n\n    /// @inheritdoc AltoBaseMarket\n    /// @dev Only the exact `creditAccount` may repay its own debt. Authorized delegates and third parties cannot repay.\n    /// Borrow tokens are burned from `creditAccount`.\n    function _repay(uint256 assets, uint256 shares, address onBehalf) internal override returns (uint256, uint256) {\n        _requireCreditAccount(msg.sender);\n        _requireCreditAccount(onBehalf);\n\n        _accrueInterest();\n\n        if (claimableFeesAssets > 0) {\n            _claimInterest(0);\n        }\n\n        return super._repay(assets, shares, onBehalf);\n    }\n\n    /// @dev Claims interest and fees by minting borrow tokens to the fee recipient.\n    function _claimInterest(uint256 interest) internal returns (uint256) {\n        if (interest == 0) {\n            interest = claimableFeesAssets;\n        }\n\n        claimableFeesAssets -= interest.toUint128();\n        if (interest != 0) {\n            _sendBorrowToken(address(this), feeRecipient, interest);\n        }\n\n        emit InterestClaimed(feeRecipient, interest);\n\n        return interest;\n    }\n\n    /// @dev Accrues interest into active debt and `claimableFeesAssets` without changing the credit limit.\n    function _accrueInterest() internal override {\n        (uint256 interest, uint256 borrowRate) = IIrm(irm).updateInterestRate(totalSupply.assets, totalBorrowed.assets);\n\n        if (interest != 0) {\n            totalBorrowed.assets += interest.toUint128();\n            claimableFeesAssets += interest.toUint128();\n            emit AccrueInterest(borrowRate, interest, totalBorrowed.assets, totalSupply.assets);\n        }\n    }\n\n    /// @inheritdoc AltoBaseMarket\n    /// @dev Full share repayment can leave virtual-share rounding dust in global borrowed assets. The account's\n    /// solvency follows its borrow shares, so that residual does not lock a debt-free account's collateral.\n    function _isSolvent(address _user) internal view override returns (bool) {\n        if (position[_user].borrowShares == 0) {\n            return true;\n        }\n\n        uint256 collateralValue = _collateralValue(_user);\n        uint256 maxBorrowValue = collateralValue.multiplyWithPrecision(maxLtv);\n        return maxBorrowValue >= _borrowValue(_user);\n    }\n\n    /// @dev Returns true if the user's position has breached the foreclosure LTV.\n    function _isLiquidatable(address _user) internal view returns (bool) {\n        uint256 collateralValue = _collateralValue(_user);\n        uint256 foreclosureBorrowValue = collateralValue.multiplyWithPrecision(foreclosureLtv);\n        return _borrowValue(_user) > foreclosureBorrowValue;\n    }\n\n    /// @dev Disabled because this market supports governance foreclosure instead of public liquidation.\n    function _liquidate(address, bytes calldata, bytes memory)\n        internal\n        pure\n        override\n        returns (uint256, uint256, uint256)\n    {\n        revert AltoCreditMarketNonLiquidatable();\n    }\n\n    /// @inheritdoc AltoBaseMarket\n    function _sendBorrowToken(address from, address to, uint256 amount) internal override {\n        if (from == address(this)) {\n            IMintableERC20(borrowToken).mint(to, amount);\n        } else {\n            IMintableERC20(borrowToken).burn(from, amount);\n        }\n    }\n\n    /// @dev Reverts when the supplied address is zero.\n    function _requireNonZeroAddress(address account) internal pure {\n        if (account == address(0)) {\n            revert AltoCreditMarketZeroAddress();\n        }\n    }\n\n    /// @dev Validates and stores the Convex custody and reward configuration.\n    function _initializeConvex(ConvexCreditLineInitParams memory _initParams) private {\n        uint256 tokenCount = _initParams.rewardTokens.length;\n        (address depositToken, address rewardPool) = AltoConvexCreditLineLib.validateConvexInitialization(\n            _initParams.convexBooster, _initParams.convexPoolId, collateralToken, _initParams.rewardRecipient\n        );\n\n        convexBooster = _initParams.convexBooster;\n        convexPoolId = _initParams.convexPoolId;\n        convexRewardPool = rewardPool;\n        rewardRecipient = _initParams.rewardRecipient;\n        convexActive = true;\n\n        for (uint256 i = 0; i < tokenCount; ++i) {\n            _addRewardToken(_initParams.rewardTokens[i]);\n        }\n\n        if (!isRewardToken[IConvexRewardPool(rewardPool).rewardToken()]) {\n            revert AltoCreditMarketInvalidInput();\n        }\n\n        emit ConvexConfigured(\n            _initParams.convexBooster, _initParams.convexPoolId, rewardPool, depositToken, _initParams.rewardRecipient\n        );\n    }\n\n    /// @dev Adds a validated token to the reward forwarding list.\n    function _addRewardToken(address _token) private {\n        AltoConvexCreditLineLib.validateRewardTokenAddition(\n            rewardToken.length, isRewardToken[_token], _token, collateralToken, borrowToken, convexRewardPool\n        );\n\n        isRewardToken[_token] = true;\n        rewardToken.push(_token);\n        emit RewardTokenAdded(_token);\n    }\n\n    /// @dev Returns the user's collateral value in borrow-token asset units.\n    function _collateralValue(address _user) private view returns (uint256) {\n        uint256 collateralPrice = ILendingOracle(oracle).getPrice();\n        if (collateralPrice == 0) {\n            revert AltoCreditMarketInvalidOraclePrice();\n        }\n\n        uint256 collateralAssets = uint256(position[_user].collateralAssets);\n        return collateralAssets.divideWithRounding(collateralPrice, LENDING_ORACLE_PRICE_PRECISION, false);\n    }\n\n    /// @dev Returns the user's borrow value in borrow-token asset units.\n    function _borrowValue(address _user) private view returns (uint256) {\n        uint256 borrowShares = uint256(position[_user].borrowShares);\n        return borrowShares.convertToAssetsUp(totalBorrowed.assets, totalBorrowed.shares);\n    }\n\n    /// @dev Reverts unless the account is the configured credit account.\n    function _requireCreditAccount(address account) private view {\n        if (account != creditAccount) {\n            revert AltoCreditMarketUnauthorizedAccount();\n        }\n    }\n}\n","deployed_bytecode":"0x608060405260043610610388575f3560e01c806379ba5097116101d9578063bb14516c11610100578063e529ee9511610099578063e529ee9514610c49578063e5ca1fd414610c5e578063e74b981b14610c72578063e76ed98614610c91578063e7c646e914610cb0578063eecea00014610ccf578063f2fde38b14610cee578063f774bbaf14610d0d578063fbb922cd14610d0d575f5ffd5b8063bb14516c14610b27578063cadac47914610b46578063d0b2ca3414610b65578063d558f62714610b93578063dcd6f52614610bb9578063dd81aac014610bd8578063e084142814610bf7578063e30c397814610c16578063e521136f14610c2a575f5ffd5b8063959916dc11610172578063959916dc146109965780639e9e4666146109aa578063a6afed95146109d8578063a866442e146109ec578063ad3cb1cc14610a0b578063b1e8f8ef14610a48578063b2016bd414610a67578063b5fd73f814610a86578063b7648fb914610ab4575f5ffd5b806379ba50971461087e5780637adbf973146108925780637dc0d1d0146108b15780637df65b26146108d057806380cd33c0146108ef57806383b597471461090e57806384b0196e1461092d5780638da5cb5b1461095457806393930dce14610968575f5ffd5b806344bf3c72116102bd57806352d1902d1161025657806352d1902d1461076e578063563d4f64146107825780635ab6ced4146107975780635e36746a146107ac57806365e4ad9e146107cb5780636d0a1218146108015780636d8500701461082057806370ae92d21461083f578063715018a61461086a575f5ffd5b806344bf3c7214610639578063456dc17a14610658578063469048401461067c57806348780d2e1461069b5780634c19386c146106d45780634d298abd146106fe5780634f1ef2861461071d578063509b6c3f146107305780635100b5671461074f575f5ffd5b806328e8fe7d1161032f57806328e8fe7d146104d45780632cdacb50146104f35780632d7bd628146105125780632eb375ea14610546578063372500ab146105735780633a12c6da146105945780633d509c97146105a95780633e6950ab146105c85780633fcebaf4146105ff575f5ffd5b806303fce1851461038c5780630a3ce376146103ad578063176dfd89146103e257806317f333401461040157806318160ddd1461042d5780631c03e6cc146104775780631d93f7a114610496578063250313e2146104b5575b5f5ffd5b348015610397575f5ffd5b506103ab6103a6366004614d3a565b610d2c565b005b3480156103b8575f5ffd5b506039546103cd90600160a01b900460ff1681565b60405190151581526020015b60405180910390f35b3480156103ed575f5ffd5b506103ab6103fc366004614dfc565b610d42565b34801561040c575f5ffd5b50603954610420906001600160a01b031681565b6040516103d99190614e89565b348015610438575f5ffd5b50600654610457906001600160801b0380821691600160801b90041682565b604080516001600160801b039384168152929091166020830152016103d9565b348015610482575f5ffd5b506103ab610491366004614e9d565b610fb1565b3480156104a1575f5ffd5b506103ab6104b0366004614eb8565b610fc5565b3480156104c0575f5ffd5b506103ab6104cf366004614f64565b611044565b3480156104df575f5ffd5b50600a54610420906001600160a01b031681565b3480156104fe575f5ffd5b50603654610420906001600160a01b031681565b34801561051d575f5ffd5b5061053161052c366004615105565b611146565b604080519283526020830191909152016103d9565b348015610551575f5ffd5b50610565610560366004614eb8565b61120e565b6040519081526020016103d9565b34801561057e575f5ffd5b506105876112b6565b6040516103d99190615175565b34801561059f575f5ffd5b50610565600c5481565b3480156105b4575f5ffd5b506103ab6105c3366004614e9d565b61135c565b3480156105d3575f5ffd5b506034546105e7906001600160801b031681565b6040516001600160801b0390911681526020016103d9565b34801561060a575f5ffd5b5061061e6106193660046151c4565b61141b565b604080519384526020840192909252908201526060016103d9565b348015610644575f5ffd5b50600e54610420906001600160a01b031681565b348015610663575f5ffd5b506004546104209061010090046001600160a01b031681565b348015610687575f5ffd5b50600d54610420906001600160a01b031681565b3480156106a6575f5ffd5b506103cd6106b536600461523a565b600360209081525f928352604080842090915290825290205460ff1681565b3480156106df575f5ffd5b50600754610457906001600160801b0380821691600160801b90041682565b348015610709575f5ffd5b506103ab610718366004614e9d565b6114f9565b6103ab61072b366004615264565b61150a565b34801561073b575f5ffd5b5061042061074a366004614eb8565b611525565b34801561075a575f5ffd5b506103ab610769366004614eb8565b61154d565b348015610779575f5ffd5b506105656115bf565b34801561078d575f5ffd5b50610565603c5481565b3480156107a2575f5ffd5b5061056560335481565b3480156107b7575f5ffd5b506105316107c6366004615309565b6115da565b3480156107d6575f5ffd5b506103cd6107e5366004615350565b5f60208181529281526040808220909352908152205460ff1681565b34801561080c575f5ffd5b50603254610420906001600160a01b031681565b34801561082b575f5ffd5b506103ab61083a366004614eb8565b61164b565b34801561084a575f5ffd5b50610565610859366004614e9d565b60016020525f908152604090205481565b348015610875575f5ffd5b506103ab611732565b348015610889575f5ffd5b506103ab611745565b34801561089d575f5ffd5b506103ab6108ac366004614e9d565b611781565b3480156108bc575f5ffd5b50600b54610420906001600160a01b031681565b3480156108db575f5ffd5b506103ab6108ea366004615387565b611792565b3480156108fa575f5ffd5b50610531610909366004614d3a565b6117aa565b348015610919575f5ffd5b506103ab610928366004614e9d565b611954565b348015610938575f5ffd5b50610941611a23565b6040516103d997969594939291906153f0565b34801561095f575f5ffd5b50610420611ac7565b348015610973575f5ffd5b506103cd610982366004614e9d565b600f6020525f908152604090205460ff1681565b3480156109a1575f5ffd5b50603554610565565b3480156109b5575f5ffd5b506103cd6109c4366004614eb8565b60026020525f908152604090205460ff1681565b3480156109e3575f5ffd5b506103ab611afb565b3480156109f7575f5ffd5b5061061e610a0636600461545f565b611b57565b348015610a16575f5ffd5b50610a3b604051806040016040528060058152602001640352e302e360dc1b81525081565b6040516103d991906154df565b348015610a53575f5ffd5b50610531610a62366004615105565b611c13565b348015610a72575f5ffd5b50600554610420906001600160a01b031681565b348015610a91575f5ffd5b506103cd610aa0366004614e9d565b603b6020525f908152604090205460ff1681565b348015610abf575f5ffd5b50610afd610ace366004614e9d565b60086020525f9081526040902080546001909101546001600160801b0380831692600160801b90048116911683565b604080516001600160801b03948516815292841660208401529216918101919091526060016103d9565b348015610b32575f5ffd5b506103ab610b413660046154f1565b611c76565b348015610b51575f5ffd5b50610565610b60366004615512565b611d78565b348015610b70575f5ffd5b506103cd610b7f366004614e9d565b60096020525f908152604090205460ff1681565b348015610b9e575f5ffd5b50600454610bac9060ff1681565b6040516103d99190615549565b348015610bc4575f5ffd5b50603854610420906001600160a01b031681565b348015610be3575f5ffd5b50610565610bf236600461556f565b611e35565b348015610c02575f5ffd5b506103ab610c11366004614eb8565b611eb3565b348015610c21575f5ffd5b50610420611f33565b348015610c35575f5ffd5b506103ab610c44366004614e9d565b611f3d565b348015610c54575f5ffd5b5061056560375481565b348015610c69575f5ffd5b50610565611faa565b348015610c7d575f5ffd5b506103ab610c8c366004614e9d565b6120ed565b348015610c9c575f5ffd5b506103ab610cab366004614eb8565b612159565b348015610cbb575f5ffd5b506103ab610cca366004614e9d565b61216a565b348015610cda575f5ffd5b506103ab610ce9366004614d3a565b612172565b348015610cf9575f5ffd5b506103ab610d08366004614e9d565b612224565b348015610d18575f5ffd5b506103ab610d27366004614d3a565b612294565b610d346122a6565b610d3e82826122d8565b5050565b8160800151421115610d675760405163fd1d678360e01b815260040160405180910390fd5b81516001600160a01b03165f908152600160205260408120805491610d8b836155d3565b91905055826060015114610db2576040516338a8556160e01b815260040160405180910390fd5b604080517fdc4e086394e5096a6add5d5327f22bea47783d5150bbc2440a258e94a12df54860208083019190915284516001600160a01b039081168385015290850151166060808301919091529184015115156080808301919091529184015160a08201529083015160c08201525f9060e0016040516020818303038152906040528051906020012090505f610e478261231a565b84519091505f90610eae908360208701803590604089013590610e6a908a6155eb565b604051602001610e9a93929190928352602083019190915260f81b6001600160f81b031916604082015260410190565b604051602081830303815290604052612346565b905080610ece57604051637a0ddbd160e11b815260040160405180910390fd5b60408581015186516001600160a01b039081165f9081526020818152848220818b015184168352815290849020805460ff191693151593909317909255875160608901519351938452169133917fa58af1a0c70dba0c7aa60d1a1a147ebd61000d1690a968828ac718bca927f2c7910160405180910390a384602001516001600160a01b0316855f01516001600160a01b0316336001600160a01b03167fd5e969f01efe921d3f766bdebad25f0a05e3f237311f56482bf132d0326309c08860400151604051610fa2911515815260200190565b60405180910390a45050505050565b610fb96122a6565b610fc2816123b9565b50565b610fcd6122a6565b600c5481111580610fe55750670de0b6b3a764000081115b156110035760405163fc91449760e01b815260040160405180910390fd5b60335460408051918252602082018390527f37734fca9f253a81e2893a3dc65f94f53caa23cff074b1fcaaa679c6618ff109910160405180910390a1603355565b5f61104d6124fb565b805490915060ff600160401b82041615906001600160401b03165f811580156110735750825b90505f826001600160401b0316600114801561108e5750303b155b90508115801561109c575080155b156110ba5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff1916600117855583156110e457845460ff60401b1916600160401b1785555b85516110ef90612523565b6110f886612708565b831561113e57845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b505050505050565b5f516020615a3c5f395f51905f525f90815260026020525f5160206159dc5f395f51905f5254819060ff16156111a357604051638698dd2b60e01b81525f516020615a3c5f395f51905f5260048201526024015b60405180910390fd5b5f5160206159bc5f395f51905f525f5260026020525f516020615a1c5f395f51905f525460ff16156111f757604051638698dd2b60e01b81525f5160206159bc5f395f51905f52600482015260240161119a565b61120285858561295e565b91509150935093915050565b5f516020615a3c5f395f51905f525f90815260026020525f5160206159dc5f395f51905f525460ff161561126457604051638698dd2b60e01b81525f516020615a3c5f395f51905f52600482015260240161119a565b600d54611279906001600160a01b0316612979565b6034546001600160801b03168211156112a55760405163fc91449760e01b815260040160405180910390fd5b6112ae826129a0565b90505b919050565b60606112c0612a63565b6038546039546040516313c181cf60e11b815273d7c8bb6708e989fc61a4ac025ecf4c0ed6b90eb492632783039e9261130e926001600160a01b039283169290911690603a9060040161560b565b5f60405180830381865af4158015611328573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261134f919081019061562f565b9050611359612aad565b90565b6113646122a6565b6038546040516308b3168160e21b8152603a6004820152603b60248201526001600160a01b039182166044820152908216606482015273d7c8bb6708e989fc61a4ac025ecf4c0ed6b90eb4906322cc5a04906084015f6040518083038186803b1580156113cf575f5ffd5b505af41580156113e1573d5f5f3e3d5ffd5b50506040516001600160a01b03841692507f66257bcef574219c04f7c05f7a1c78d599da10491294c92a5805c48b4cdf500991505f90a250565b5f516020615a3c5f395f51905f525f90815260026020525f5160206159dc5f395f51905f52548190819060ff161561147557604051638698dd2b60e01b81525f516020615a3c5f395f51905f52600482015260240161119a565b5f5160206159bc5f395f51905f525f5260026020525f516020615a1c5f395f51905f525460ff16156114c957604051638698dd2b60e01b81525f5160206159bc5f395f51905f52600482015260240161119a565b6114d1612a63565b6114df898989898989612ad3565b9250925092506114ed612aad565b96509650969350505050565b6115016122a6565b610fc281612b64565b611512612b7d565b61151b82612c21565b610d3e8282612c29565b603a8181548110611534575f80fd5b5f918252602090912001546001600160a01b0316905081565b6115556122a6565b670de0b6b3a764000081111561157e5760405163fc91449760e01b815260040160405180910390fd5b60355460408051918252602082018390527f49dbba69a16a62cba637f2214d89fa57fa1b2dac288502fca505113d191240f7910160405180910390a1603555565b5f6115c8612cdc565b505f5160206159fc5f395f51905f5290565b5f516020615a3c5f395f51905f525f90815260026020525f5160206159dc5f395f51905f5254819060ff161561163257604051638698dd2b60e01b81525f516020615a3c5f395f51905f52600482015260240161119a565b61163e8686868661295e565b9150915094509492505050565b6116536122a6565b5f516020615a3c5f395f51905f525f5260026020525f5160206159dc5f395f51905f525460ff1661168657611686612d25565b603c5460075482916116a0916001600160801b03166156b5565b11156116bf5760405163828435f760e01b815260040160405180910390fd5b6006546001600160801b03166116d482612e8d565b600680546001600160801b0319166001600160801b039290921691909117905560408051828152602081018490527f1099cd9f9ddfd0f163da23e6cfa1b521a78ad68d1a3ba76f683a9ed85494355691015b60405180910390a15050565b61173a6122a6565b6117435f612eba565b565b338061174f611f33565b6001600160a01b031614611778578060405163118cdaa760e01b815260040161119a9190614e89565b610fc281612eba565b6117896122a6565b610fc281612edc565b61179a6122a6565b6117a5838383612f5e565b505050565b5f5f6117b4612a63565b6117bc6122a6565b6117c584612fc1565b5f516020615a3c5f395f51905f525f5260026020525f5160206159dc5f395f51905f525460ff161580156117f7575082155b1561180457611804612d25565b61180d84612fef565b61182a5760405163093687eb60e01b815260040160405180910390fd5b50506001600160a01b0382165f908152600860205260408120600181015481546007805490859055603c80546001600160801b03948516969285169594600160801b909404909316928592906118819084906156b5565b90915550506040518381527f50033b418a5ee3b84a888e58b173ed55186161b36f84b47eb587b8894d86c9ea9060200160405180910390a181546001600160801b031682556001820180546001600160801b031916905583156118e8576118e83385613027565b60408051338152602081018690529081018490526001600160801b03821660608201526001600160a01b038716907ff5fb0963d72631ccb5b35b1f3211f8b7703485665806717f2a5c4231d33e86b39060800160405180910390a2505061194d612aad565b9250929050565b61195c6122a6565b61196581612979565b6032546001600160a01b03165f9081526008602052604090208054600160801b90046001600160801b03161515806119a9575060018101546001600160801b031615155b156119c757604051637393cb1b60e01b815260040160405180910390fd5b6032546040516001600160a01b038085169216907f1caf1e415bbf6b44cff7c784e551494a5748817c5ee20c0a8b7f26dfc49e9c39905f90a350603280546001600160a01b0319166001600160a01b0392909216919091179055565b5f6060805f5f5f60605f611a356130f7565b8054909150158015611a4957506001810154155b611a8d5760405162461bcd60e51b81526020600482015260156024820152741152540dcc4c8e88155b9a5b9a5d1a585b1a5e9959605a1b604482015260640161119a565b611a9561311b565b611a9d6131b9565b604080515f80825260208201909252600f60f81b9c939b5091995046985030975095509350915050565b5f807f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c1993005b546001600160a01b031692915050565b5f516020615a3c5f395f51905f525f5260026020525f5160206159dc5f395f51905f525460ff1615611b4f57604051638698dd2b60e01b81525f516020615a3c5f395f51905f52600482015260240161119a565b611743612d25565b5f516020615a3c5f395f51905f525f90815260026020525f5160206159dc5f395f51905f52548190819060ff1615611bb157604051638698dd2b60e01b81525f516020615a3c5f395f51905f52600482015260240161119a565b611bb9612a63565b611bfa88888888888080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152506131d592505050565b925092509250611c08612aad565b955095509592505050565b5f516020615a3c5f395f51905f525f90815260026020525f5160206159dc5f395f51905f5254819060ff1615611c6b57604051638698dd2b60e01b81525f516020615a3c5f395f51905f52600482015260240161119a565b6112028585856131f1565b335f908152600360209081526040808320858452909152902054829060ff16611cb657338160405163122994e360e11b815260040161119a9291906156c8565b611cc08383613234565b5f8381526002602052604090205482151560ff909116151503611d1c575f8381526002602052604090819020549051634363bf4f60e01b81526004810185905260ff90911615156024820152821515604482015260640161119a565b5f83815260026020908152604091829020805460ff191685151590811790915582518681529182015233917f33b87b74fe6b8ad758141301728df7c3aef0580734207b5484402185fd4c002491015b60405180910390a2505050565b5f516020615a3c5f395f51905f525f90815260026020525f5160206159dc5f395f51905f525460ff1615611dce57604051638698dd2b60e01b81525f516020615a3c5f395f51905f52600482015260240161119a565b5f5160206159bc5f395f51905f525f5260026020525f516020615a1c5f395f51905f525460ff1615611e2257604051638698dd2b60e01b81525f5160206159bc5f395f51905f52600482015260240161119a565b611e2c83836132ad565b90505b92915050565b5f516020615a3c5f395f51905f525f90815260026020525f5160206159dc5f395f51905f525460ff1615611e8b57604051638698dd2b60e01b81525f516020615a3c5f395f51905f52600482015260240161119a565b611e93612a63565b611ea086868686866132dc565b9050611eaa612aad565b95945050505050565b611ebb6122a6565b805f03611edb5760405163fc91449760e01b815260040160405180910390fd5b80603c5f828254611eec91906156e1565b90915550611efd9050333083613325565b6040518181527f400a13da53bfd3f099aeac0af799847596847105daf792ad35de00bbcbf9b44b9060200160405180910390a150565b5f5f611aeb6133d1565b611f4633612fc1565b611f4f81612979565b6039546040516001600160a01b038084169216907fc6b66e0e282673c442421e1c6b89458b7631f26f5dcd0b2b216c45831ca1d7d5905f90a3603980546001600160a01b0319166001600160a01b0392909216919091179055565b5f611fb36122a6565b5f516020615a3c5f395f51905f525f5260026020525f5160206159dc5f395f51905f525460ff16611ff75760405163e553ef8560e01b815260040160405180910390fd5b603954600160a01b900460ff1661202157604051634a908ac760e11b815260040160405180910390fd5b6039805460ff60a01b19169055603854604051631bfc726f60e21b815273d7c8bb6708e989fc61a4ac025ecf4c0ed6b90eb491636ff1c9bc91612070916001600160a01b031690600401614e89565b602060405180830381865af415801561208b573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120af91906156f4565b90507f9998b9f8aa8b3b8014117736f15ce06e6c325fd656f7d88ecca7b29d600fd754816040516120e291815260200190565b60405180910390a190565b6120f56122a6565b6120fe81612979565b600d546040516001600160a01b038084169216907fd9d6b85b6d670cd443496fc6d03390f739bbff47f96a8e33fb0cdd52ad26f5c2905f90a3600d80546001600160a01b0319166001600160a01b0392909216919091179055565b6121616122a6565b610fc2816133f5565b6117786122a6565b335f908152602081815260408083206001600160a01b038616845290915290205460ff161515811515036121b95760405163b1a94de960e01b815260040160405180910390fd5b335f818152602081815260408083206001600160a01b03871680855290835292819020805460ff1916861515908117909155905190815291929182917fd5e969f01efe921d3f766bdebad25f0a05e3f237311f56482bf132d0326309c0910160405180910390a45050565b61222c6122a6565b5f6122356133d1565b80546001600160a01b0319166001600160a01b038416908117825590915061225b611ac7565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a35050565b61229c6122a6565b610d3e8282612b64565b336122af611ac7565b6001600160a01b031614611743573360405163118cdaa760e01b815260040161119a9190614e89565b6122e182612979565b600a546001600160a01b03908116908316036123105760405163fc91449760e01b815260040160405180910390fd5b610d3e8282613458565b5f6112ae612326613523565b8360405161190160f01b8152600281019290925260228201526042902090565b5f836001600160a01b03163b5f036123a4575f5f6123648585613531565b5090925090505f81600381111561237d5761237d615535565b14801561239b5750856001600160a01b0316826001600160a01b0316145b925050506123b2565b6123af84848461357a565b90505b9392505050565b603a546001600160a01b038281165f818152603b60205260409081902054600554600480546038549451635a561e7560e11b81529182019790975260ff909216151560248301526044820193909352918316606483015261010090930482166084820152911660a482015273d7c8bb6708e989fc61a4ac025ecf4c0ed6b90eb49063b4ac3cea9060c4015f6040518083038186803b158015612459575f5ffd5b505af415801561246b573d5f5f3e3d5ffd5b5050506001600160a01b0382165f818152603b6020526040808220805460ff19166001908117909155603a8054918201815583527fa2999d817b6757290b50e8ecf3fa939673403dd35c97de392fdb343b4015ce9e0180546001600160a01b03191684179055519192507ff3e4c2c64e71e6ba2eaab9a599bced62f9eb91d2cda610bf41aa8c80ff2cf82691a250565b5f807ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00611e2f565b61252b613650565b8051602082015161253b90612979565b6125488160e00151612979565b6125558160400151612979565b604082015115806125715750670de0b6b3a76400008260800151115b80612584575081606001518160c0015110155b8061259a5750670de0b6b3a76400008260600151115b156125b85760405163fc91449760e01b815260040160405180910390fd5b6125c0613675565b6125cb81600361367d565b60608201516033819055604080515f815260208101929092527f37734fca9f253a81e2893a3dc65f94f53caa23cff074b1fcaaa679c6618ff109910160405180910390a16020820151603280546001600160a01b0319166001600160a01b0390921691821790556040515f907f1caf1e415bbf6b44cff7c784e551494a5748817c5ee20c0a8b7f26dfc49e9c39908290a36126698260400151612e8d565b600680546001600160801b0319166001600160801b039290921691909117905560408281015181515f815260208101919091527f1099cd9f9ddfd0f163da23e6cfa1b521a78ad68d1a3ba76f683a9ed854943556910160405180910390a160808201516035819055604080515f815260208101929092527f49dbba69a16a62cba637f2214d89fa57fa1b2dac288502fca505113d191240f79101611726565b60808101515160208201516040808401516005546060860151925163856b2a5b60e01b81526001600160a01b039485166004820152602481019290925283166044820152911660648201525f90819073d7c8bb6708e989fc61a4ac025ecf4c0ed6b90eb49063856b2a5b906084016040805180830381865af4158015612790573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127b4919061570b565b6020860151603680546001600160a01b039283166001600160a01b03199182161790915560408801516037556038805483851692169190911790556060870151603980546001600160a81b0319169190921617600160a01b17905590925090505f5b8381101561284c576128448560800151828151811061283757612837615738565b60200260200101516123b9565b600101612816565b50603b5f826001600160a01b031663f7c618c16040518163ffffffff1660e01b8152600401602060405180830381865afa15801561288c573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128b0919061574c565b6001600160a01b0316815260208101919091526040015f205460ff166128e95760405163fc91449760e01b815260040160405180910390fd5b806001600160a01b0316846040015185602001516001600160a01b03167f7dc50a634e8ac3e02ed0cceb9a21ec3ce3226c661eeed5c9731aec51e9d683858588606001516040516129509291906001600160a01b0392831681529116602082015260400190565b60405180910390a450505050565b5f5f60405163021f521960e51b815260040160405180910390fd5b6001600160a01b038116610fc2576040516358d86ebd60e01b815260040160405180910390fd5b5f815f036129b7576034546001600160801b031691505b6129c082612e8d565b603480545f906129da9084906001600160801b0316615767565b92506101000a8154816001600160801b0302191690836001600160801b03160217905550815f14612a1d57600d54612a1d9030906001600160a01b031684613325565b600d546040518381526001600160a01b03909116907ff9984c8173c4b4ff9cc454f76ed19c053f4490ccb224fd9ddffeb4ef4bea35309060200160405180910390a25090565b7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00805460011901612aa757604051633ee5aeb560e01b815260040160405180910390fd5b60029055565b60017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0055565b5f5f5f612adf87612fc1565b8315612afe5760405163c8126e6360e01b815260040160405180910390fd5b5f612b0d8a8a8a8a8a8a613a24565b600654603c54600754949e50929c509093506001600160801b0390811692612b369291166156b5565b1115612b555760405163828435f760e01b815260040160405180910390fd5b98999798979650505050505050565b60405163021f521960e51b815260040160405180910390fd5b306001600160a01b037f000000000000000000000000886bbdc1b5e264b919fb5bbb4b3ebd1243b86027161480612c0357507f000000000000000000000000886bbdc1b5e264b919fb5bbb4b3ebd1243b860276001600160a01b0316612bf75f5160206159fc5f395f51905f52546001600160a01b031690565b6001600160a01b031614155b156117435760405163703e46dd60e11b815260040160405180910390fd5b610fc26122a6565b816001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa925050508015612c83575060408051601f3d908101601f19168201909252612c80918101906156f4565b60015b612ca25781604051634c9c8ce360e01b815260040161119a9190614e89565b5f5160206159fc5f395f51905f528114612cd257604051632a87526960e21b81526004810182905260240161119a565b6117a58383613dee565b306001600160a01b037f000000000000000000000000886bbdc1b5e264b919fb5bbb4b3ebd1243b8602716146117435760405163703e46dd60e11b815260040160405180910390fd5b600a54600654600754604051636f0a79c360e01b81526001600160801b039283166004820152911660248201525f9182916001600160a01b0390911690636f0a79c39060440160408051808303815f875af1158015612d86573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612daa9190615786565b91509150815f14610d3e57612dbe82612e8d565b600780545f90612dd89084906001600160801b03166157a8565b92506101000a8154816001600160801b0302191690836001600160801b03160217905550612e0582612e8d565b603480545f90612e1f9084906001600160801b03166157a8565b82546101009290920a6001600160801b0381810219909316918316021790915560075460065460408051868152602081018890529284169083015290911660608201527f09879000b63e0bf6c32bfdb8a19d3f69266bfce49f7755caae358a65b0c30a5a9150608001611726565b5f6001600160801b03821115612eb6576040516303fcd3a560e01b815260040160405180910390fd5b5090565b5f612ec36133d1565b80546001600160a01b03191681559050610d3e82613e43565b6001600160a01b038116612f035760405163253de67360e01b815260040160405180910390fd5b600b546040516001600160a01b038084169216907fb7261e9c33aa7c56209c3bf60b424a8f9551ce28876c0ab3d0c487695e943487905f90a3600b80546001600160a01b0319166001600160a01b0392909216919091179055565b6001600160a01b0383165f818152600360209081526040808320868452825291829020805460ff19168515159081179091558251868152918201527f401fe6257c73ed319c2871c4950de4700b99658b381d2168c833b0c4eb52babd9101611d6b565b6032546001600160a01b03828116911614610fc257604051637f491adf60e11b815260040160405180910390fd5b5f5f612ffa83613eb3565b90505f61301260335483613f9690919063ffffffff16565b90508061301e85613fb4565b11949350505050565b603954600160a01b900460ff16156130ed576038546040516324b0820160e01b815273d7c8bb6708e989fc61a4ac025ecf4c0ed6b90eb4916324b082019161307d916001600160a01b03169085906004016156c8565b5f6040518083038186803b158015613093575f5ffd5b505af41580156130a5573d5f5f3e3d5ffd5b50505050816001600160a01b03167ffd1f751d6710c4879825e2063777b717670add453a19e3bd1968196207e8aa98826040516130e491815260200190565b60405180910390a25b610d3e8282613ff6565b7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10090565b60605f6131266130f7565b9050806002018054613137906157c7565b80601f0160208091040260200160405190810160405280929190818152602001828054613163906157c7565b80156131ae5780601f10613185576101008083540402835291602001916131ae565b820191905f5260205f20905b81548152906001019060200180831161319157829003601f168201915b505050505091505090565b60605f6131c46130f7565b9050806003018054613137906157c7565b5f5f5f6040516339e396c960e01b815260040160405180910390fd5b5f5f6131fc33612fc1565b61320583612fc1565b61320d612d25565b6034546001600160801b031615613229576132275f6129a0565b505b61120285858561400d565b5f516020615a3c5f395f51905f528203610d3e57801561325657610d3e612d25565b600a54604051637c3bfe2760e11b815282151560048201526001600160a01b039091169063f877fc4e906024015b5f604051808303815f87803b15801561329b575f5ffd5b505af115801561113e573d5f5f3e3d5ffd5b5f6132b6612a63565b6132bf33612fc1565b6132c882612fc1565b6132d283836141fb565b9050611e2f612aad565b5f6132e684612979565b81156133055760405163c8126e6360e01b815260040160405180910390fd5b61330e85612fc1565b61331b86868686866142de565b9695505050505050565b306001600160a01b0384160361339c57600480546040516340c10f1960e01b81526101009091046001600160a01b0316916340c10f199161336a9186918691016156c8565b5f604051808303815f87803b158015613381575f5ffd5b505af1158015613393573d5f5f3e3d5ffd5b50505050505050565b60048054604051632770a7eb60e21b81526101009091046001600160a01b031691639dc29fac9161336a9187918691016156c8565b7f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c0090565b60335481106134175760405163fc91449760e01b815260040160405180910390fd5b600c5460408051918252602082018390527f4f0b060f766324f442578ff1f6aea17b16b5c0b66f16b6f21edf689bfdffd80d910160405180910390a1600c55565b5f516020615a3c5f395f51905f525f5260026020525f5160206159dc5f395f51905f525460ff1615801561348a575080155b1561349757613497612d25565b600a546040516001600160a01b038085169216907f91392d9529f68f736b760c529c8ab9bd67e10618ce79f361e18b8ff152221512905f90a3600a80546001600160a01b0319166001600160a01b03841690811790915515610d3e57600a54604051636dcea85f60e01b81526001600160a01b0390911690636dcea85f90613284903090600401614e89565b5f61352c6144de565b905090565b5f5f5f8351604103613568576020840151604085015160608601515f1a61355a88828585614551565b955095509550505050613573565b505081515f91506002905b9250925092565b5f5f5f856001600160a01b0316858560405160240161359a9291906157ff565b60408051601f198184030181529181526020820180516001600160e01b0316630b135d3f60e11b179052516135cf9190615817565b5f60405180830381855afa9150503d805f8114613607576040519150601f19603f3d011682016040523d82523d5f602084013e61360c565b606091505b509150915081801561362057506020815110155b801561331b57508051630b135d3f60e11b9061364590830160209081019084016156f4565b149695505050505050565b61365861460f565b61174357604051631afcd79f60e31b815260040160405180910390fd5b611743613650565b613685613650565b6004805482919060ff191660018360038111156136a4576136a4615535565b021790555081516001600160a01b031615806136cb575060208201516001600160a01b0316155b806136e1575060808201516001600160a01b0316155b806136f7575060a08201516001600160a01b0316155b156137155760405163253de67360e01b815260040160405180910390fd5b670de0b6b3a76400008260c0015111156137425760405163253de67360e01b815260040160405180910390fd5b815160048054610100600160a81b0319166101006001600160a01b039384168102919091179091556020840151600580546001600160a01b031990811692851692909217905590840151600e8054909216921691821790556040515f907f1457447b4f8c4f1383eb399705615641dc1167b81ef64e51725dd83b25ae1f86908290a3600e546001600160a01b03161561383357600e5460405163a9c3b95560e01b81526001600160a01b039091169063a9c3b95590613805903090600401614e89565b5f604051808303815f87803b15801561381c575f5ffd5b505af115801561382e573d5f5f3e3d5ffd5b505050505b604082810151600a80546001600160a01b0319166001600160a01b03909216918217905590515f907f91392d9529f68f736b760c529c8ab9bd67e10618ce79f361e18b8ff152221512908290a360a0820151600b80546001600160a01b0319166001600160a01b0390921691821790556040515f907fb7261e9c33aa7c56209c3bf60b424a8f9551ce28876c0ab3d0c487695e943487908290a360c0820151600c819055604080515f815260208101929092527f4f0b060f766324f442578ff1f6aea17b16b5c0b66f16b6f21edf689bfdffd80d910160405180910390a160e0820151600d80546001600160a01b0319166001600160a01b0390921691821790556040515f907fd9d6b85b6d670cd443496fc6d03390f739bbff47f96a8e33fb0cdd52ad26f5c2908290a3600a546001600160a01b0316156139cd57600a54604051636dcea85f60e01b81526001600160a01b0390911690636dcea85f9061399f903090600401614e89565b5f604051808303815f87803b1580156139b6575f5ffd5b505af11580156139c8573d5f5f3e3d5ffd5b505050505b6139ea82608001515f516020615a3c5f395f51905f526001612f5e565b613a0782608001515f5160206159bc5f395f51905f526001612f5e565b613a148260600151614628565b613a1c614639565b610d3e614680565b5f5f5f613a318989614690565b1580613a4457506001600160a01b038616155b15613a625760405163253de67360e01b815260040160405180910390fd5b613a6b876146b5565b613a8857604051636fba12b160e01b815260040160405180910390fd5b613a90612d25565b5f895f03613b0a575f613aac613aa560355490565b8b906146ef565b600754909150613ad19082906001600160801b0380821691600160801b90041661470b565b9150613add818b6156b5565b600754909a50613b02908b906001600160801b0380821691600160801b900416614731565b9a5050613b4a565b613b16613aa560355490565b9050613b22818b6156b5565b600754909a50613b47908b906001600160801b0380821691600160801b900416614756565b98505b613b538a612e8d565b600780545f90613b6d9084906001600160801b03166157a8565b92506101000a8154816001600160801b0302191690836001600160801b03160217905550613b9a89612e8d565b60078054601090613bbc908490600160801b90046001600160801b03166157a8565b82546101009290920a6001600160801b03818102199093169183160217909155600654600754908216911611159050613c085760405163828435f760e01b815260040160405180910390fd5b613c1189612e8d565b6001600160a01b0389165f9081526008602052604090208054601090613c48908490600160801b90046001600160801b03166157a8565b92506101000a8154816001600160801b0302191690836001600160801b031602179055505f818b613c7991906156e1565b9050613c86308983613325565b5f8215613c9957613c9683614772565b90505b6001600160a01b0389165f9081526009602052604090205460ff1615613d3e575f879003613cda5760405163253de67360e01b815260040160405180910390fd5b60405163cef01ba360e01b81526001600160a01b038a169063cef01ba390613d0c9085908e908d908d9060040161582d565b5f604051808303815f87803b158015613d23575f5ffd5b505af1158015613d35573d5f5f3e3d5ffd5b50505050613d5d565b8615613d5d57604051636fba12b160e01b815260040160405180910390fd5b613d668a6147c2565b613d8357604051631065af7f60e21b815260040160405180910390fd5b60408051838152602081018d9052908101849052606081018290526001600160a01b03808b1691908c169033907f445cc7189b699aba312bd54ce4e386e25919e7992981f28a29855412132fce9c9060800160405180910390a450999a989950979650505050505050565b613df78261482e565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a2805115613e3b576117a58282614888565b610d3e6148f1565b7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930080546001600160a01b031981166001600160a01b03848116918217845560405192169182907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a3505050565b5f5f600b5f9054906101000a90046001600160a01b03166001600160a01b03166398d5fdca6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613f05573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613f2991906156f4565b9050805f03613f4b5760405163163551f360e01b815260040160405180910390fd5b6001600160a01b0383165f908152600860205260408120600101546001600160801b031690613f8e90829084906ec097ce7bc90715b34b9f100000000090614910565b949350505050565b5f670de0b6b3a7640000613faa8385615873565b611e2c919061589e565b6001600160a01b0381165f908152600860205260408120546007546001600160801b03600160801b928390048116926123b2928492818116929091041661470b565b600554610d3e906001600160a01b03168383614946565b5f5f6140198585614690565b158061402c57506001600160a01b038316155b1561404a5760405163253de67360e01b815260040160405180910390fd5b614052612d25565b845f036140825760075461407b9085906001600160801b0380821691600160801b90041661470b565b94506140a7565b6007546140a49086906001600160801b0380821691600160801b90041661499e565b93505b6140b085612e8d565b600780545f906140ca9084906001600160801b0316615767565b92506101000a8154816001600160801b0302191690836001600160801b031602179055506140f784612e8d565b60078054601090614119908490600160801b90046001600160801b0316615767565b92506101000a8154816001600160801b0302191690836001600160801b0316021790555061414684612e8d565b6001600160a01b0384165f908152600860205260409020805460109061417d908490600160801b90046001600160801b0316615767565b92506101000a8154816001600160801b0302191690836001600160801b031602179055506141ac333087613325565b60408051868152602081018690526001600160a01b0385169133917fe4a1ae657f49cb1fb1c7d3a94ae6093565c4c8c0e03de488f79c377c3c3a24e0910160405180910390a350929391925050565b5f82158061421057506001600160a01b038216155b1561422e5760405163253de67360e01b815260040160405180910390fd5b61423783612e8d565b6001600160a01b0383165f908152600860205260408120600101805490919061426a9084906001600160801b03166157a8565b92506101000a8154816001600160801b0302191690836001600160801b03160217905550614297836149ba565b6040518381526001600160a01b0383169033907fa32435755c235de2976ed44a75a2f85cb01faf0c894f639fe0c32bb9455fea8f9060200160405180910390a35090919050565b5f8515806142f357506001600160a01b038516155b156143115760405163253de67360e01b815260040160405180910390fd5b61431a856146b5565b61433757604051636fba12b160e01b815260040160405180910390fd5b61433f612d25565b61434886612e8d565b6001600160a01b0386165f908152600860205260408120600101805490919061437b9084906001600160801b0316615767565b92506101000a8154816001600160801b0302191690836001600160801b031602179055506143a98487613027565b6001600160a01b0384165f9081526009602052604090205460ff1680156143cf57508115155b1561443857604051631e9ad06b60e01b81526001600160a01b03851690631e9ad06b9061440690899089908890889060040161582d565b5f604051808303815f87803b15801561441d575f5ffd5b505af115801561442f573d5f5f3e3d5ffd5b50505050614457565b811561445757604051636fba12b160e01b815260040160405180910390fd5b614460856147c2565b61447d57604051630df3ade160e01b815260040160405180910390fd5b836001600160a01b0316856001600160a01b0316336001600160a01b03167fabbccae251882e9f89a99740b415b291a053e1d8e2c1cf8f603c50b94ed7bc33896040516144cc91815260200190565b60405180910390a45093949350505050565b5f7f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f614508614a76565b614510614adb565b60408051602081019490945283019190915260608201524660808201523060a082015260c00160405160208183030381529060405280519060200120905090565b5f80806fa2a8918ca85bafe22016d0b997e4df60600160ff1b0384111561458057505f91506003905082614605565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa1580156145d1573d5f5f3e3d5ffd5b5050604051601f1901519150506001600160a01b0381166145fc57505f925060019150829050614605565b92505f91508190505b9450945094915050565b5f6146186124fb565b54600160401b900460ff16919050565b614630613650565b610fc281614b1a565b614641613650565b61174360405180604001604052806004815260200163416c746f60e01b815250604051806040016040528060018152602001603160f81b815250614b4b565b614688613650565b611743614b5d565b5f8215801561469e57508115155b80611e2c57508215801590611e2c57505015919050565b5f336001600160a01b03831614806112ae5750506001600160a01b03165f9081526020818152604080832033845290915290205460ff1690565b5f611e2c6146fd8385615873565b670de0b6b3a7640000614b65565b5f6123af61471a6001856156b5565b614727620f4240856156b5565b8691906001614910565b5f6123af6147406001856156b5565b61474d620f4240856156b5565b8691905f614910565b5f6123af614767620f4240846156b5565b6147276001866156b5565b5f61477c82612e8d565b603480545f906147969084906001600160801b03166157a8565b92506101000a8154816001600160801b0302191690836001600160801b031602179055505f9050919050565b6001600160a01b0381165f90815260086020526040812054600160801b90046001600160801b031681036147f857506001919050565b5f61480283613eb3565b90505f61481a600c5483613f9690919063ffffffff16565b905061482584613fb4565b11159392505050565b806001600160a01b03163b5f0361485a5780604051634c9c8ce360e01b815260040161119a9190614e89565b5f5160206159fc5f395f51905f5280546001600160a01b0319166001600160a01b0392909216919091179055565b60605f5f846001600160a01b0316846040516148a49190615817565b5f60405180830381855af49150503d805f81146148dc576040519150601f19603f3d011682016040523d82523d5f602084013e6148e1565b606091505b5091509150611eaa858383614b98565b34156117435760405163b398979f60e01b815260040160405180910390fd5b5f81156149315761492a6149248587615873565b84614b65565b9050613f8e565b8261493c8587615873565b611eaa919061589e565b6117a583846001600160a01b031663a9059cbb858560405160240161496c9291906156c8565b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050614beb565b5f6123af6149af620f4240846156b5565b61474d6001866156b5565b603954600160a01b900460ff166149e45760405163fc91449760e01b815260040160405180910390fd5b6149ed81614c54565b60055460365460375460405163b6727e1960e01b81526001600160a01b03938416600482015292909116602483015260448201526064810182905273d7c8bb6708e989fc61a4ac025ecf4c0ed6b90eb49063b6727e19906084015f6040518083038186803b158015614a5d575f5ffd5b505af4158015614a6f573d5f5f3e3d5ffd5b5050505050565b5f5f614a806130f7565b90505f614a8b61311b565b805190915015614aa357805160209091012092915050565b81548015614ab2579392505050565b7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470935050505090565b5f5f614ae56130f7565b90505f614af06131b9565b805190915015614b0857805160209091012092915050565b60018201548015614ab2579392505050565b614b22613650565b6001600160a01b038116611778575f604051631e4fbdf760e01b815260040161119a9190614e89565b614b53613650565b610d3e8282614c6c565b612aad613650565b5f815f03614b7757614b776012614cab565b816001840381614b8957614b8961588a565b04600101831515029392505050565b606082614bad57614ba882614cbc565b6123b2565b8151158015614bc457506001600160a01b0384163b155b15614be45783604051639996b31560e01b815260040161119a9190614e89565b50806123b2565b5f5f60205f8451602086015f885af180614c0a576040513d5f823e3d81fd5b50505f513d91508115614c21578060011415614c2e565b6001600160a01b0384163b155b15614c4e5783604051635274afe760e01b815260040161119a9190614e89565b50505050565b600554610fc2906001600160a01b0316333084614ce4565b614c74613650565b5f614c7d6130f7565b905060028101614c8d8482615901565b5060038101614c9c8382615901565b505f8082556001909101555050565b634e487b715f52806020526024601cfd5b805115614ccb57805160208201fd5b60405163d6bda27560e01b815260040160405180910390fd5b614c4e84856001600160a01b03166323b872dd86868660405160240161496c9392919061560b565b6001600160a01b0381168114610fc2575f5ffd5b80356112b181614d0c565b803580151581146112b1575f5ffd5b5f5f60408385031215614d4b575f5ffd5b8235614d5681614d0c565b9150614d6460208401614d2b565b90509250929050565b634e487b7160e01b5f52604160045260245ffd5b60405160a081016001600160401b0381118282101715614da357614da3614d6d565b60405290565b60405161012081016001600160401b0381118282101715614da357614da3614d6d565b604051601f8201601f191681016001600160401b0381118282101715614df457614df4614d6d565b604052919050565b5f5f828403610100811215614e0f575f5ffd5b60a0811215614e1c575f5ffd5b614e24614d81565b8435614e2f81614d0c565b81526020850135614e3f81614d0c565b6020820152614e5060408601614d2b565b60408201526060858101358183015260808087013590830152909350609f1982011215614e7b575f5ffd5b5060a0830190509250929050565b6001600160a01b0391909116815260200190565b5f60208284031215614ead575f5ffd5b81356123b281614d0c565b5f60208284031215614ec8575f5ffd5b5035919050565b5f6001600160401b03821115614ee757614ee7614d6d565b5060051b60200190565b5f82601f830112614f00575f5ffd5b8135614f13614f0e82614ecf565b614dcc565b8082825260208201915060208360051b860101925085831115614f34575f5ffd5b602085015b83811015614f5a578035614f4c81614d0c565b835260209283019201614f39565b5095945050505050565b5f60208284031215614f74575f5ffd5b81356001600160401b03811115614f89575f5ffd5b8201808403610220811215614f9c575f5ffd5b614fa4614d81565b6101a0821215614fb2575f5ffd5b614fba614d81565b610120831215614fc8575f5ffd5b614fd0614da9565b9250614fdb84614d20565b8352614fe960208501614d20565b6020840152614ffa60408501614d20565b604084015261500b60608501614d20565b606084015261501c60808501614d20565b608084015261502d60a08501614d20565b60a084015260c0848101359084015261504860e08501614d20565b60e084015261505a6101008501614d20565b6101008401528281526150706101208501614d20565b6020820152610140840135604082015261016084013560608201526101808401356080820181905290825291506150aa6101a08401614d20565b60208201526101c08301356040820181905291506150cb6101e08401614d20565b606082015261020083013591506001600160401b038211156150eb575f5ffd5b6150f786838501614ef1565b608082015295945050505050565b5f5f5f60608486031215615117575f5ffd5b8335925060208401359150604084013561513081614d0c565b809150509250925092565b5f8151808452602084019350602083015f5b8281101561516b57815186526020958601959091019060010161514d565b5093949350505050565b602081525f611e2c602083018461513b565b5f5f83601f840112615197575f5ffd5b5081356001600160401b038111156151ad575f5ffd5b60208301915083602082850101111561194d575f5ffd5b5f5f5f5f5f5f60a087890312156151d9575f5ffd5b863595506020870135945060408701356151f281614d0c565b9350606087013561520281614d0c565b925060808701356001600160401b0381111561521c575f5ffd5b61522889828a01615187565b979a9699509497509295939492505050565b5f5f6040838503121561524b575f5ffd5b823561525681614d0c565b946020939093013593505050565b5f5f60408385031215615275575f5ffd5b823561528081614d0c565b915060208301356001600160401b0381111561529a575f5ffd5b8301601f810185136152aa575f5ffd5b80356001600160401b038111156152c3576152c3614d6d565b6152d6601f8201601f1916602001614dcc565b8181528660208385010111156152ea575f5ffd5b816020840160208301375f602083830101528093505050509250929050565b5f5f5f5f6080858703121561531c575f5ffd5b8435935060208501359250604085013561533581614d0c565b9150606085013561534581614d0c565b939692955090935050565b5f5f60408385031215615361575f5ffd5b823561536c81614d0c565b9150602083013561537c81614d0c565b809150509250929050565b5f5f5f60608486031215615399575f5ffd5b83356153a481614d0c565b9250602084013591506153b960408501614d2b565b90509250925092565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b60ff60f81b8816815260e060208201525f61540e60e08301896153c2565b828103604084015261542081896153c2565b606084018890526001600160a01b038716608085015260a0840186905283810360c08501529050615451818561513b565b9a9950505050505050505050565b5f5f5f5f5f60608688031215615473575f5ffd5b853561547e81614d0c565b945060208601356001600160401b03811115615498575f5ffd5b6154a488828901615187565b90955093505060408601356001600160401b038111156154c2575f5ffd5b6154ce88828901615187565b969995985093965092949392505050565b602081525f611e2c60208301846153c2565b5f5f60408385031215615502575f5ffd5b82359150614d6460208401614d2b565b5f5f60408385031215615523575f5ffd5b82359150602083013561537c81614d0c565b634e487b7160e01b5f52602160045260245ffd5b602081016004831061556957634e487b7160e01b5f52602160045260245ffd5b91905290565b5f5f5f5f5f60808688031215615583575f5ffd5b85359450602086013561559581614d0c565b935060408601356155a581614d0c565b925060608601356001600160401b038111156154c2575f5ffd5b634e487b7160e01b5f52601160045260245ffd5b5f600182016155e4576155e46155bf565b5060010190565b5f602082840312156155fb575f5ffd5b813560ff811681146123b2575f5ffd5b6001600160a01b039384168152919092166020820152604081019190915260600190565b5f6020828403121561563f575f5ffd5b81516001600160401b03811115615654575f5ffd5b8201601f81018413615664575f5ffd5b8051615672614f0e82614ecf565b8082825260208201915060208360051b850101925086831115615693575f5ffd5b6020840193505b8284101561331b57835182526020938401939091019061569a565b80820180821115611e2f57611e2f6155bf565b6001600160a01b03929092168252602082015260400190565b81810381811115611e2f57611e2f6155bf565b5f60208284031215615704575f5ffd5b5051919050565b5f5f6040838503121561571c575f5ffd5b825161572781614d0c565b602084015190925061537c81614d0c565b634e487b7160e01b5f52603260045260245ffd5b5f6020828403121561575c575f5ffd5b81516123b281614d0c565b6001600160801b038281168282160390811115611e2f57611e2f6155bf565b5f5f60408385031215615797575f5ffd5b505080516020909101519092909150565b6001600160801b038181168382160190811115611e2f57611e2f6155bf565b600181811c908216806157db57607f821691505b6020821081036157f957634e487b7160e01b5f52602260045260245ffd5b50919050565b828152604060208201525f6123af60408301846153c2565b5f82518060208501845e5f920191825250919050565b8481526001600160a01b03841660208201526060604082018190528101829052818360808301375f818301608090810191909152601f909201601f191601019392505050565b8082028115828204841417611e2f57611e2f6155bf565b634e487b7160e01b5f52601260045260245ffd5b5f826158b857634e487b7160e01b5f52601260045260245ffd5b500490565b601f8211156117a557805f5260205f20601f840160051c810160208510156158e25750805b601f840160051c820191505b81811015614a6f575f81556001016158ee565b81516001600160401b0381111561591a5761591a614d6d565b61592e8161592884546157c7565b846158bd565b6020601f821160018114615960575f83156159495750848201515b5f19600385901b1c1916600184901b178455614a6f565b5f84815260208120601f198516915b8281101561598f578785015182556020948501946001909201910161596f565b50848210156159ac57868401515f19600387901b60f8161c191681555b50505050600190811b0190555056fe587e479931b32b4bcfb1625b83bf110c2402b6e624bcdc3b8ff7d5fb2ffe3350de98d7c08d23b7d4e1dfa601c5ce140785716410cf765aa1938f7112dbcb4e9e360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc4511b33380d79edebecfedff607cbd4ea5334b23b6dcba33466bf64ecdc4a86331533cf09d9fd562a4609906b5c62508f0dd93bd2222c49d6a9d4cd4326f5725a2646970667358221220bd09b992313a387b1eb072a1ebb63c33cbc5e6c922c3f63e792a8bcc12357ecf64736f6c634300081c0033","optimization_enabled":true,"verified_twin_address_hash":null,"is_verified":true,"compiler_settings":{"evmVersion":"cancun","libraries":{"contracts/lending/credit-market/AltoConvexCreditLineMarket.sol:AltoConvexCreditLineLib":"0xd7c8bb6708e989fc61a4ac025ecf4c0ed6b90eb4"},"metadata":{"bytecodeHash":"ipfs"},"optimizer":{"enabled":true,"runs":100},"remappings":[":@alto-test/=test/",":@alto/=contracts/",":@bundler3/=lib/bundler3/",":@chainlink/=lib/chainlink-evm/",":@erc4626-tests/=lib/erc4626-tests/",":@layerzerolabs/=node_modules/@layerzerolabs/",":@morpho-org/bundler3/=lib/bundler3/src/",":@morpho-org/irm/=lib/morpho-blue-irm/src/",":@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",":@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",":@uniswap/v3-core/=lib/v3-core/",":bundler3/=lib/bundler3/",":chainlink-evm/=lib/chainlink-evm/",":deployments/=contracts/deployments/",":ds-test/=lib/morpho-blue-irm/lib/forge-std/lib/ds-test/src/",":erc4626-tests/=lib/erc4626-tests/",":forge-gas-snapshot/=lib/bundler3/lib/permit2/lib/forge-gas-snapshot/src/",":forge-std/=lib/forge-std/src/",":halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",":morpho-blue-irm/=lib/morpho-blue-irm/src/",":morpho-blue/=lib/bundler3/lib/morpho-blue/",":openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",":openzeppelin-contracts/=lib/bundler3/lib/openzeppelin-contracts/",":openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",":permit2/=lib/bundler3/lib/permit2/",":solidity-bytes-utils/=node_modules/solidity-bytes-utils/",":solmate/=lib/morpho-blue-irm/lib/solmate/src/",":v3-core/=lib/v3-core/"]},"optimization_runs":100,"sourcify_repo_url":"https://repo.sourcify.dev/contracts/partial_match/1/0x886bBDc1b5E264B919fB5bBb4B3Ebd1243B86027/","decoded_constructor_args":null,"compiler_version":"0.8.28+commit.7893614a","is_verified_via_verifier_alliance":false,"verified_at":"2026-09-25T01:22:39.286915Z","implementations":[],"proxy_type":null,"external_libraries":[{"name":"contracts/lending/credit-market/AltoConvexCreditLineMarket.sol:AltoConvexCreditLineLib","address_hash":"0xd7c8bB6708E989fc61A4AC025EcF4c0eD6b90Eb4"}],"creation_bytecode":"0x60a060405230608052348015610013575f5ffd5b5061001c610021565b6100d3565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000900460ff16156100715760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b03908116146100d05780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b608051615a916100f95f395f8181612b8801528181612bb10152612ce70152615a915ff3fe608060405260043610610388575f3560e01c806379ba5097116101d9578063bb14516c11610100578063e529ee9511610099578063e529ee9514610c49578063e5ca1fd414610c5e578063e74b981b14610c72578063e76ed98614610c91578063e7c646e914610cb0578063eecea00014610ccf578063f2fde38b14610cee578063f774bbaf14610d0d578063fbb922cd14610d0d575f5ffd5b8063bb14516c14610b27578063cadac47914610b46578063d0b2ca3414610b65578063d558f62714610b93578063dcd6f52614610bb9578063dd81aac014610bd8578063e084142814610bf7578063e30c397814610c16578063e521136f14610c2a575f5ffd5b8063959916dc11610172578063959916dc146109965780639e9e4666146109aa578063a6afed95146109d8578063a866442e146109ec578063ad3cb1cc14610a0b578063b1e8f8ef14610a48578063b2016bd414610a67578063b5fd73f814610a86578063b7648fb914610ab4575f5ffd5b806379ba50971461087e5780637adbf973146108925780637dc0d1d0146108b15780637df65b26146108d057806380cd33c0146108ef57806383b597471461090e57806384b0196e1461092d5780638da5cb5b1461095457806393930dce14610968575f5ffd5b806344bf3c72116102bd57806352d1902d1161025657806352d1902d1461076e578063563d4f64146107825780635ab6ced4146107975780635e36746a146107ac57806365e4ad9e146107cb5780636d0a1218146108015780636d8500701461082057806370ae92d21461083f578063715018a61461086a575f5ffd5b806344bf3c7214610639578063456dc17a14610658578063469048401461067c57806348780d2e1461069b5780634c19386c146106d45780634d298abd146106fe5780634f1ef2861461071d578063509b6c3f146107305780635100b5671461074f575f5ffd5b806328e8fe7d1161032f57806328e8fe7d146104d45780632cdacb50146104f35780632d7bd628146105125780632eb375ea14610546578063372500ab146105735780633a12c6da146105945780633d509c97146105a95780633e6950ab146105c85780633fcebaf4146105ff575f5ffd5b806303fce1851461038c5780630a3ce376146103ad578063176dfd89146103e257806317f333401461040157806318160ddd1461042d5780631c03e6cc146104775780631d93f7a114610496578063250313e2146104b5575b5f5ffd5b348015610397575f5ffd5b506103ab6103a6366004614d3a565b610d2c565b005b3480156103b8575f5ffd5b506039546103cd90600160a01b900460ff1681565b60405190151581526020015b60405180910390f35b3480156103ed575f5ffd5b506103ab6103fc366004614dfc565b610d42565b34801561040c575f5ffd5b50603954610420906001600160a01b031681565b6040516103d99190614e89565b348015610438575f5ffd5b50600654610457906001600160801b0380821691600160801b90041682565b604080516001600160801b039384168152929091166020830152016103d9565b348015610482575f5ffd5b506103ab610491366004614e9d565b610fb1565b3480156104a1575f5ffd5b506103ab6104b0366004614eb8565b610fc5565b3480156104c0575f5ffd5b506103ab6104cf366004614f64565b611044565b3480156104df575f5ffd5b50600a54610420906001600160a01b031681565b3480156104fe575f5ffd5b50603654610420906001600160a01b031681565b34801561051d575f5ffd5b5061053161052c366004615105565b611146565b604080519283526020830191909152016103d9565b348015610551575f5ffd5b50610565610560366004614eb8565b61120e565b6040519081526020016103d9565b34801561057e575f5ffd5b506105876112b6565b6040516103d99190615175565b34801561059f575f5ffd5b50610565600c5481565b3480156105b4575f5ffd5b506103ab6105c3366004614e9d565b61135c565b3480156105d3575f5ffd5b506034546105e7906001600160801b031681565b6040516001600160801b0390911681526020016103d9565b34801561060a575f5ffd5b5061061e6106193660046151c4565b61141b565b604080519384526020840192909252908201526060016103d9565b348015610644575f5ffd5b50600e54610420906001600160a01b031681565b348015610663575f5ffd5b506004546104209061010090046001600160a01b031681565b348015610687575f5ffd5b50600d54610420906001600160a01b031681565b3480156106a6575f5ffd5b506103cd6106b536600461523a565b600360209081525f928352604080842090915290825290205460ff1681565b3480156106df575f5ffd5b50600754610457906001600160801b0380821691600160801b90041682565b348015610709575f5ffd5b506103ab610718366004614e9d565b6114f9565b6103ab61072b366004615264565b61150a565b34801561073b575f5ffd5b5061042061074a366004614eb8565b611525565b34801561075a575f5ffd5b506103ab610769366004614eb8565b61154d565b348015610779575f5ffd5b506105656115bf565b34801561078d575f5ffd5b50610565603c5481565b3480156107a2575f5ffd5b5061056560335481565b3480156107b7575f5ffd5b506105316107c6366004615309565b6115da565b3480156107d6575f5ffd5b506103cd6107e5366004615350565b5f60208181529281526040808220909352908152205460ff1681565b34801561080c575f5ffd5b50603254610420906001600160a01b031681565b34801561082b575f5ffd5b506103ab61083a366004614eb8565b61164b565b34801561084a575f5ffd5b50610565610859366004614e9d565b60016020525f908152604090205481565b348015610875575f5ffd5b506103ab611732565b348015610889575f5ffd5b506103ab611745565b34801561089d575f5ffd5b506103ab6108ac366004614e9d565b611781565b3480156108bc575f5ffd5b50600b54610420906001600160a01b031681565b3480156108db575f5ffd5b506103ab6108ea366004615387565b611792565b3480156108fa575f5ffd5b50610531610909366004614d3a565b6117aa565b348015610919575f5ffd5b506103ab610928366004614e9d565b611954565b348015610938575f5ffd5b50610941611a23565b6040516103d997969594939291906153f0565b34801561095f575f5ffd5b50610420611ac7565b348015610973575f5ffd5b506103cd610982366004614e9d565b600f6020525f908152604090205460ff1681565b3480156109a1575f5ffd5b50603554610565565b3480156109b5575f5ffd5b506103cd6109c4366004614eb8565b60026020525f908152604090205460ff1681565b3480156109e3575f5ffd5b506103ab611afb565b3480156109f7575f5ffd5b5061061e610a0636600461545f565b611b57565b348015610a16575f5ffd5b50610a3b604051806040016040528060058152602001640352e302e360dc1b81525081565b6040516103d991906154df565b348015610a53575f5ffd5b50610531610a62366004615105565b611c13565b348015610a72575f5ffd5b50600554610420906001600160a01b031681565b348015610a91575f5ffd5b506103cd610aa0366004614e9d565b603b6020525f908152604090205460ff1681565b348015610abf575f5ffd5b50610afd610ace366004614e9d565b60086020525f9081526040902080546001909101546001600160801b0380831692600160801b90048116911683565b604080516001600160801b03948516815292841660208401529216918101919091526060016103d9565b348015610b32575f5ffd5b506103ab610b413660046154f1565b611c76565b348015610b51575f5ffd5b50610565610b60366004615512565b611d78565b348015610b70575f5ffd5b506103cd610b7f366004614e9d565b60096020525f908152604090205460ff1681565b348015610b9e575f5ffd5b50600454610bac9060ff1681565b6040516103d99190615549565b348015610bc4575f5ffd5b50603854610420906001600160a01b031681565b348015610be3575f5ffd5b50610565610bf236600461556f565b611e35565b348015610c02575f5ffd5b506103ab610c11366004614eb8565b611eb3565b348015610c21575f5ffd5b50610420611f33565b348015610c35575f5ffd5b506103ab610c44366004614e9d565b611f3d565b348015610c54575f5ffd5b5061056560375481565b348015610c69575f5ffd5b50610565611faa565b348015610c7d575f5ffd5b506103ab610c8c366004614e9d565b6120ed565b348015610c9c575f5ffd5b506103ab610cab366004614eb8565b612159565b348015610cbb575f5ffd5b506103ab610cca366004614e9d565b61216a565b348015610cda575f5ffd5b506103ab610ce9366004614d3a565b612172565b348015610cf9575f5ffd5b506103ab610d08366004614e9d565b612224565b348015610d18575f5ffd5b506103ab610d27366004614d3a565b612294565b610d346122a6565b610d3e82826122d8565b5050565b8160800151421115610d675760405163fd1d678360e01b815260040160405180910390fd5b81516001600160a01b03165f908152600160205260408120805491610d8b836155d3565b91905055826060015114610db2576040516338a8556160e01b815260040160405180910390fd5b604080517fdc4e086394e5096a6add5d5327f22bea47783d5150bbc2440a258e94a12df54860208083019190915284516001600160a01b039081168385015290850151166060808301919091529184015115156080808301919091529184015160a08201529083015160c08201525f9060e0016040516020818303038152906040528051906020012090505f610e478261231a565b84519091505f90610eae908360208701803590604089013590610e6a908a6155eb565b604051602001610e9a93929190928352602083019190915260f81b6001600160f81b031916604082015260410190565b604051602081830303815290604052612346565b905080610ece57604051637a0ddbd160e11b815260040160405180910390fd5b60408581015186516001600160a01b039081165f9081526020818152848220818b015184168352815290849020805460ff191693151593909317909255875160608901519351938452169133917fa58af1a0c70dba0c7aa60d1a1a147ebd61000d1690a968828ac718bca927f2c7910160405180910390a384602001516001600160a01b0316855f01516001600160a01b0316336001600160a01b03167fd5e969f01efe921d3f766bdebad25f0a05e3f237311f56482bf132d0326309c08860400151604051610fa2911515815260200190565b60405180910390a45050505050565b610fb96122a6565b610fc2816123b9565b50565b610fcd6122a6565b600c5481111580610fe55750670de0b6b3a764000081115b156110035760405163fc91449760e01b815260040160405180910390fd5b60335460408051918252602082018390527f37734fca9f253a81e2893a3dc65f94f53caa23cff074b1fcaaa679c6618ff109910160405180910390a1603355565b5f61104d6124fb565b805490915060ff600160401b82041615906001600160401b03165f811580156110735750825b90505f826001600160401b0316600114801561108e5750303b155b90508115801561109c575080155b156110ba5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff1916600117855583156110e457845460ff60401b1916600160401b1785555b85516110ef90612523565b6110f886612708565b831561113e57845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b505050505050565b5f516020615a3c5f395f51905f525f90815260026020525f5160206159dc5f395f51905f5254819060ff16156111a357604051638698dd2b60e01b81525f516020615a3c5f395f51905f5260048201526024015b60405180910390fd5b5f5160206159bc5f395f51905f525f5260026020525f516020615a1c5f395f51905f525460ff16156111f757604051638698dd2b60e01b81525f5160206159bc5f395f51905f52600482015260240161119a565b61120285858561295e565b91509150935093915050565b5f516020615a3c5f395f51905f525f90815260026020525f5160206159dc5f395f51905f525460ff161561126457604051638698dd2b60e01b81525f516020615a3c5f395f51905f52600482015260240161119a565b600d54611279906001600160a01b0316612979565b6034546001600160801b03168211156112a55760405163fc91449760e01b815260040160405180910390fd5b6112ae826129a0565b90505b919050565b60606112c0612a63565b6038546039546040516313c181cf60e11b815273d7c8bb6708e989fc61a4ac025ecf4c0ed6b90eb492632783039e9261130e926001600160a01b039283169290911690603a9060040161560b565b5f60405180830381865af4158015611328573d5f5f3e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261134f919081019061562f565b9050611359612aad565b90565b6113646122a6565b6038546040516308b3168160e21b8152603a6004820152603b60248201526001600160a01b039182166044820152908216606482015273d7c8bb6708e989fc61a4ac025ecf4c0ed6b90eb4906322cc5a04906084015f6040518083038186803b1580156113cf575f5ffd5b505af41580156113e1573d5f5f3e3d5ffd5b50506040516001600160a01b03841692507f66257bcef574219c04f7c05f7a1c78d599da10491294c92a5805c48b4cdf500991505f90a250565b5f516020615a3c5f395f51905f525f90815260026020525f5160206159dc5f395f51905f52548190819060ff161561147557604051638698dd2b60e01b81525f516020615a3c5f395f51905f52600482015260240161119a565b5f5160206159bc5f395f51905f525f5260026020525f516020615a1c5f395f51905f525460ff16156114c957604051638698dd2b60e01b81525f5160206159bc5f395f51905f52600482015260240161119a565b6114d1612a63565b6114df898989898989612ad3565b9250925092506114ed612aad565b96509650969350505050565b6115016122a6565b610fc281612b64565b611512612b7d565b61151b82612c21565b610d3e8282612c29565b603a8181548110611534575f80fd5b5f918252602090912001546001600160a01b0316905081565b6115556122a6565b670de0b6b3a764000081111561157e5760405163fc91449760e01b815260040160405180910390fd5b60355460408051918252602082018390527f49dbba69a16a62cba637f2214d89fa57fa1b2dac288502fca505113d191240f7910160405180910390a1603555565b5f6115c8612cdc565b505f5160206159fc5f395f51905f5290565b5f516020615a3c5f395f51905f525f90815260026020525f5160206159dc5f395f51905f5254819060ff161561163257604051638698dd2b60e01b81525f516020615a3c5f395f51905f52600482015260240161119a565b61163e8686868661295e565b9150915094509492505050565b6116536122a6565b5f516020615a3c5f395f51905f525f5260026020525f5160206159dc5f395f51905f525460ff1661168657611686612d25565b603c5460075482916116a0916001600160801b03166156b5565b11156116bf5760405163828435f760e01b815260040160405180910390fd5b6006546001600160801b03166116d482612e8d565b600680546001600160801b0319166001600160801b039290921691909117905560408051828152602081018490527f1099cd9f9ddfd0f163da23e6cfa1b521a78ad68d1a3ba76f683a9ed85494355691015b60405180910390a15050565b61173a6122a6565b6117435f612eba565b565b338061174f611f33565b6001600160a01b031614611778578060405163118cdaa760e01b815260040161119a9190614e89565b610fc281612eba565b6117896122a6565b610fc281612edc565b61179a6122a6565b6117a5838383612f5e565b505050565b5f5f6117b4612a63565b6117bc6122a6565b6117c584612fc1565b5f516020615a3c5f395f51905f525f5260026020525f5160206159dc5f395f51905f525460ff161580156117f7575082155b1561180457611804612d25565b61180d84612fef565b61182a5760405163093687eb60e01b815260040160405180910390fd5b50506001600160a01b0382165f908152600860205260408120600181015481546007805490859055603c80546001600160801b03948516969285169594600160801b909404909316928592906118819084906156b5565b90915550506040518381527f50033b418a5ee3b84a888e58b173ed55186161b36f84b47eb587b8894d86c9ea9060200160405180910390a181546001600160801b031682556001820180546001600160801b031916905583156118e8576118e83385613027565b60408051338152602081018690529081018490526001600160801b03821660608201526001600160a01b038716907ff5fb0963d72631ccb5b35b1f3211f8b7703485665806717f2a5c4231d33e86b39060800160405180910390a2505061194d612aad565b9250929050565b61195c6122a6565b61196581612979565b6032546001600160a01b03165f9081526008602052604090208054600160801b90046001600160801b03161515806119a9575060018101546001600160801b031615155b156119c757604051637393cb1b60e01b815260040160405180910390fd5b6032546040516001600160a01b038085169216907f1caf1e415bbf6b44cff7c784e551494a5748817c5ee20c0a8b7f26dfc49e9c39905f90a350603280546001600160a01b0319166001600160a01b0392909216919091179055565b5f6060805f5f5f60605f611a356130f7565b8054909150158015611a4957506001810154155b611a8d5760405162461bcd60e51b81526020600482015260156024820152741152540dcc4c8e88155b9a5b9a5d1a585b1a5e9959605a1b604482015260640161119a565b611a9561311b565b611a9d6131b9565b604080515f80825260208201909252600f60f81b9c939b5091995046985030975095509350915050565b5f807f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c1993005b546001600160a01b031692915050565b5f516020615a3c5f395f51905f525f5260026020525f5160206159dc5f395f51905f525460ff1615611b4f57604051638698dd2b60e01b81525f516020615a3c5f395f51905f52600482015260240161119a565b611743612d25565b5f516020615a3c5f395f51905f525f90815260026020525f5160206159dc5f395f51905f52548190819060ff1615611bb157604051638698dd2b60e01b81525f516020615a3c5f395f51905f52600482015260240161119a565b611bb9612a63565b611bfa88888888888080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152506131d592505050565b925092509250611c08612aad565b955095509592505050565b5f516020615a3c5f395f51905f525f90815260026020525f5160206159dc5f395f51905f5254819060ff1615611c6b57604051638698dd2b60e01b81525f516020615a3c5f395f51905f52600482015260240161119a565b6112028585856131f1565b335f908152600360209081526040808320858452909152902054829060ff16611cb657338160405163122994e360e11b815260040161119a9291906156c8565b611cc08383613234565b5f8381526002602052604090205482151560ff909116151503611d1c575f8381526002602052604090819020549051634363bf4f60e01b81526004810185905260ff90911615156024820152821515604482015260640161119a565b5f83815260026020908152604091829020805460ff191685151590811790915582518681529182015233917f33b87b74fe6b8ad758141301728df7c3aef0580734207b5484402185fd4c002491015b60405180910390a2505050565b5f516020615a3c5f395f51905f525f90815260026020525f5160206159dc5f395f51905f525460ff1615611dce57604051638698dd2b60e01b81525f516020615a3c5f395f51905f52600482015260240161119a565b5f5160206159bc5f395f51905f525f5260026020525f516020615a1c5f395f51905f525460ff1615611e2257604051638698dd2b60e01b81525f5160206159bc5f395f51905f52600482015260240161119a565b611e2c83836132ad565b90505b92915050565b5f516020615a3c5f395f51905f525f90815260026020525f5160206159dc5f395f51905f525460ff1615611e8b57604051638698dd2b60e01b81525f516020615a3c5f395f51905f52600482015260240161119a565b611e93612a63565b611ea086868686866132dc565b9050611eaa612aad565b95945050505050565b611ebb6122a6565b805f03611edb5760405163fc91449760e01b815260040160405180910390fd5b80603c5f828254611eec91906156e1565b90915550611efd9050333083613325565b6040518181527f400a13da53bfd3f099aeac0af799847596847105daf792ad35de00bbcbf9b44b9060200160405180910390a150565b5f5f611aeb6133d1565b611f4633612fc1565b611f4f81612979565b6039546040516001600160a01b038084169216907fc6b66e0e282673c442421e1c6b89458b7631f26f5dcd0b2b216c45831ca1d7d5905f90a3603980546001600160a01b0319166001600160a01b0392909216919091179055565b5f611fb36122a6565b5f516020615a3c5f395f51905f525f5260026020525f5160206159dc5f395f51905f525460ff16611ff75760405163e553ef8560e01b815260040160405180910390fd5b603954600160a01b900460ff1661202157604051634a908ac760e11b815260040160405180910390fd5b6039805460ff60a01b19169055603854604051631bfc726f60e21b815273d7c8bb6708e989fc61a4ac025ecf4c0ed6b90eb491636ff1c9bc91612070916001600160a01b031690600401614e89565b602060405180830381865af415801561208b573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120af91906156f4565b90507f9998b9f8aa8b3b8014117736f15ce06e6c325fd656f7d88ecca7b29d600fd754816040516120e291815260200190565b60405180910390a190565b6120f56122a6565b6120fe81612979565b600d546040516001600160a01b038084169216907fd9d6b85b6d670cd443496fc6d03390f739bbff47f96a8e33fb0cdd52ad26f5c2905f90a3600d80546001600160a01b0319166001600160a01b0392909216919091179055565b6121616122a6565b610fc2816133f5565b6117786122a6565b335f908152602081815260408083206001600160a01b038616845290915290205460ff161515811515036121b95760405163b1a94de960e01b815260040160405180910390fd5b335f818152602081815260408083206001600160a01b03871680855290835292819020805460ff1916861515908117909155905190815291929182917fd5e969f01efe921d3f766bdebad25f0a05e3f237311f56482bf132d0326309c0910160405180910390a45050565b61222c6122a6565b5f6122356133d1565b80546001600160a01b0319166001600160a01b038416908117825590915061225b611ac7565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a35050565b61229c6122a6565b610d3e8282612b64565b336122af611ac7565b6001600160a01b031614611743573360405163118cdaa760e01b815260040161119a9190614e89565b6122e182612979565b600a546001600160a01b03908116908316036123105760405163fc91449760e01b815260040160405180910390fd5b610d3e8282613458565b5f6112ae612326613523565b8360405161190160f01b8152600281019290925260228201526042902090565b5f836001600160a01b03163b5f036123a4575f5f6123648585613531565b5090925090505f81600381111561237d5761237d615535565b14801561239b5750856001600160a01b0316826001600160a01b0316145b925050506123b2565b6123af84848461357a565b90505b9392505050565b603a546001600160a01b038281165f818152603b60205260409081902054600554600480546038549451635a561e7560e11b81529182019790975260ff909216151560248301526044820193909352918316606483015261010090930482166084820152911660a482015273d7c8bb6708e989fc61a4ac025ecf4c0ed6b90eb49063b4ac3cea9060c4015f6040518083038186803b158015612459575f5ffd5b505af415801561246b573d5f5f3e3d5ffd5b5050506001600160a01b0382165f818152603b6020526040808220805460ff19166001908117909155603a8054918201815583527fa2999d817b6757290b50e8ecf3fa939673403dd35c97de392fdb343b4015ce9e0180546001600160a01b03191684179055519192507ff3e4c2c64e71e6ba2eaab9a599bced62f9eb91d2cda610bf41aa8c80ff2cf82691a250565b5f807ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00611e2f565b61252b613650565b8051602082015161253b90612979565b6125488160e00151612979565b6125558160400151612979565b604082015115806125715750670de0b6b3a76400008260800151115b80612584575081606001518160c0015110155b8061259a5750670de0b6b3a76400008260600151115b156125b85760405163fc91449760e01b815260040160405180910390fd5b6125c0613675565b6125cb81600361367d565b60608201516033819055604080515f815260208101929092527f37734fca9f253a81e2893a3dc65f94f53caa23cff074b1fcaaa679c6618ff109910160405180910390a16020820151603280546001600160a01b0319166001600160a01b0390921691821790556040515f907f1caf1e415bbf6b44cff7c784e551494a5748817c5ee20c0a8b7f26dfc49e9c39908290a36126698260400151612e8d565b600680546001600160801b0319166001600160801b039290921691909117905560408281015181515f815260208101919091527f1099cd9f9ddfd0f163da23e6cfa1b521a78ad68d1a3ba76f683a9ed854943556910160405180910390a160808201516035819055604080515f815260208101929092527f49dbba69a16a62cba637f2214d89fa57fa1b2dac288502fca505113d191240f79101611726565b60808101515160208201516040808401516005546060860151925163856b2a5b60e01b81526001600160a01b039485166004820152602481019290925283166044820152911660648201525f90819073d7c8bb6708e989fc61a4ac025ecf4c0ed6b90eb49063856b2a5b906084016040805180830381865af4158015612790573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127b4919061570b565b6020860151603680546001600160a01b039283166001600160a01b03199182161790915560408801516037556038805483851692169190911790556060870151603980546001600160a81b0319169190921617600160a01b17905590925090505f5b8381101561284c576128448560800151828151811061283757612837615738565b60200260200101516123b9565b600101612816565b50603b5f826001600160a01b031663f7c618c16040518163ffffffff1660e01b8152600401602060405180830381865afa15801561288c573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128b0919061574c565b6001600160a01b0316815260208101919091526040015f205460ff166128e95760405163fc91449760e01b815260040160405180910390fd5b806001600160a01b0316846040015185602001516001600160a01b03167f7dc50a634e8ac3e02ed0cceb9a21ec3ce3226c661eeed5c9731aec51e9d683858588606001516040516129509291906001600160a01b0392831681529116602082015260400190565b60405180910390a450505050565b5f5f60405163021f521960e51b815260040160405180910390fd5b6001600160a01b038116610fc2576040516358d86ebd60e01b815260040160405180910390fd5b5f815f036129b7576034546001600160801b031691505b6129c082612e8d565b603480545f906129da9084906001600160801b0316615767565b92506101000a8154816001600160801b0302191690836001600160801b03160217905550815f14612a1d57600d54612a1d9030906001600160a01b031684613325565b600d546040518381526001600160a01b03909116907ff9984c8173c4b4ff9cc454f76ed19c053f4490ccb224fd9ddffeb4ef4bea35309060200160405180910390a25090565b7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00805460011901612aa757604051633ee5aeb560e01b815260040160405180910390fd5b60029055565b60017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0055565b5f5f5f612adf87612fc1565b8315612afe5760405163c8126e6360e01b815260040160405180910390fd5b5f612b0d8a8a8a8a8a8a613a24565b600654603c54600754949e50929c509093506001600160801b0390811692612b369291166156b5565b1115612b555760405163828435f760e01b815260040160405180910390fd5b98999798979650505050505050565b60405163021f521960e51b815260040160405180910390fd5b306001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161480612c0357507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316612bf75f5160206159fc5f395f51905f52546001600160a01b031690565b6001600160a01b031614155b156117435760405163703e46dd60e11b815260040160405180910390fd5b610fc26122a6565b816001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa925050508015612c83575060408051601f3d908101601f19168201909252612c80918101906156f4565b60015b612ca25781604051634c9c8ce360e01b815260040161119a9190614e89565b5f5160206159fc5f395f51905f528114612cd257604051632a87526960e21b81526004810182905260240161119a565b6117a58383613dee565b306001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146117435760405163703e46dd60e11b815260040160405180910390fd5b600a54600654600754604051636f0a79c360e01b81526001600160801b039283166004820152911660248201525f9182916001600160a01b0390911690636f0a79c39060440160408051808303815f875af1158015612d86573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612daa9190615786565b91509150815f14610d3e57612dbe82612e8d565b600780545f90612dd89084906001600160801b03166157a8565b92506101000a8154816001600160801b0302191690836001600160801b03160217905550612e0582612e8d565b603480545f90612e1f9084906001600160801b03166157a8565b82546101009290920a6001600160801b0381810219909316918316021790915560075460065460408051868152602081018890529284169083015290911660608201527f09879000b63e0bf6c32bfdb8a19d3f69266bfce49f7755caae358a65b0c30a5a9150608001611726565b5f6001600160801b03821115612eb6576040516303fcd3a560e01b815260040160405180910390fd5b5090565b5f612ec36133d1565b80546001600160a01b03191681559050610d3e82613e43565b6001600160a01b038116612f035760405163253de67360e01b815260040160405180910390fd5b600b546040516001600160a01b038084169216907fb7261e9c33aa7c56209c3bf60b424a8f9551ce28876c0ab3d0c487695e943487905f90a3600b80546001600160a01b0319166001600160a01b0392909216919091179055565b6001600160a01b0383165f818152600360209081526040808320868452825291829020805460ff19168515159081179091558251868152918201527f401fe6257c73ed319c2871c4950de4700b99658b381d2168c833b0c4eb52babd9101611d6b565b6032546001600160a01b03828116911614610fc257604051637f491adf60e11b815260040160405180910390fd5b5f5f612ffa83613eb3565b90505f61301260335483613f9690919063ffffffff16565b90508061301e85613fb4565b11949350505050565b603954600160a01b900460ff16156130ed576038546040516324b0820160e01b815273d7c8bb6708e989fc61a4ac025ecf4c0ed6b90eb4916324b082019161307d916001600160a01b03169085906004016156c8565b5f6040518083038186803b158015613093575f5ffd5b505af41580156130a5573d5f5f3e3d5ffd5b50505050816001600160a01b03167ffd1f751d6710c4879825e2063777b717670add453a19e3bd1968196207e8aa98826040516130e491815260200190565b60405180910390a25b610d3e8282613ff6565b7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10090565b60605f6131266130f7565b9050806002018054613137906157c7565b80601f0160208091040260200160405190810160405280929190818152602001828054613163906157c7565b80156131ae5780601f10613185576101008083540402835291602001916131ae565b820191905f5260205f20905b81548152906001019060200180831161319157829003601f168201915b505050505091505090565b60605f6131c46130f7565b9050806003018054613137906157c7565b5f5f5f6040516339e396c960e01b815260040160405180910390fd5b5f5f6131fc33612fc1565b61320583612fc1565b61320d612d25565b6034546001600160801b031615613229576132275f6129a0565b505b61120285858561400d565b5f516020615a3c5f395f51905f528203610d3e57801561325657610d3e612d25565b600a54604051637c3bfe2760e11b815282151560048201526001600160a01b039091169063f877fc4e906024015b5f604051808303815f87803b15801561329b575f5ffd5b505af115801561113e573d5f5f3e3d5ffd5b5f6132b6612a63565b6132bf33612fc1565b6132c882612fc1565b6132d283836141fb565b9050611e2f612aad565b5f6132e684612979565b81156133055760405163c8126e6360e01b815260040160405180910390fd5b61330e85612fc1565b61331b86868686866142de565b9695505050505050565b306001600160a01b0384160361339c57600480546040516340c10f1960e01b81526101009091046001600160a01b0316916340c10f199161336a9186918691016156c8565b5f604051808303815f87803b158015613381575f5ffd5b505af1158015613393573d5f5f3e3d5ffd5b50505050505050565b60048054604051632770a7eb60e21b81526101009091046001600160a01b031691639dc29fac9161336a9187918691016156c8565b7f237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c0090565b60335481106134175760405163fc91449760e01b815260040160405180910390fd5b600c5460408051918252602082018390527f4f0b060f766324f442578ff1f6aea17b16b5c0b66f16b6f21edf689bfdffd80d910160405180910390a1600c55565b5f516020615a3c5f395f51905f525f5260026020525f5160206159dc5f395f51905f525460ff1615801561348a575080155b1561349757613497612d25565b600a546040516001600160a01b038085169216907f91392d9529f68f736b760c529c8ab9bd67e10618ce79f361e18b8ff152221512905f90a3600a80546001600160a01b0319166001600160a01b03841690811790915515610d3e57600a54604051636dcea85f60e01b81526001600160a01b0390911690636dcea85f90613284903090600401614e89565b5f61352c6144de565b905090565b5f5f5f8351604103613568576020840151604085015160608601515f1a61355a88828585614551565b955095509550505050613573565b505081515f91506002905b9250925092565b5f5f5f856001600160a01b0316858560405160240161359a9291906157ff565b60408051601f198184030181529181526020820180516001600160e01b0316630b135d3f60e11b179052516135cf9190615817565b5f60405180830381855afa9150503d805f8114613607576040519150601f19603f3d011682016040523d82523d5f602084013e61360c565b606091505b509150915081801561362057506020815110155b801561331b57508051630b135d3f60e11b9061364590830160209081019084016156f4565b149695505050505050565b61365861460f565b61174357604051631afcd79f60e31b815260040160405180910390fd5b611743613650565b613685613650565b6004805482919060ff191660018360038111156136a4576136a4615535565b021790555081516001600160a01b031615806136cb575060208201516001600160a01b0316155b806136e1575060808201516001600160a01b0316155b806136f7575060a08201516001600160a01b0316155b156137155760405163253de67360e01b815260040160405180910390fd5b670de0b6b3a76400008260c0015111156137425760405163253de67360e01b815260040160405180910390fd5b815160048054610100600160a81b0319166101006001600160a01b039384168102919091179091556020840151600580546001600160a01b031990811692851692909217905590840151600e8054909216921691821790556040515f907f1457447b4f8c4f1383eb399705615641dc1167b81ef64e51725dd83b25ae1f86908290a3600e546001600160a01b03161561383357600e5460405163a9c3b95560e01b81526001600160a01b039091169063a9c3b95590613805903090600401614e89565b5f604051808303815f87803b15801561381c575f5ffd5b505af115801561382e573d5f5f3e3d5ffd5b505050505b604082810151600a80546001600160a01b0319166001600160a01b03909216918217905590515f907f91392d9529f68f736b760c529c8ab9bd67e10618ce79f361e18b8ff152221512908290a360a0820151600b80546001600160a01b0319166001600160a01b0390921691821790556040515f907fb7261e9c33aa7c56209c3bf60b424a8f9551ce28876c0ab3d0c487695e943487908290a360c0820151600c819055604080515f815260208101929092527f4f0b060f766324f442578ff1f6aea17b16b5c0b66f16b6f21edf689bfdffd80d910160405180910390a160e0820151600d80546001600160a01b0319166001600160a01b0390921691821790556040515f907fd9d6b85b6d670cd443496fc6d03390f739bbff47f96a8e33fb0cdd52ad26f5c2908290a3600a546001600160a01b0316156139cd57600a54604051636dcea85f60e01b81526001600160a01b0390911690636dcea85f9061399f903090600401614e89565b5f604051808303815f87803b1580156139b6575f5ffd5b505af11580156139c8573d5f5f3e3d5ffd5b505050505b6139ea82608001515f516020615a3c5f395f51905f526001612f5e565b613a0782608001515f5160206159bc5f395f51905f526001612f5e565b613a148260600151614628565b613a1c614639565b610d3e614680565b5f5f5f613a318989614690565b1580613a4457506001600160a01b038616155b15613a625760405163253de67360e01b815260040160405180910390fd5b613a6b876146b5565b613a8857604051636fba12b160e01b815260040160405180910390fd5b613a90612d25565b5f895f03613b0a575f613aac613aa560355490565b8b906146ef565b600754909150613ad19082906001600160801b0380821691600160801b90041661470b565b9150613add818b6156b5565b600754909a50613b02908b906001600160801b0380821691600160801b900416614731565b9a5050613b4a565b613b16613aa560355490565b9050613b22818b6156b5565b600754909a50613b47908b906001600160801b0380821691600160801b900416614756565b98505b613b538a612e8d565b600780545f90613b6d9084906001600160801b03166157a8565b92506101000a8154816001600160801b0302191690836001600160801b03160217905550613b9a89612e8d565b60078054601090613bbc908490600160801b90046001600160801b03166157a8565b82546101009290920a6001600160801b03818102199093169183160217909155600654600754908216911611159050613c085760405163828435f760e01b815260040160405180910390fd5b613c1189612e8d565b6001600160a01b0389165f9081526008602052604090208054601090613c48908490600160801b90046001600160801b03166157a8565b92506101000a8154816001600160801b0302191690836001600160801b031602179055505f818b613c7991906156e1565b9050613c86308983613325565b5f8215613c9957613c9683614772565b90505b6001600160a01b0389165f9081526009602052604090205460ff1615613d3e575f879003613cda5760405163253de67360e01b815260040160405180910390fd5b60405163cef01ba360e01b81526001600160a01b038a169063cef01ba390613d0c9085908e908d908d9060040161582d565b5f604051808303815f87803b158015613d23575f5ffd5b505af1158015613d35573d5f5f3e3d5ffd5b50505050613d5d565b8615613d5d57604051636fba12b160e01b815260040160405180910390fd5b613d668a6147c2565b613d8357604051631065af7f60e21b815260040160405180910390fd5b60408051838152602081018d9052908101849052606081018290526001600160a01b03808b1691908c169033907f445cc7189b699aba312bd54ce4e386e25919e7992981f28a29855412132fce9c9060800160405180910390a450999a989950979650505050505050565b613df78261482e565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a2805115613e3b576117a58282614888565b610d3e6148f1565b7f9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c19930080546001600160a01b031981166001600160a01b03848116918217845560405192169182907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a3505050565b5f5f600b5f9054906101000a90046001600160a01b03166001600160a01b03166398d5fdca6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613f05573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613f2991906156f4565b9050805f03613f4b5760405163163551f360e01b815260040160405180910390fd5b6001600160a01b0383165f908152600860205260408120600101546001600160801b031690613f8e90829084906ec097ce7bc90715b34b9f100000000090614910565b949350505050565b5f670de0b6b3a7640000613faa8385615873565b611e2c919061589e565b6001600160a01b0381165f908152600860205260408120546007546001600160801b03600160801b928390048116926123b2928492818116929091041661470b565b600554610d3e906001600160a01b03168383614946565b5f5f6140198585614690565b158061402c57506001600160a01b038316155b1561404a5760405163253de67360e01b815260040160405180910390fd5b614052612d25565b845f036140825760075461407b9085906001600160801b0380821691600160801b90041661470b565b94506140a7565b6007546140a49086906001600160801b0380821691600160801b90041661499e565b93505b6140b085612e8d565b600780545f906140ca9084906001600160801b0316615767565b92506101000a8154816001600160801b0302191690836001600160801b031602179055506140f784612e8d565b60078054601090614119908490600160801b90046001600160801b0316615767565b92506101000a8154816001600160801b0302191690836001600160801b0316021790555061414684612e8d565b6001600160a01b0384165f908152600860205260409020805460109061417d908490600160801b90046001600160801b0316615767565b92506101000a8154816001600160801b0302191690836001600160801b031602179055506141ac333087613325565b60408051868152602081018690526001600160a01b0385169133917fe4a1ae657f49cb1fb1c7d3a94ae6093565c4c8c0e03de488f79c377c3c3a24e0910160405180910390a350929391925050565b5f82158061421057506001600160a01b038216155b1561422e5760405163253de67360e01b815260040160405180910390fd5b61423783612e8d565b6001600160a01b0383165f908152600860205260408120600101805490919061426a9084906001600160801b03166157a8565b92506101000a8154816001600160801b0302191690836001600160801b03160217905550614297836149ba565b6040518381526001600160a01b0383169033907fa32435755c235de2976ed44a75a2f85cb01faf0c894f639fe0c32bb9455fea8f9060200160405180910390a35090919050565b5f8515806142f357506001600160a01b038516155b156143115760405163253de67360e01b815260040160405180910390fd5b61431a856146b5565b61433757604051636fba12b160e01b815260040160405180910390fd5b61433f612d25565b61434886612e8d565b6001600160a01b0386165f908152600860205260408120600101805490919061437b9084906001600160801b0316615767565b92506101000a8154816001600160801b0302191690836001600160801b031602179055506143a98487613027565b6001600160a01b0384165f9081526009602052604090205460ff1680156143cf57508115155b1561443857604051631e9ad06b60e01b81526001600160a01b03851690631e9ad06b9061440690899089908890889060040161582d565b5f604051808303815f87803b15801561441d575f5ffd5b505af115801561442f573d5f5f3e3d5ffd5b50505050614457565b811561445757604051636fba12b160e01b815260040160405180910390fd5b614460856147c2565b61447d57604051630df3ade160e01b815260040160405180910390fd5b836001600160a01b0316856001600160a01b0316336001600160a01b03167fabbccae251882e9f89a99740b415b291a053e1d8e2c1cf8f603c50b94ed7bc33896040516144cc91815260200190565b60405180910390a45093949350505050565b5f7f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f614508614a76565b614510614adb565b60408051602081019490945283019190915260608201524660808201523060a082015260c00160405160208183030381529060405280519060200120905090565b5f80806fa2a8918ca85bafe22016d0b997e4df60600160ff1b0384111561458057505f91506003905082614605565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa1580156145d1573d5f5f3e3d5ffd5b5050604051601f1901519150506001600160a01b0381166145fc57505f925060019150829050614605565b92505f91508190505b9450945094915050565b5f6146186124fb565b54600160401b900460ff16919050565b614630613650565b610fc281614b1a565b614641613650565b61174360405180604001604052806004815260200163416c746f60e01b815250604051806040016040528060018152602001603160f81b815250614b4b565b614688613650565b611743614b5d565b5f8215801561469e57508115155b80611e2c57508215801590611e2c57505015919050565b5f336001600160a01b03831614806112ae5750506001600160a01b03165f9081526020818152604080832033845290915290205460ff1690565b5f611e2c6146fd8385615873565b670de0b6b3a7640000614b65565b5f6123af61471a6001856156b5565b614727620f4240856156b5565b8691906001614910565b5f6123af6147406001856156b5565b61474d620f4240856156b5565b8691905f614910565b5f6123af614767620f4240846156b5565b6147276001866156b5565b5f61477c82612e8d565b603480545f906147969084906001600160801b03166157a8565b92506101000a8154816001600160801b0302191690836001600160801b031602179055505f9050919050565b6001600160a01b0381165f90815260086020526040812054600160801b90046001600160801b031681036147f857506001919050565b5f61480283613eb3565b90505f61481a600c5483613f9690919063ffffffff16565b905061482584613fb4565b11159392505050565b806001600160a01b03163b5f0361485a5780604051634c9c8ce360e01b815260040161119a9190614e89565b5f5160206159fc5f395f51905f5280546001600160a01b0319166001600160a01b0392909216919091179055565b60605f5f846001600160a01b0316846040516148a49190615817565b5f60405180830381855af49150503d805f81146148dc576040519150601f19603f3d011682016040523d82523d5f602084013e6148e1565b606091505b5091509150611eaa858383614b98565b34156117435760405163b398979f60e01b815260040160405180910390fd5b5f81156149315761492a6149248587615873565b84614b65565b9050613f8e565b8261493c8587615873565b611eaa919061589e565b6117a583846001600160a01b031663a9059cbb858560405160240161496c9291906156c8565b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050614beb565b5f6123af6149af620f4240846156b5565b61474d6001866156b5565b603954600160a01b900460ff166149e45760405163fc91449760e01b815260040160405180910390fd5b6149ed81614c54565b60055460365460375460405163b6727e1960e01b81526001600160a01b03938416600482015292909116602483015260448201526064810182905273d7c8bb6708e989fc61a4ac025ecf4c0ed6b90eb49063b6727e19906084015f6040518083038186803b158015614a5d575f5ffd5b505af4158015614a6f573d5f5f3e3d5ffd5b5050505050565b5f5f614a806130f7565b90505f614a8b61311b565b805190915015614aa357805160209091012092915050565b81548015614ab2579392505050565b7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470935050505090565b5f5f614ae56130f7565b90505f614af06131b9565b805190915015614b0857805160209091012092915050565b60018201548015614ab2579392505050565b614b22613650565b6001600160a01b038116611778575f604051631e4fbdf760e01b815260040161119a9190614e89565b614b53613650565b610d3e8282614c6c565b612aad613650565b5f815f03614b7757614b776012614cab565b816001840381614b8957614b8961588a565b04600101831515029392505050565b606082614bad57614ba882614cbc565b6123b2565b8151158015614bc457506001600160a01b0384163b155b15614be45783604051639996b31560e01b815260040161119a9190614e89565b50806123b2565b5f5f60205f8451602086015f885af180614c0a576040513d5f823e3d81fd5b50505f513d91508115614c21578060011415614c2e565b6001600160a01b0384163b155b15614c4e5783604051635274afe760e01b815260040161119a9190614e89565b50505050565b600554610fc2906001600160a01b0316333084614ce4565b614c74613650565b5f614c7d6130f7565b905060028101614c8d8482615901565b5060038101614c9c8382615901565b505f8082556001909101555050565b634e487b715f52806020526024601cfd5b805115614ccb57805160208201fd5b60405163d6bda27560e01b815260040160405180910390fd5b614c4e84856001600160a01b03166323b872dd86868660405160240161496c9392919061560b565b6001600160a01b0381168114610fc2575f5ffd5b80356112b181614d0c565b803580151581146112b1575f5ffd5b5f5f60408385031215614d4b575f5ffd5b8235614d5681614d0c565b9150614d6460208401614d2b565b90509250929050565b634e487b7160e01b5f52604160045260245ffd5b60405160a081016001600160401b0381118282101715614da357614da3614d6d565b60405290565b60405161012081016001600160401b0381118282101715614da357614da3614d6d565b604051601f8201601f191681016001600160401b0381118282101715614df457614df4614d6d565b604052919050565b5f5f828403610100811215614e0f575f5ffd5b60a0811215614e1c575f5ffd5b614e24614d81565b8435614e2f81614d0c565b81526020850135614e3f81614d0c565b6020820152614e5060408601614d2b565b60408201526060858101358183015260808087013590830152909350609f1982011215614e7b575f5ffd5b5060a0830190509250929050565b6001600160a01b0391909116815260200190565b5f60208284031215614ead575f5ffd5b81356123b281614d0c565b5f60208284031215614ec8575f5ffd5b5035919050565b5f6001600160401b03821115614ee757614ee7614d6d565b5060051b60200190565b5f82601f830112614f00575f5ffd5b8135614f13614f0e82614ecf565b614dcc565b8082825260208201915060208360051b860101925085831115614f34575f5ffd5b602085015b83811015614f5a578035614f4c81614d0c565b835260209283019201614f39565b5095945050505050565b5f60208284031215614f74575f5ffd5b81356001600160401b03811115614f89575f5ffd5b8201808403610220811215614f9c575f5ffd5b614fa4614d81565b6101a0821215614fb2575f5ffd5b614fba614d81565b610120831215614fc8575f5ffd5b614fd0614da9565b9250614fdb84614d20565b8352614fe960208501614d20565b6020840152614ffa60408501614d20565b604084015261500b60608501614d20565b606084015261501c60808501614d20565b608084015261502d60a08501614d20565b60a084015260c0848101359084015261504860e08501614d20565b60e084015261505a6101008501614d20565b6101008401528281526150706101208501614d20565b6020820152610140840135604082015261016084013560608201526101808401356080820181905290825291506150aa6101a08401614d20565b60208201526101c08301356040820181905291506150cb6101e08401614d20565b606082015261020083013591506001600160401b038211156150eb575f5ffd5b6150f786838501614ef1565b608082015295945050505050565b5f5f5f60608486031215615117575f5ffd5b8335925060208401359150604084013561513081614d0c565b809150509250925092565b5f8151808452602084019350602083015f5b8281101561516b57815186526020958601959091019060010161514d565b5093949350505050565b602081525f611e2c602083018461513b565b5f5f83601f840112615197575f5ffd5b5081356001600160401b038111156151ad575f5ffd5b60208301915083602082850101111561194d575f5ffd5b5f5f5f5f5f5f60a087890312156151d9575f5ffd5b863595506020870135945060408701356151f281614d0c565b9350606087013561520281614d0c565b925060808701356001600160401b0381111561521c575f5ffd5b61522889828a01615187565b979a9699509497509295939492505050565b5f5f6040838503121561524b575f5ffd5b823561525681614d0c565b946020939093013593505050565b5f5f60408385031215615275575f5ffd5b823561528081614d0c565b915060208301356001600160401b0381111561529a575f5ffd5b8301601f810185136152aa575f5ffd5b80356001600160401b038111156152c3576152c3614d6d565b6152d6601f8201601f1916602001614dcc565b8181528660208385010111156152ea575f5ffd5b816020840160208301375f602083830101528093505050509250929050565b5f5f5f5f6080858703121561531c575f5ffd5b8435935060208501359250604085013561533581614d0c565b9150606085013561534581614d0c565b939692955090935050565b5f5f60408385031215615361575f5ffd5b823561536c81614d0c565b9150602083013561537c81614d0c565b809150509250929050565b5f5f5f60608486031215615399575f5ffd5b83356153a481614d0c565b9250602084013591506153b960408501614d2b565b90509250925092565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b60ff60f81b8816815260e060208201525f61540e60e08301896153c2565b828103604084015261542081896153c2565b606084018890526001600160a01b038716608085015260a0840186905283810360c08501529050615451818561513b565b9a9950505050505050505050565b5f5f5f5f5f60608688031215615473575f5ffd5b853561547e81614d0c565b945060208601356001600160401b03811115615498575f5ffd5b6154a488828901615187565b90955093505060408601356001600160401b038111156154c2575f5ffd5b6154ce88828901615187565b969995985093965092949392505050565b602081525f611e2c60208301846153c2565b5f5f60408385031215615502575f5ffd5b82359150614d6460208401614d2b565b5f5f60408385031215615523575f5ffd5b82359150602083013561537c81614d0c565b634e487b7160e01b5f52602160045260245ffd5b602081016004831061556957634e487b7160e01b5f52602160045260245ffd5b91905290565b5f5f5f5f5f60808688031215615583575f5ffd5b85359450602086013561559581614d0c565b935060408601356155a581614d0c565b925060608601356001600160401b038111156154c2575f5ffd5b634e487b7160e01b5f52601160045260245ffd5b5f600182016155e4576155e46155bf565b5060010190565b5f602082840312156155fb575f5ffd5b813560ff811681146123b2575f5ffd5b6001600160a01b039384168152919092166020820152604081019190915260600190565b5f6020828403121561563f575f5ffd5b81516001600160401b03811115615654575f5ffd5b8201601f81018413615664575f5ffd5b8051615672614f0e82614ecf565b8082825260208201915060208360051b850101925086831115615693575f5ffd5b6020840193505b8284101561331b57835182526020938401939091019061569a565b80820180821115611e2f57611e2f6155bf565b6001600160a01b03929092168252602082015260400190565b81810381811115611e2f57611e2f6155bf565b5f60208284031215615704575f5ffd5b5051919050565b5f5f6040838503121561571c575f5ffd5b825161572781614d0c565b602084015190925061537c81614d0c565b634e487b7160e01b5f52603260045260245ffd5b5f6020828403121561575c575f5ffd5b81516123b281614d0c565b6001600160801b038281168282160390811115611e2f57611e2f6155bf565b5f5f60408385031215615797575f5ffd5b505080516020909101519092909150565b6001600160801b038181168382160190811115611e2f57611e2f6155bf565b600181811c908216806157db57607f821691505b6020821081036157f957634e487b7160e01b5f52602260045260245ffd5b50919050565b828152604060208201525f6123af60408301846153c2565b5f82518060208501845e5f920191825250919050565b8481526001600160a01b03841660208201526060604082018190528101829052818360808301375f818301608090810191909152601f909201601f191601019392505050565b8082028115828204841417611e2f57611e2f6155bf565b634e487b7160e01b5f52601260045260245ffd5b5f826158b857634e487b7160e01b5f52601260045260245ffd5b500490565b601f8211156117a557805f5260205f20601f840160051c810160208510156158e25750805b601f840160051c820191505b81811015614a6f575f81556001016158ee565b81516001600160401b0381111561591a5761591a614d6d565b61592e8161592884546157c7565b846158bd565b6020601f821160018114615960575f83156159495750848201515b5f19600385901b1c1916600184901b178455614a6f565b5f84815260208120601f198516915b8281101561598f578785015182556020948501946001909201910161596f565b50848210156159ac57868401515f19600387901b60f8161c191681555b50505050600190811b0190555056fe587e479931b32b4bcfb1625b83bf110c2402b6e624bcdc3b8ff7d5fb2ffe3350de98d7c08d23b7d4e1dfa601c5ce140785716410cf765aa1938f7112dbcb4e9e360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc4511b33380d79edebecfedff607cbd4ea5334b23b6dcba33466bf64ecdc4a86331533cf09d9fd562a4609906b5c62508f0dd93bd2222c49d6a9d4cd4326f5725a2646970667358221220bd09b992313a387b1eb072a1ebb63c33cbc5e6c922c3f63e792a8bcc12357ecf64736f6c634300081c0033","name":"AltoConvexCreditLineMarket","is_blueprint":false,"license_type":"none","is_fully_verified":false,"is_verified_via_eth_bytecode_db":true,"language":"solidity","evm_version":"cancun","can_be_visualized_via_sol2uml":true,"is_verified_via_sourcify":true,"additional_sources":[{"file_path":"contracts/lending/AltoBaseMarket.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {AltoOwnable2StepUpgradeable} from \"@alto/utils/AltoOwnable2StepUpgradeable.sol\";\nimport {ReentrancyGuardUpgradeable} from \"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol\";\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport {UUPSUpgradeable} from \"@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol\";\n\nimport {Initializable} from \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport {ILendingOracle, LENDING_ORACLE_PRICE_PRECISION} from \"@alto/oracles/interfaces/IOracle.sol\";\n\nimport {\n    Balance,\n    Position,\n    BaseMarketInitParams,\n    MarketType,\n    IMarketStaticTypes,\n    IMarketBase\n} from \"@alto/lending/interfaces/IMarket.sol\";\nimport {AuthUpgradeable} from \"@alto/utils/AuthUpgradeable.sol\";\nimport {IIrm} from \"@alto/lending/interfaces/IIrm.sol\";\n\nimport {Uint128Converter} from \"./libraries/Uint128Converter.sol\";\n\nimport {FixedPointMath, MATH_PRECISION} from \"@alto/utils/FixedPointMath.sol\";\nimport {PAUSE_TYPE, FROZEN_TYPE} from \"@alto/utils/Constants.sol\";\nimport {Pausable, IPausable} from \"@alto/utils/Pausable.sol\";\nimport {AssetShareConversionMath} from \"@alto/lending/libraries/AssetShareConversionMath.sol\";\nimport {\n    IBorrowCallback,\n    IRemoveCollateralCallback,\n    ILiquidateCallback\n} from \"@alto/lending/interfaces/IMarketCallbacks.sol\";\nimport {\n    IAltoLiquidationEngine,\n    LiquidationEngineResult,\n    LiquidationEngineInput\n} from \"@alto/lending/interfaces/IAltoLiquidationEngine.sol\";\n\n/// @title Alto Base Market\n/// @author GPM\n/// @custom:contact security@altofoundation.org\n/// @notice An Isolated Borrow Market\nabstract contract AltoBaseMarket is\n    Initializable,\n    UUPSUpgradeable,\n    AltoOwnable2StepUpgradeable,\n    IMarketStaticTypes,\n    AuthUpgradeable,\n    Pausable,\n    ReentrancyGuardUpgradeable\n{\n    using FixedPointMath for uint256;\n    using AssetShareConversionMath for uint256;\n    using Uint128Converter for uint256;\n\n    using SafeERC20 for IERC20;\n\n    /// @inheritdoc IMarketBase\n    MarketType public MARKET_TYPE;\n\n    /// @inheritdoc IMarketBase\n    address public borrowToken;\n\n    /// @inheritdoc IMarketBase\n    address public collateralToken;\n\n    /// @inheritdoc IMarketStaticTypes\n    Balance public totalSupply;\n\n    /// @inheritdoc IMarketStaticTypes\n    Balance public totalBorrowed;\n\n    /// @inheritdoc IMarketStaticTypes\n    mapping(address => Position) public position;\n\n    /// @inheritdoc IMarketBase\n    mapping(address => bool) public authorizedCallbacks;\n\n    /// @inheritdoc IMarketBase\n    address public irm;\n\n    /// @inheritdoc IMarketBase\n    address public oracle;\n\n    /// @inheritdoc IMarketBase\n    uint256 public maxLtv;\n\n    /// @inheritdoc IMarketBase\n    address public feeRecipient;\n\n    /// @inheritdoc IMarketBase\n    address public liquidationEngine;\n\n    /// @inheritdoc IMarketBase\n    mapping(address => bool) public authorizedLiquidationPeriphery;\n\n    /// upgrade gap\n    uint256[34] private __gap_base;\n\n    function __AltoBaseMarket_init(BaseMarketInitParams memory _initParams, MarketType _marketType)\n        internal\n        onlyInitializing\n    {\n        MARKET_TYPE = _marketType;\n\n        if (\n            _initParams.borrowToken == address(0) || _initParams.collateralToken == address(0)\n                || _initParams.emergencyAdmin == address(0) || _initParams.oracle == address(0)\n        ) {\n            revert AltoBaseMarketInvalidInput();\n        }\n        if (_initParams.maxLtv > MATH_PRECISION) {\n            revert AltoBaseMarketInvalidInput();\n        }\n\n        borrowToken = _initParams.borrowToken;\n        collateralToken = _initParams.collateralToken;\n\n        liquidationEngine = _initParams.liquidationEngine;\n        emit SetLiquidationEngine(address(0), _initParams.liquidationEngine);\n\n        if (liquidationEngine != address(0)) {\n            IAltoLiquidationEngine(liquidationEngine).setMarketOnce(address(this));\n        }\n\n        irm = _initParams.irm;\n        emit SetIrm(address(0), _initParams.irm);\n\n        oracle = _initParams.oracle;\n        emit SetOracle(address(0), _initParams.oracle);\n\n        maxLtv = _initParams.maxLtv;\n        emit SetMaxLtv(0, _initParams.maxLtv);\n\n        feeRecipient = _initParams.feeRecipient;\n        emit SetFeeRecipient(address(0), _initParams.feeRecipient);\n\n        if (irm != address(0)) {\n            IIrm(irm).setMarket(address(this));\n        }\n\n        _setPauser(_initParams.emergencyAdmin, PAUSE_TYPE, true);\n        _setPauser(_initParams.emergencyAdmin, FROZEN_TYPE, true);\n\n        __Ownable_init(_initParams.owner);\n        __Auth_init();\n        __ReentrancyGuard_init();\n    }\n\n    /// @inheritdoc IMarketBase\n    function borrowOpeningFee() public view virtual returns (uint256);\n\n    /// @inheritdoc IMarketBase\n    function setIrm(address _irm, bool _skipAccrueInterest) external onlyOwner {\n        _setIrm(_irm, _skipAccrueInterest);\n    }\n\n    /// @dev See `IMarketBase.setIrm`.\n    function _setIrm(address _irm, bool _skipAccrueInterest) internal virtual {\n        if (!paused[PAUSE_TYPE] && !_skipAccrueInterest) {\n            _accrueInterest();\n        }\n\n        emit SetIrm(irm, _irm);\n        irm = _irm;\n\n        if (irm != address(0)) {\n            IIrm(irm).setMarket(address(this));\n        }\n    }\n\n    /// @inheritdoc IMarketBase\n    function setOracle(address _oracle) external onlyOwner {\n        _setOracle(_oracle);\n    }\n\n    /// @dev See `IMarketBase.setOracle`.\n    function _setOracle(address _oracle) internal virtual {\n        if (_oracle == address(0)) {\n            revert AltoBaseMarketInvalidInput();\n        }\n\n        emit SetOracle(oracle, _oracle);\n        oracle = _oracle;\n    }\n\n    /// @inheritdoc IMarketBase\n    function setMaxLtv(uint256 _maxLtv) external onlyOwner {\n        _setMaxLtv(_maxLtv);\n    }\n\n    /// @dev See `IMarketBase.setMaxLtv`.\n    function _setMaxLtv(uint256 _maxLtv) internal virtual {\n        uint256 maxLiquidationLtv = IAltoLiquidationEngine(liquidationEngine).minLltv();\n        if (_maxLtv > MATH_PRECISION || _maxLtv > maxLiquidationLtv) {\n            revert AltoBaseMarketInvalidInput();\n        }\n\n        emit SetMaxLtv(maxLtv, _maxLtv);\n        maxLtv = _maxLtv;\n    }\n\n    /// @inheritdoc IMarketBase\n    function setLiquidationEngine(address _liquidationEngine) external onlyOwner {\n        _setLiquidationEngine(_liquidationEngine);\n    }\n\n    /// @dev See `IMarketBase.setLiquidationEngine`.\n    function _setLiquidationEngine(address _liquidationEngine) internal virtual {\n        if (liquidationEngine == address(0) || _liquidationEngine == address(0)) {\n            revert AltoBaseMarketInvalidInput();\n        }\n\n        emit SetLiquidationEngine(liquidationEngine, _liquidationEngine);\n        liquidationEngine = _liquidationEngine;\n\n        IAltoLiquidationEngine(liquidationEngine).setMarketOnce(address(this));\n    }\n\n    /// @inheritdoc IMarketBase\n    function setAuthorizedLiquidationPeriphery(address periphery, bool value) external onlyOwner {\n        _setAuthorizedLiquidationPeriphery(periphery, value);\n    }\n\n    /// @dev See `IMarketBase.setAuthorizedLiquidationPeriphery`.\n    function _setAuthorizedLiquidationPeriphery(address periphery, bool value) internal virtual {\n        if (periphery == address(0)) {\n            revert AltoBaseMarketInvalidInput();\n        }\n\n        authorizedLiquidationPeriphery[periphery] = value;\n        emit SetAuthorizedLiquidationPeriphery(periphery, value);\n    }\n\n    /// @inheritdoc IMarketBase\n    function setAuthorizedCallback(address callback, bool value) external onlyOwner {\n        _setAuthorizedCallback(callback, value);\n    }\n\n    /// @dev See `IMarketBase.setAuthorizedCallback`.\n    function _setAuthorizedCallback(address callback, bool value) internal virtual {\n        if (callback == address(0)) {\n            revert AltoBaseMarketInvalidInput();\n        }\n\n        authorizedCallbacks[callback] = value;\n        emit SetAuthorizedCallback(callback, value);\n    }\n\n    /// @inheritdoc IPausable\n    function setPauser(address pauser, bytes32 pauseType, bool status)\n        external\n        override(IPausable, Pausable)\n        onlyOwner\n    {\n        _setPauser(pauser, pauseType, status);\n    }\n\n    /// @inheritdoc IMarketBase\n    function addSupply(uint256 assets, uint256 shares, address onBehalf)\n        external\n        whenNotPaused\n        whenNotFrozen\n        returns (uint256, uint256)\n    {\n        return _addSupply(assets, shares, onBehalf);\n    }\n\n    /// @dev See `IMarketBase.addSupply`\n    /// @dev This function is virtual to allow for custom logic.\n    function _addSupply(uint256 assets, uint256 shares, address onBehalf) internal virtual returns (uint256, uint256) {\n        if (!_onlyOneZero(assets, shares) || onBehalf == address(0)) {\n            revert AltoBaseMarketInvalidInput();\n        }\n\n        _accrueInterest();\n\n        if (assets == 0) {\n            assets = shares.convertToAssetsUp(totalSupply.assets, totalSupply.shares);\n        } else {\n            shares = assets.convertToSharesDown(totalSupply.assets, totalSupply.shares);\n        }\n\n        totalSupply.assets += assets.toUint128();\n        totalSupply.shares += shares.toUint128();\n\n        position[onBehalf].supplyShares += shares.toUint128();\n\n        _sendBorrowToken(msg.sender, address(this), assets);\n\n        emit AddSupply(msg.sender, onBehalf, assets, shares);\n\n        return (assets, shares);\n    }\n\n    /// @inheritdoc IMarketBase\n    function removeSupply(uint256 assets, uint256 shares, address onBehalf, address receiver)\n        external\n        whenNotPaused\n        returns (uint256, uint256)\n    {\n        return _removeSupply(assets, shares, onBehalf, receiver);\n    }\n\n    /// @dev See `IMarketBase.removeSupply`\n    /// @dev This function is virtual to allow for custom logic.\n    function _removeSupply(uint256 assets, uint256 shares, address onBehalf, address receiver)\n        internal\n        virtual\n        returns (uint256, uint256)\n    {\n        if (!_onlyOneZero(assets, shares) || receiver == address(0)) {\n            revert AltoBaseMarketInvalidInput();\n        }\n        if (!_isSenderAuthorized(onBehalf)) {\n            revert AltoBaseMarketUnauthorized();\n        }\n\n        _accrueInterest();\n\n        if (assets == 0) {\n            assets = shares.convertToAssetsDown(totalSupply.assets, totalSupply.shares);\n        } else {\n            shares = assets.convertToSharesUp(totalSupply.assets, totalSupply.shares);\n        }\n\n        totalSupply.assets -= assets.toUint128();\n        totalSupply.shares -= shares.toUint128();\n\n        position[onBehalf].supplyShares -= shares.toUint128();\n\n        // Invariant to prevent donation of borrow assets and removing supply\n        if (totalBorrowed.assets > totalSupply.assets) {\n            revert AltoBaseMarketInsufficientMarketLiquidity();\n        }\n\n        _sendBorrowToken(address(this), receiver, assets);\n\n        emit RemoveSupply(msg.sender, onBehalf, receiver, assets, shares);\n\n        return (assets, shares);\n    }\n\n    /// @inheritdoc IMarketBase\n    function addCollateral(uint256 assets, address onBehalf) external whenNotPaused whenNotFrozen returns (uint256) {\n        return _addCollateral(assets, onBehalf);\n    }\n\n    /// @dev See `IMarketBase.addCollateral`\n    /// @dev This function is virtual to allow for custom logic.\n    function _addCollateral(uint256 assets, address onBehalf) internal virtual returns (uint256) {\n        if (assets == 0 || onBehalf == address(0)) {\n            revert AltoBaseMarketInvalidInput();\n        }\n\n        position[onBehalf].collateralAssets += assets.toUint128();\n\n        _receiveCollateral(assets);\n\n        emit AddCollateral(msg.sender, onBehalf, assets);\n\n        return (assets);\n    }\n\n    /// @dev Receives collateral from the caller.\n    /// @dev This function is virtual to allow for custom collateral custody logic.\n    function _receiveCollateral(uint256 assets) internal virtual {\n        IERC20(collateralToken).safeTransferFrom(msg.sender, address(this), assets);\n    }\n\n    /// @inheritdoc IMarketBase\n    function removeCollateral(uint256 assets, address onBehalf, address receiver, bytes calldata swapParams)\n        external\n        whenNotPaused\n        nonReentrant\n        returns (uint256)\n    {\n        return _removeCollateral(assets, onBehalf, receiver, swapParams);\n    }\n\n    /// @dev See `IMarketBase.removeCollateral`\n    /// @dev This function is virtual to allow for custom logic.\n    function _removeCollateral(uint256 assets, address onBehalf, address receiver, bytes calldata swapParams)\n        internal\n        virtual\n        returns (uint256)\n    {\n        if (assets == 0 || onBehalf == address(0)) {\n            revert AltoBaseMarketInvalidInput();\n        }\n\n        if (!_isSenderAuthorized(onBehalf)) {\n            revert AltoBaseMarketUnauthorized();\n        }\n\n        _accrueInterest();\n\n        position[onBehalf].collateralAssets -= assets.toUint128();\n\n        _sendCollateral(receiver, assets);\n\n        if (authorizedCallbacks[receiver] && swapParams.length > 0) {\n            IRemoveCollateralCallback(receiver).onRemoveCollateralCallback(assets, onBehalf, swapParams);\n        } else if (swapParams.length > 0) {\n            revert AltoBaseMarketUnauthorized();\n        }\n\n        if (!_isSolvent(onBehalf)) {\n            revert AltoBaseMarketInsufficientUserCollateral();\n        }\n\n        emit RemoveCollateral(msg.sender, onBehalf, receiver, assets);\n\n        return (assets);\n    }\n\n    /// @dev Sends collateral to the receiver.\n    /// @dev This function is virtual to allow for custom collateral custody logic.\n    function _sendCollateral(address receiver, uint256 assets) internal virtual {\n        IERC20(collateralToken).safeTransfer(receiver, assets);\n    }\n\n    /// @inheritdoc IMarketBase\n    function borrow(uint256 assets, uint256 shares, address onBehalf, address receiver, bytes calldata swapParams)\n        external\n        whenNotPaused\n        whenNotFrozen\n        nonReentrant\n        returns (uint256, uint256, uint256)\n    {\n        return _borrow(assets, shares, onBehalf, receiver, swapParams);\n    }\n\n    /// @dev See `IMarketBase.borrow`\n    /// @dev This function is virtual to allow for custom logic.\n    function _borrow(uint256 assets, uint256 shares, address onBehalf, address receiver, bytes calldata swapParams)\n        internal\n        virtual\n        returns (uint256, uint256, uint256)\n    {\n        if (!_onlyOneZero(assets, shares) || receiver == address(0)) {\n            revert AltoBaseMarketInvalidInput();\n        }\n        if (!_isSenderAuthorized(onBehalf)) {\n            revert AltoBaseMarketUnauthorized();\n        }\n\n        _accrueInterest();\n\n        uint256 openingFeeAssets;\n\n        if (assets == 0) {\n            // calculate opening fee from shares\n            uint256 openingFeeShares = shares.multiplyWithPrecisionUp(borrowOpeningFee());\n            openingFeeAssets = openingFeeShares.convertToAssetsUp(totalBorrowed.assets, totalBorrowed.shares);\n            shares += openingFeeShares;\n\n            assets = shares.convertToAssetsDown(totalBorrowed.assets, totalBorrowed.shares);\n        } else {\n            // calculate opening fee from assets\n            openingFeeAssets = assets.multiplyWithPrecisionUp(borrowOpeningFee());\n            assets += openingFeeAssets;\n\n            shares = assets.convertToSharesUp(totalBorrowed.assets, totalBorrowed.shares);\n        }\n\n        totalBorrowed.assets += assets.toUint128();\n        totalBorrowed.shares += shares.toUint128();\n\n        if (totalBorrowed.assets > totalSupply.assets) {\n            revert AltoBaseMarketInsufficientMarketLiquidity();\n        }\n\n        position[onBehalf].borrowShares += shares.toUint128();\n\n        // send assets to the receiver minus the opening fee as now `assets` includes the opening fee\n        uint256 assetsToSend = assets - openingFeeAssets;\n        _sendBorrowToken(address(this), receiver, assetsToSend);\n\n        uint256 feeSupplyShares;\n        if (openingFeeAssets > 0) {\n            feeSupplyShares = _applyBorrowOpeningFee(openingFeeAssets);\n        }\n\n        if (authorizedCallbacks[receiver]) {\n            if (swapParams.length == 0) {\n                revert AltoBaseMarketInvalidInput();\n            }\n            IBorrowCallback(receiver).onBorrowCallback(assetsToSend, onBehalf, swapParams);\n        } else if (swapParams.length > 0) {\n            revert AltoBaseMarketUnauthorized();\n        }\n\n        if (!_isSolvent(onBehalf)) {\n            revert AltoBaseMarketBorrowingTooMuch();\n        }\n\n        emit Borrow(msg.sender, onBehalf, receiver, assetsToSend, shares, openingFeeAssets, feeSupplyShares);\n\n        return (assets, shares, openingFeeAssets);\n    }\n\n    /// @dev Adds opening fee to the fee recipient's supply position and to the market.\n    /// @param openingFeeAssets The amount of opening fee to add.\n    /// @return feeSupplyShares The amount of shares added to the fee recipient's supply position.\n    /// @dev This function is virtual to allow for custom logic\n    function _applyBorrowOpeningFee(uint256 openingFeeAssets) internal virtual returns (uint256) {\n        // add opening fee to the fee recipient's supply position\n        uint256 feeSupplyShares = openingFeeAssets.convertToSharesUp(totalSupply.assets, totalSupply.shares);\n        totalSupply.shares += feeSupplyShares.toUint128();\n        totalSupply.assets += openingFeeAssets.toUint128();\n        position[feeRecipient].supplyShares += feeSupplyShares.toUint128();\n\n        return feeSupplyShares;\n    }\n\n    /// @inheritdoc IMarketBase\n    function repay(uint256 assets, uint256 shares, address onBehalf) external whenNotPaused returns (uint256, uint256) {\n        return _repay(assets, shares, onBehalf);\n    }\n\n    /// @dev See `IMarketBase.repay`\n    /// @dev This function is virtual to allow for custom logic.\n    function _repay(uint256 assets, uint256 shares, address onBehalf) internal virtual returns (uint256, uint256) {\n        if (!_onlyOneZero(assets, shares) || onBehalf == address(0)) {\n            revert AltoBaseMarketInvalidInput();\n        }\n\n        _accrueInterest();\n\n        if (assets == 0) {\n            assets = shares.convertToAssetsUp(totalBorrowed.assets, totalBorrowed.shares);\n        } else {\n            shares = assets.convertToSharesDown(totalBorrowed.assets, totalBorrowed.shares);\n        }\n\n        totalBorrowed.assets -= assets.toUint128();\n        totalBorrowed.shares -= shares.toUint128();\n\n        position[onBehalf].borrowShares -= shares.toUint128();\n\n        _sendBorrowToken(msg.sender, address(this), assets);\n\n        emit Repay(msg.sender, onBehalf, assets, shares);\n\n        return (assets, shares);\n    }\n\n    /// @inheritdoc IMarketBase\n    function accrueInterest() external whenNotPaused {\n        _accrueInterest();\n    }\n\n    /// @dev Accrues interest for the market.\n    /// @dev If `irm` is set to zero address, this function does nothing.\n    /// @dev This function is virtual to allow for custom logic.\n    function _accrueInterest() internal virtual {\n        if (irm == address(0)) {\n            return;\n        }\n\n        (uint256 interest, uint256 borrowRate) = IIrm(irm).updateInterestRate(totalSupply.assets, totalBorrowed.assets);\n\n        if (interest == 0) {\n            return;\n        }\n\n        totalSupply.assets += interest.toUint128();\n        totalBorrowed.assets += interest.toUint128();\n\n        emit AccrueInterest(borrowRate, interest, totalBorrowed.assets, totalSupply.assets);\n    }\n\n    /// @dev Returns true if the user's position is solvent.\n    /// @param _user The address of the user whose position is being checked\n    function _isSolvent(address _user) internal view virtual returns (bool) {\n        uint256 collateralPrice = ILendingOracle(oracle).getPrice();\n        uint256 collateralValue = uint256(position[_user].collateralAssets)\n            .divideWithRounding(collateralPrice, LENDING_ORACLE_PRICE_PRECISION, false);\n        uint256 maxBorrowValue = collateralValue.multiplyWithPrecision(maxLtv);\n        uint256 borrowValue =\n            uint256(position[_user].borrowShares).convertToAssetsUp(totalBorrowed.assets, totalBorrowed.shares);\n\n        return maxBorrowValue >= borrowValue;\n    }\n\n    /// @inheritdoc IMarketBase\n    function liquidate(address borrower, bytes calldata callbackData, bytes calldata liquidationData)\n        external\n        whenNotPaused\n        nonReentrant\n        returns (uint256, uint256, uint256)\n    {\n        return _liquidate(borrower, callbackData, liquidationData);\n    }\n\n    /// @dev Liquidates a position.\n    /// @param borrower The address of the borrower being liquidated.\n    /// @param callbackData Additional data for the liquidator contract.\n    /// @param liquidationData Additional data for the liquidation engine.\n    /// @return The amount of collateral received.\n    /// @return The amount of assets repaid.\n    /// @return The amount of protocol fee paid.\n    function _liquidate(address borrower, bytes calldata callbackData, bytes memory liquidationData)\n        internal\n        virtual\n        returns (uint256, uint256, uint256)\n    {\n        _accrueInterest();\n        address originalLiquidator = msg.sender;\n\n        if (authorizedLiquidationPeriphery[msg.sender]) {\n            (originalLiquidator, liquidationData) = abi.decode(liquidationData, (address, bytes));\n\n            if (originalLiquidator == address(0)) {\n                revert AltoBaseMarketInvalidInput();\n            }\n        }\n\n        LiquidationEngineResult memory result = IAltoLiquidationEngine(liquidationEngine)\n            .prepareLiquidation(\n                LiquidationEngineInput({\n                borrower: borrower,\n                liquidator: originalLiquidator,\n                totalSupply: totalSupply,\n                totalBorrowed: totalBorrowed,\n                position: position[borrower],\n                maxLtv: maxLtv,\n                collateralPrice: ILendingOracle(oracle).getPrice(),\n                liquidationData: liquidationData\n            })\n            );\n        // apply liquidation\n        position[borrower].collateralAssets -= result.seizedCollateralAssets.toUint128();\n        position[borrower].borrowShares -= result.repaidBorrowShares.toUint128();\n\n        totalBorrowed.shares -= result.repaidBorrowShares.toUint128();\n        totalBorrowed.assets = (totalBorrowed.assets > result.repaidBorrowAmount\n                ? totalBorrowed.assets - result.repaidBorrowAmount\n                : 0)\n        .toUint128();\n\n        Balance memory badDebt;\n        if (position[borrower].collateralAssets == 0) {\n            badDebt.shares = position[borrower].borrowShares;\n            badDebt.assets = uint128(\n                Math.min(\n                    totalBorrowed.assets,\n                    uint256(badDebt.shares).convertToAssetsUp(totalBorrowed.assets, totalBorrowed.shares)\n                )\n            );\n\n            _applyLiquidationBadDebt(badDebt, borrower);\n        }\n\n        // apply protocol fee\n        position[feeRecipient].collateralAssets += result.protocolSeizedCollateralFee.toUint128();\n\n        uint256 collateralAmountToSend = result.seizedCollateralAssets - result.protocolSeizedCollateralFee;\n\n        // transfer collateral and borrow tokens with applied protocol fee\n        IERC20(collateralToken).safeTransfer(msg.sender, collateralAmountToSend);\n\n        if (callbackData.length > 0) {\n            ILiquidateCallback(msg.sender)\n                .onLiquidateCallback(result.repaidBorrowAmount, collateralAmountToSend, callbackData);\n        }\n\n        _sendBorrowToken(msg.sender, address(this), result.repaidBorrowAmount);\n\n        emit Liquidation(\n            borrower,\n            originalLiquidator,\n            result.seizedCollateralAssets,\n            result.protocolSeizedCollateralFee,\n            result.repaidBorrowAmount,\n            result.repaidBorrowShares,\n            badDebt.assets,\n            badDebt.shares\n        );\n\n        return (result.seizedCollateralAssets, result.repaidBorrowAmount, result.protocolSeizedCollateralFee);\n    }\n\n    /// @inheritdoc IMarketBase\n    function governanceLiquidate(address borrower, bool skipAccrueInterest)\n        external\n        virtual\n        onlyOwner\n        nonReentrant\n        returns (uint256, uint256)\n    {\n        if (!paused[PAUSE_TYPE] && !skipAccrueInterest) {\n            _accrueInterest();\n        }\n\n        Position memory _position = position[borrower];\n\n        uint256 collateralAmount = _position.collateralAssets;\n\n        uint256 badDebtAmount = Math.min(\n            uint256(_position.borrowShares).convertToAssetsUp(totalBorrowed.assets, totalBorrowed.shares),\n            totalBorrowed.assets\n        );\n        uint128 badDebtShares = position[borrower].borrowShares;\n\n        _applyLiquidationBadDebt(Balance({shares: badDebtShares, assets: badDebtAmount.toUint128()}), borrower);\n\n        position[borrower].collateralAssets = 0;\n\n        if (collateralAmount > 0) {\n            IERC20(collateralToken).safeTransfer(msg.sender, collateralAmount);\n        }\n\n        emit GovernanceLiquidation(borrower, msg.sender, collateralAmount, badDebtAmount, badDebtShares);\n\n        return (collateralAmount, badDebtAmount);\n    }\n\n    /// @dev Applies the bad debt to the market.\n    /// @param badDebt The bad debt to apply.\n    /// @param borrower The address of the borrower whose position is being liquidated.\n    /// @dev This function is virtual to allow for custom logic.\n    function _applyLiquidationBadDebt(Balance memory badDebt, address borrower) internal virtual {\n        totalBorrowed.shares -= badDebt.shares;\n        totalBorrowed.assets -= badDebt.assets;\n\n        totalSupply.assets -= badDebt.assets;\n\n        position[borrower].borrowShares = 0;\n    }\n\n    /// @dev Sends the borrow token from one address to another.\n    /// @param from The address of the sender.\n    /// @param to The address of the receiver.\n    /// @param amount The amount of borrow token to send.\n    /// @dev This function is virtual to allow for custom logic.\n    function _sendBorrowToken(address from, address to, uint256 amount) internal virtual {\n        if (from == address(this)) {\n            IERC20(borrowToken).safeTransfer(to, amount);\n        } else {\n            IERC20(borrowToken).safeTransferFrom(from, to, amount);\n        }\n    }\n\n    /// @dev Checks if one of the inputs is zero and the other is not.\n    function _onlyOneZero(uint256 x, uint256 y) internal pure returns (bool) {\n        return (x == 0 && y != 0) || (x != 0 && y == 0);\n    }\n\n    /// @dev Modifier to check if the market is not paused.\n    modifier whenNotPaused() {\n        if (paused[PAUSE_TYPE]) {\n            revert IPausable.IsPaused(PAUSE_TYPE);\n        }\n        _;\n    }\n\n    /// @dev Modifier to check if the market is not frozen.\n    modifier whenNotFrozen() {\n        if (paused[FROZEN_TYPE]) {\n            revert IPausable.IsPaused(FROZEN_TYPE);\n        }\n        _;\n    }\n\n    function _onPause(bytes32 pauseType, bool _paused) internal override {\n        if (pauseType == PAUSE_TYPE) {\n            if (_paused) {\n                _accrueInterest();\n            } else {\n                IIrm(irm).onMarketPause(_paused);\n            }\n        }\n    }\n\n    function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}\n}\n"},{"file_path":"contracts/oracles/interfaces/IOracle.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.5.0;\n\n/// @title IOracle\n/// @notice This represents basic oracle interface\ninterface IOracle {\n    /// @notice Returns the price of the asset\n    /// @return The price of the asset\n    function getPrice() external view returns (uint256);\n}\n\n/// @dev The precision of the price of the asset in the Alto Lending oracles\nuint256 constant LENDING_ORACLE_PRICE_PRECISION = 1e36;\n\n/// @title IOracle\n/// @author GPM\n/// @custom:contact security@altofoundation.org\n/// @notice This represents the oracle that's used in the Alto Lending\n/// @dev This oracle is supposed to return the price of the asset in with LENDING_ORACLE_PRICE_PRECISION precision\ninterface ILendingOracle is IOracle {\n    /// @notice Returns the price of the asset\n    /// @return The price of the asset in LENDING_ORACLE_PRICE_PRECISION precision\n    /// @dev It will return the price of one unit of the collateral token,\n    /// quoted in one unit of the borrow token, scaled by 1e36. It corresponds to the price of\n    /// 10^(collateral token decimals) units of the collateral token quoted in\n    /// 10^(borrow token decimals) units of the borrow token, with a precision of\n    /// (36 + borrow token decimals - collateral token decimals) decimal places.\n    function getPrice() external view returns (uint256);\n}\n\n/// @dev The precision of the price of the asset in USD oracles\nuint256 constant USD_ORACLE_PRICE_PRECISION = 1e8;\n\n/// @title IUsdOracle\n/// @author GPM\n/// @custom:contact security@altofoundation.org\n/// @notice This represents the oracle that returns the price of the asset in USD\n/// @dev This is supposed to return the price of the asset in with USD_ORACLE_PRICE_PRECISION precision\ninterface IUsdOracle {\n    /// @notice Returns the price of the asset in USD\n    /// @return The price of the asset in USD in USD_ORACLE_PRICE_PRECISION precision\n    /// @dev It will return the price of one unit of the asset, quoted in USD, scaled by USD_ORACLE_PRICE_PRECISION.\n    function getPrice() external view returns (uint256);\n}\n\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,\n * consider using {ReentrancyGuardTransient} instead.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant NOT_ENTERED = 1;\n    uint256 private constant ENTERED = 2;\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard\n    struct ReentrancyGuardStorage {\n        uint256 _status;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ReentrancyGuard\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;\n\n    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {\n        assembly {\n            $.slot := ReentrancyGuardStorageLocation\n        }\n    }\n\n    /**\n     * @dev Unauthorized reentrant call.\n     */\n    error ReentrancyGuardReentrantCall();\n\n    function __ReentrancyGuard_init() internal onlyInitializing {\n        __ReentrancyGuard_init_unchained();\n    }\n\n    function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        $._status = NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        // On the first call to nonReentrant, _status will be NOT_ENTERED\n        if ($._status == ENTERED) {\n            revert ReentrancyGuardReentrantCall();\n        }\n\n        // Any calls to nonReentrant after this point will fail\n        $._status = ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        $._status = NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        return $._status == ENTERED;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n    enum RecoverError {\n        NoError,\n        InvalidSignature,\n        InvalidSignatureLength,\n        InvalidSignatureS\n    }\n\n    /**\n     * @dev The signature derives the `address(0)`.\n     */\n    error ECDSAInvalidSignature();\n\n    /**\n     * @dev The signature has an invalid length.\n     */\n    error ECDSAInvalidSignatureLength(uint256 length);\n\n    /**\n     * @dev The signature has an S value that is in the upper half order.\n     */\n    error ECDSAInvalidSignatureS(bytes32 s);\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not\n     * return address(0) without also returning an error description. Errors are documented using an enum (error type)\n     * and a bytes32 providing additional information about the error.\n     *\n     * If no error is returned, then the address can be used for verification purposes.\n     *\n     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.\n     *\n     * Documentation for signature generation:\n     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n     */\n    function tryRecover(\n        bytes32 hash,\n        bytes memory signature\n    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n        if (signature.length == 65) {\n            bytes32 r;\n            bytes32 s;\n            uint8 v;\n            // ecrecover takes the signature parameters, and the only way to get them\n            // currently is to use assembly.\n            assembly (\"memory-safe\") {\n                r := mload(add(signature, 0x20))\n                s := mload(add(signature, 0x40))\n                v := byte(0, mload(add(signature, 0x60)))\n            }\n            return tryRecover(hash, v, r, s);\n        } else {\n            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));\n        }\n    }\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with\n     * `signature`. This address can then be used for verification purposes.\n     *\n     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.\n     */\n    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);\n        _throwError(error, errorArg);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n     *\n     * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]\n     */\n    function tryRecover(\n        bytes32 hash,\n        bytes32 r,\n        bytes32 vs\n    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n        unchecked {\n            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n            // We do not check for an overflow here since the shift operation results in 0 or 1.\n            uint8 v = uint8((uint256(vs) >> 255) + 27);\n            return tryRecover(hash, v, r, s);\n        }\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n     */\n    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {\n        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);\n        _throwError(error, errorArg);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     */\n    function tryRecover(\n        bytes32 hash,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n        // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n        //\n        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n        // these malleable signatures as well.\n        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n            return (address(0), RecoverError.InvalidSignatureS, s);\n        }\n\n        // If the signature is valid (and not malleable), return the signer address\n        address signer = ecrecover(hash, v, r, s);\n        if (signer == address(0)) {\n            return (address(0), RecoverError.InvalidSignature, bytes32(0));\n        }\n\n        return (signer, RecoverError.NoError, bytes32(0));\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     */\n    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);\n        _throwError(error, errorArg);\n        return recovered;\n    }\n\n    /**\n     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.\n     */\n    function _throwError(RecoverError error, bytes32 errorArg) private pure {\n        if (error == RecoverError.NoError) {\n            return; // no error: do nothing\n        } else if (error == RecoverError.InvalidSignature) {\n            revert ECDSAInvalidSignature();\n        } else if (error == RecoverError.InvalidSignatureLength) {\n            revert ECDSAInvalidSignatureLength(uint256(errorArg));\n        } else if (error == RecoverError.InvalidSignatureS) {\n            revert ECDSAInvalidSignatureS(errorArg);\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/utils/cryptography/EIP712Upgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/cryptography/EIP712.sol)\n\npragma solidity ^0.8.20;\n\nimport {MessageHashUtils} from \"@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol\";\nimport {IERC5267} from \"@openzeppelin/contracts/interfaces/IERC5267.sol\";\nimport {Initializable} from \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose\n * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract\n * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to\n * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * NOTE: The upgradeable version of this contract does not use an immutable cache and recomputes the domain separator\n * each time {_domainSeparatorV4} is called. That is cheaper than accessing a cached version in cold storage.\n */\nabstract contract EIP712Upgradeable is Initializable, IERC5267 {\n    bytes32 private constant TYPE_HASH =\n        keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.EIP712\n    struct EIP712Storage {\n        /// @custom:oz-renamed-from _HASHED_NAME\n        bytes32 _hashedName;\n        /// @custom:oz-renamed-from _HASHED_VERSION\n        bytes32 _hashedVersion;\n\n        string _name;\n        string _version;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.EIP712\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant EIP712StorageLocation = 0xa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100;\n\n    function _getEIP712Storage() private pure returns (EIP712Storage storage $) {\n        assembly {\n            $.slot := EIP712StorageLocation\n        }\n    }\n\n    /**\n     * @dev Initializes the domain separator and parameter caches.\n     *\n     * The meaning of `name` and `version` is specified in\n     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:\n     *\n     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n     * - `version`: the current major version of the signing domain.\n     *\n     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n     * contract upgrade].\n     */\n    function __EIP712_init(string memory name, string memory version) internal onlyInitializing {\n        __EIP712_init_unchained(name, version);\n    }\n\n    function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {\n        EIP712Storage storage $ = _getEIP712Storage();\n        $._name = name;\n        $._version = version;\n\n        // Reset prior values in storage if upgrading\n        $._hashedName = 0;\n        $._hashedVersion = 0;\n    }\n\n    /**\n     * @dev Returns the domain separator for the current chain.\n     */\n    function _domainSeparatorV4() internal view returns (bytes32) {\n        return _buildDomainSeparator();\n    }\n\n    function _buildDomainSeparator() private view returns (bytes32) {\n        return keccak256(abi.encode(TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));\n    }\n\n    /**\n     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n     * function returns the hash of the fully encoded EIP712 message for this domain.\n     *\n     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n     *\n     * ```solidity\n     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n     *     keccak256(\"Mail(address to,string contents)\"),\n     *     mailTo,\n     *     keccak256(bytes(mailContents))\n     * )));\n     * address signer = ECDSA.recover(digest, signature);\n     * ```\n     */\n    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n        return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);\n    }\n\n    /// @inheritdoc IERC5267\n    function eip712Domain()\n        public\n        view\n        virtual\n        returns (\n            bytes1 fields,\n            string memory name,\n            string memory version,\n            uint256 chainId,\n            address verifyingContract,\n            bytes32 salt,\n            uint256[] memory extensions\n        )\n    {\n        EIP712Storage storage $ = _getEIP712Storage();\n        // If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized\n        // and the EIP712 domain is not reliable, as it will be missing name and version.\n        require($._hashedName == 0 && $._hashedVersion == 0, \"EIP712: Uninitialized\");\n\n        return (\n            hex\"0f\", // 01111\n            _EIP712Name(),\n            _EIP712Version(),\n            block.chainid,\n            address(this),\n            bytes32(0),\n            new uint256[](0)\n        );\n    }\n\n    /**\n     * @dev The name parameter for the EIP712 domain.\n     *\n     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n     * are a concern.\n     */\n    function _EIP712Name() internal view virtual returns (string memory) {\n        EIP712Storage storage $ = _getEIP712Storage();\n        return $._name;\n    }\n\n    /**\n     * @dev The version parameter for the EIP712 domain.\n     *\n     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n     * are a concern.\n     */\n    function _EIP712Version() internal view virtual returns (string memory) {\n        EIP712Storage storage $ = _getEIP712Storage();\n        return $._version;\n    }\n\n    /**\n     * @dev The hash of the name parameter for the EIP712 domain.\n     *\n     * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.\n     */\n    function _EIP712NameHash() internal view returns (bytes32) {\n        EIP712Storage storage $ = _getEIP712Storage();\n        string memory name = _EIP712Name();\n        if (bytes(name).length > 0) {\n            return keccak256(bytes(name));\n        } else {\n            // If the name is empty, the contract may have been upgraded without initializing the new storage.\n            // We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.\n            bytes32 hashedName = $._hashedName;\n            if (hashedName != 0) {\n                return hashedName;\n            } else {\n                return keccak256(\"\");\n            }\n        }\n    }\n\n    /**\n     * @dev The hash of the version parameter for the EIP712 domain.\n     *\n     * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.\n     */\n    function _EIP712VersionHash() internal view returns (bytes32) {\n        EIP712Storage storage $ = _getEIP712Storage();\n        string memory version = _EIP712Version();\n        if (bytes(version).length > 0) {\n            return keccak256(bytes(version));\n        } else {\n            // If the version is empty, the contract may have been upgraded without initializing the new storage.\n            // We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.\n            bytes32 hashedVersion = $._hashedVersion;\n            if (hashedVersion != 0) {\n                return hashedVersion;\n            } else {\n                return keccak256(\"\");\n            }\n        }\n    }\n}\n"},{"file_path":"contracts/lending/interfaces/IIrm.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\nenum IRMType {\n    FIXED_RATE, // FixedRateIrm\n    ADAPTIVE_CURVE, // AdaptiveCurveIrm\n    PEG_RESPONSIVE_EXPONENTIAL // PegResponsiveExponentialIrm\n}\n\ninterface IIrm {\n    /// @notice Error thrown when the caller is not the market\n    error IrmUnauthorized();\n\n    /// @notice Error thrown when the market is already set\n    error IrmMarketAlreadySet();\n\n    /// @notice Error thrown when the market is not set\n    error IrmMarketNotSet();\n\n    /// @notice Error thrown when the parameters are invalid\n    error IrmInvalidParams();\n\n    /// @notice The type of the IRM\n    /// @dev This is used to identify the type of the IRM during indexing\n    function IRM_TYPE() external view returns (IRMType);\n\n    /// @notice Sets the market for the IRM\n    /// @param _market The market to set\n    /// @dev This function has to be called first time by the market to set up the IRM\n    function setMarket(address _market) external;\n\n    /// @notice Called when the market is paused\n    /// @param _paused The new paused state\n    /// @dev This function is function is used when market of this IRM is paused/unpaused.\n    /// Pausing market should also pause the accrual of interest.\n    function onMarketPause(bool _paused) external;\n\n    /// @notice Updates interest rate the the latest value\n    /// @param totalSupply Total amount of assets supplied to the markets\n    /// @param totalBorrowed Total amount of assets borrowed from the markets\n    /// @return new interest rate in second percent yield (SPY), new interest since last update\n    function updateInterestRate(uint256 totalSupply, uint256 totalBorrowed) external returns (uint256, uint256);\n\n    /// @notice Performs compuutation of the interest rate without mutating state\n    /// @param totalSupply Total amount of assets supplied to the markets\n    /// @param totalBorrowed Total amount of assets borrowed from the markets\n    /// @return new interest rate in second percent yield (SPY), new interest since last update\n    function updateInterestRateView(uint256 totalSupply, uint256 totalBorrowed) external view returns (uint256, uint256);\n}\n\n"},{"file_path":"contracts/lending/interfaces/IMarket.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IAuth} from \"@alto/utils/interfaces/IAuth.sol\";\nimport {IPausable} from \"@alto/utils/interfaces/IPausable.sol\";\n\n/// @notice The type of the market\nenum MarketType {\n    BORROW, // AltoBorrowMarket\n    MINT, // AltoMintMarket\n    DAO_MINT, // AltoDaoMintMarket\n    CREDIT_MINT // AltoConvexCreditLineMarket\n}\n\n/// @notice Struct that represents the balance of a token\nstruct Balance {\n    uint128 assets;\n    uint128 shares;\n}\n\n/// @notice Struct that represents the position of a user\nstruct Position {\n    uint128 supplyShares;\n    uint128 borrowShares;\n    uint128 collateralAssets;\n}\n\n/// @notice Struct that represents the parameters for initializing a base market\nstruct BaseMarketInitParams {\n    /// @notice The address of the borrow token.\n    address borrowToken;\n    /// @notice The address of the collateral token.\n    address collateralToken;\n    /// @notice The address of the IRM contract.\n    address irm;\n    /// @notice The address of the owner.\n    address owner;\n    /// @notice The address initially authorized to pause and freeze the market.\n    address emergencyAdmin;\n    /// @notice The address of the oracle contract.\n    address oracle;\n    /// @notice The max LTV for the market.\n    uint256 maxLtv;\n    /// @notice The address of the fee recipient.\n    address feeRecipient;\n    /// @notice The address of the liquidation engine.\n    address liquidationEngine;\n}\n\n/// @notice Struct that represents the parameters for initializing a borrow market\nstruct BorrowMarketInitParams {\n    /// @notice The parameters for initializing a base market.\n    BaseMarketInitParams baseMarketInitParams;\n    /// @notice The initial borrow opening fee.\n    uint256 initialBorrowOpeningFee;\n    /// @notice The maximum amount of assets that can be supplied to the market.\n    uint128 supplyCapAssets;\n    /// @notice The initial interest fee.\n    uint256 initialInterestFee;\n}\n\n/// @notice Struct that represents the parameters for initializing a mint market\nstruct MintMarketInitParams {\n    /// @notice The parameters for initializing a base market.\n    BaseMarketInitParams baseMarketInitParams;\n    /// @notice The debt ceiling of mint market.\n    uint256 debtCeiling;\n    /// @notice The initial borrow opening fee.\n    uint256 initialBorrowOpeningFee;\n}\n\ninterface IMarketErrors {\n    /// @notice Error thrown when the input is invalid\n    error AltoBaseMarketInvalidInput();\n\n    /// @notice Error thrown when the user is trying to remove more collateral then allowed\n    error AltoBaseMarketInsufficientUserCollateral();\n\n    /// @notice Error thrown when the user is trying to borrow more than they are allowed\n    error AltoBaseMarketBorrowingTooMuch();\n\n    /// @notice Error thrown when the market has insufficient liquidity for the borrow\n    error AltoBaseMarketInsufficientMarketLiquidity();\n\n    /// @notice Error thrown when executor is not allowed to perform the action on behalf of another user\n    error AltoBaseMarketUnauthorized();\n}\n\ninterface IMarketEvents {\n    /// @notice Emitted when the IRM contract is set\n    /// @param oldAddr The address of the old IRM contract\n    /// @param newAddr The address of the new IRM contract\n    event SetIrm(address indexed oldAddr, address indexed newAddr);\n\n    /// @notice Emitted when the oracle contract is set\n    /// @param oldAddr The address of the old oracle contract\n    /// @param newAddr The address of the new oracle contract\n    event SetOracle(address indexed oldAddr, address indexed newAddr);\n\n    /// @notice Emitted when the max LTV is set\n    /// @param oldMaxLtv The address of the old max LTV\n    /// @param newMaxLtv The address of the new max LTV\n    event SetMaxLtv(uint256 oldMaxLtv, uint256 newMaxLtv);\n\n    /// @notice Emitted when the liquidation engine is set\n    /// @param oldLiquidationEngine The address of the old liquidation engine\n    /// @param newLiquidationEngine The address of the new liquidation engine\n    event SetLiquidationEngine(address indexed oldLiquidationEngine, address indexed newLiquidationEngine);\n\n    /// @notice Emitted when the fee recipient is set\n    /// @param oldAddr The address of the old fee recipient\n    /// @param newAddr The address of the new fee recipient\n    event SetFeeRecipient(address indexed oldAddr, address indexed newAddr);\n\n    /// @notice Emitted when the authorized callback is set\n    /// @param callback The address of the authorized callback\n    /// @param isAuthorized If set to true, the callback contract will be allowed as an authorized callback.\n    /// If set to false, the callback contract will be disallowed as an authorized callback.\n    event SetAuthorizedCallback(address indexed callback, bool isAuthorized);\n\n    /// @notice Emitted when the authorized liquidation periphery is set\n    /// @param periphery The address of the authorized liquidation periphery\n    /// @param isAuthorized If set to true, the liquidation periphery will be allowed as an authorized liquidation periphery.\n    /// If set to false, the liquidation periphery will be disallowed as an authorized liquidation periphery.\n    event SetAuthorizedLiquidationPeriphery(address indexed periphery, bool isAuthorized);\n\n    /// @notice Emitted when a user supplies tokens to the lending market\n    /// @param caller The address of the caller who is supplying tokens\n    /// @param onBehalf The address of the user who is receiving the ownership of supplied tokens\n    /// @param assets The amount of assets supplied\n    /// @param shares The amount of shares minted\n    event AddSupply(address indexed caller, address indexed onBehalf, uint256 assets, uint256 shares);\n\n    /// @notice Emitted when a user withdraws tokens from the lending market\n    /// @param caller The address of the caller who is withdrawing tokens on behalf\n    /// @param onBehalf The address of the user who is the owner of withdrawn tokens\n    /// @param receiver The address of the user who is receiving the withdrawn tokens\n    /// @param assets The amount of assets withdrawn\n    /// @param shares The amount of shares burned\n    event RemoveSupply(\n        address indexed caller, address indexed onBehalf, address indexed receiver, uint256 assets, uint256 shares\n    );\n\n    /// @notice Emitted when a user borrows tokens from the lending market\n    /// @param caller The address of the caller who is borrowing tokens\n    /// @param onBehalf The address of the user who is the owner of borrowed tokens\n    /// @param receiver The address of the user who is receiving the borrowed tokens\n    /// @param assets The amount of assets borrowed\n    /// @param shares The amount of shares minted\n    /// @param feeAmount The amount of assets paid as opening fee\n    /// @param feeSupplyShares The amount of supply shares given to the fee recipient\n    event Borrow(\n        address indexed caller,\n        address indexed onBehalf,\n        address indexed receiver,\n        uint256 assets,\n        uint256 shares,\n        uint256 feeAmount,\n        uint256 feeSupplyShares\n    );\n\n    /// @notice Emitted when a user repays borrowed tokens\n    /// @param caller The address of the caller who is repaying tokens\n    /// @param onBehalf The address of the user who is the owner of the borrow position\n    /// @param assets The amount of assets repaid\n    /// @param shares The amount of shares burned\n    event Repay(address indexed caller, address indexed onBehalf, uint256 assets, uint256 shares);\n\n    /// @notice Emitted when a user deposits collateral\n    /// @param caller The address of the caller who is supplying collateral\n    /// @param onBehalf The address of the user who is the owner of supplied collateral\n    /// @param amount The amount of collateral supplied\n    event AddCollateral(address indexed caller, address indexed onBehalf, uint256 amount);\n\n    /// @notice Emitted when a user withdraws collateral\n    /// @param caller The address of the caller who is withdrawing collateral\n    /// @param onBehalf The address of the owner of collateral being withdrawn\n    /// @param receiver The address of the user who is receiving the withdrawn collateral\n    /// @param amount The amount of collateral withdrawn\n    event RemoveCollateral(address indexed caller, address indexed onBehalf, address indexed receiver, uint256 amount);\n\n    /// @notice Emitted when interest is accrued\n    /// @param borrowRate The average rate\n    /// @param interest The amount of interest accrued\n    /// @param totalBorrowAssets The total borrow assets\n    /// @param totalSupplyAssets The total supply assets\n    event AccrueInterest(uint256 borrowRate, uint256 interest, uint128 totalBorrowAssets, uint128 totalSupplyAssets);\n\n    // add liquidation event\n    /// @notice Emitted when a liquidation occurs\n    /// @param user The address of the user whose position was liquidated\n    /// @param liquidator The address of the liquidator\n    /// @param liquidatedCollateral The amount of collateral that was liquidated\n    /// @param protocolFee The amount of protocol fee credited to the fee recipient\n    /// @param repaidBorrow The amount of borrow tokens that were repaid\n    /// @param repaidBorrowShares The amount of borrow shares that were repaid\n    /// @param badDebtClearedAssets The amount of bad debt cleared\n    /// @param badDebtClearedShares The amount of bad debt shares cleared\n    event Liquidation(\n        address indexed user,\n        address liquidator,\n        uint256 liquidatedCollateral,\n        uint256 protocolFee,\n        uint256 repaidBorrow,\n        uint256 repaidBorrowShares,\n        uint256 badDebtClearedAssets,\n        uint256 badDebtClearedShares\n    );\n\n    /// @notice Emitted when a liquidation is performed through governance\n    /// @param user The address of the user whose position was liquidated\n    /// @param liquidator The address of the liquidator\n    /// @param liquidatedCollateral The amount of collateral that was seized\n    /// @param badDebtClearedAssets The amount of bad debt cleared\n    /// @param badDebtClearedShares The amount of bad debt shares cleared\n    event GovernanceLiquidation(\n        address indexed user,\n        address liquidator,\n        uint256 liquidatedCollateral,\n        uint256 badDebtClearedAssets,\n        uint256 badDebtClearedShares\n    );\n}\n\ninterface IMarketBase is IMarketErrors, IMarketEvents, IAuth, IPausable {\n    /// @notice The type of the market.\n    function MARKET_TYPE() external view returns (MarketType);\n\n    /// @notice The address of the borrow token.\n    function borrowToken() external view returns (address);\n\n    /// @notice The address of the collateral token.\n    function collateralToken() external view returns (address);\n\n    /// @notice Authorized contracts to be called by `borrow` and `removeCollateral`.\n    /// @dev This is used to allow for leverage and deleverage.\n    function authorizedCallbacks(address callback) external view returns (bool);\n\n    /// @notice Authorized contracts to be called during liquidation.\n    function authorizedLiquidationPeriphery(address periphery) external view returns (bool);\n\n    /// @notice Contract used for Interest Rate Model calculation when market needs to accrue interest.\n    function irm() external view returns (address);\n\n    /// @notice Oracle used to determine the collateral to borrow price.\n    function oracle() external view returns (address);\n\n    /// @notice Max position's LTV for the market.\n    /// @dev This is used to determine the max amount of borrow that can be taken for a given collateral.\n    function maxLtv() external view returns (uint256);\n\n    /// @notice function to calculate the borrow opening fee while borrowing\n    /// @dev The implementation used to calculate the borrow opening fee may differ for AltoBorrowMarket and AltoMintMarket\n    /// @dev This function will be implemented by the AltoBorrowMarket and AltoMintMarket\n    function borrowOpeningFee() external view returns (uint256);\n\n    /// @notice Address that receives the opening fee\n    /// @dev This is used to send the opening fee to the fee recipient\n    function feeRecipient() external view returns (address);\n\n    /// @notice Setter of the IRM contract for the market\n    /// @dev This setter accrues the interest using the previous IRM contract and sets up the new IRM contract.\n    /// This can be also used to disable the interest accrual by setting the IRM to zero address.\n    /// @param irm The address of the new IRM contract\n    /// @param skipAccrueInterest If set to true, the interest accrual will be skipped. This is useful when IRM\n    /// has improper setup and accruing interest would either revert or cause unwanted interest rate calculation.\n    function setIrm(address irm, bool skipAccrueInterest) external;\n\n    /// @notice setter of the oracle contract for the market\n    function setOracle(address oracle) external;\n\n    /// @notice setter of the max LTV for the market\n    /// @dev This will be used in rare scenarios - usually when increasing the max LTV to avoid\n    /// This should always be considered to be used in tandem with `setLiquidationConfiguration` as\n    /// liquidation calculation depends on the max LTV.\n    function setMaxLtv(uint256 maxLtv) external;\n\n    /// @notice Setter of the fee recipient for the market.\n    function setFeeRecipient(address feeRecipient) external;\n\n    /// @notice Function to set an authorized callback contract.\n    /// @param callback The address of the callback contract\n    /// @param isAuthorized If set to true, the callback contract will be allowed as an authorized callback.\n    /// If set to false, the callback contract will be disallowed as an authorized callback.\n    /// @dev This is used to allow for leverage and deleverage.\n    function setAuthorizedCallback(address callback, bool isAuthorized) external;\n\n    /// @notice Function to set an authorized liquidation periphery contract.\n    /// @param periphery The address of the liquidation periphery contract\n    /// @param isAuthorized If set to true, the liquidation periphery contract will be allowed as an authorized liquidation periphery.\n    /// If set to false, the liquidation periphery contract will be disallowed as an authorized liquidation periphery.\n    function setAuthorizedLiquidationPeriphery(address periphery, bool isAuthorized) external;\n\n    /// @notice Function to supply the borrow token to the market and make it available for borrowing.\n    /// @param assets The amount of assets supplied\n    /// @param shares The amount of shares to supply\n    /// @param onBehalf The address of the user who will become the owner of the supply position\n    /// @return assets The amount of assets supplied\n    /// @return shares The amount of shares supplied\n    /// @dev This increases the `totalSupply` of the market and the `supplyShares` of the `onBehalf` user.\n    /// @dev Either assets or shares can be provided but not both.\n    /// Providing `assets` will supply exact amount of assets to the market on behalf of `onBehalf`.\n    /// Providing `shares` will supply shares to the market on behalf of `onBehalf`. `assets` should be used in majority\n    /// of the cases. Specifying `shares` may end up depositing more or less assets than expected because of the\n    /// slippage. See AltoAdapter.sol for an example on how to handle slippage.\n    function addSupply(uint256 assets, uint256 shares, address onBehalf) external returns (uint256, uint256);\n\n    /// @notice Function to remove the borrow token from the market, make it unavailable for borrowing and remove the shares.\n    /// @param assets The amount of assets to remove\n    /// @param shares The amount of shares to remove\n    /// @param onBehalf The address of the user who is the owner of the supply position\n    /// @param receiver The address of the user who is receiving the withdrawn assets\n    /// @return assets The amount of assets withdrawn\n    /// @return shares The amount of shares withdrawn\n    /// @dev This decreases the `totalSupply` of the market and the `supplyShares` of the `onBehalf` user.\n    /// @dev Either assets or shares can be provided but not both.\n    /// Providing `assets` will remove exact amount of assets from the market on behalf of `onBehalf`.\n    /// Providing `shares` will remove shares from the market on behalf of `onBehalf`. `assets` should be used in majority\n    /// of the cases. Specifying `shares` may end up withdrawing more or less assets than expected because of the\n    /// slippage. But, in the case of when user wants to withdraw all their assets, `shares` should be used.\n    /// See AltoAdapter.sol for an example on how to handle slippage.\n    /// @dev This function will revert if there are currenly not enough assets in the market to remove. This can\n    /// happen if utilization is high or trying to withdraw more than globally available for borrow in the market.\n    function removeSupply(uint256 assets, uint256 shares, address onBehalf, address receiver)\n        external\n        returns (uint256, uint256);\n\n    /// @notice Function to deposit collateral token to the market as a collateral for borrowing.\n    /// @param assets The amount of collateral supplied\n    /// @param onBehalf The address of the user who will become the owner of the collateral position\n    /// @return assets The amount of collateral supplied\n    /// @dev This increases the `totalCollateral` of the market and the `collateralAssets` of the `onBehalf` user.\n    function addCollateral(uint256 assets, address onBehalf) external returns (uint256);\n\n    /// @notice Function to withdraw collateral token from the market and make it unavailable to be used as collateral\n    /// for borrowing.\n    /// @param assets The amount of collateral to remove\n    /// @param onBehalf The address of the user who is the owner of the collateral position\n    /// @param receiver The address of the user who is receiving the withdrawn collateral\n    /// @param swapParams ABI-encoded swap parameter (see `SwapParams` struct for details)\n    /// @return assets The amount of collateral withdrawn\n    /// @dev This decreases the `totalCollateral` of the market and the `collateralAssets` of the `onBehalf` user.\n    /// @dev This function will revert if this would leave `onBehalf`'s position insolvent after the withdrawal.\n    /// @dev When `swapParams` is provided `receiver` should be an authorized callback contract implementing `IRemoveCollateralCallback`.\n    /// This is used to allow for deleverage. Authorized callback contracts would be able to perform a swap and\n    /// prepare enough funds to repay `onBehalf`'s position using collateral.\n    function removeCollateral(uint256 assets, address onBehalf, address receiver, bytes calldata swapParams)\n        external\n        returns (uint256);\n\n    /// @notice Function to borrow the borrow token from the market.\n    /// @param assets The amount of assets to borrow\n    /// @param shares The amount of shares to borrow\n    /// @param onBehalf The address of the user who will become the owner of the borrow position\n    /// @param receiver The address of the user who is receiving the borrowed tokens\n    /// @param swapParams ABI-encoded swap parameter (see `SwapParams` struct for details)\n    /// @return assets The amount of assets borrowed\n    /// @return shares The amount of shares borrowed\n    /// @return openingFeeAssets The amount of opening borrow fee paid for this borrow\n    /// @dev This increases the `totalBorrowed` of the market and the `borrowShares` of the `onBehalf` user.\n    /// @dev Either assets or shares can be provided but not both.\n    /// Providing `assets` will borrow exact amount of assets from the market on behalf of `onBehalf`.\n    /// Providing `shares` will borrow shares from the market on behalf of `onBehalf`. `assets` should be used in majority\n    /// of the cases. Specifying `shares` may end up borrowing more or less assets than expected because of the\n    /// slippage. See AltoAdapter.sol for an example on how to handle slippage.\n    /// @dev When `swapParams` is provided `receiver` should be an authorized callback contract implementing `IBorrowCallback`.\n    /// This is used to allow for leverage. Authorized callback contracts would be able to perform a swap and\n    /// prepare enough collateral to borrow `assets` from the market.\n    /// @dev This function can only borrow up to to the max LTV of the market for given collateral by `onBehalf`.\n    function borrow(uint256 assets, uint256 shares, address onBehalf, address receiver, bytes calldata swapParams)\n        external\n        returns (uint256, uint256, uint256);\n\n    /// @notice Function to repay the borrow token to the market.\n    /// @param assets The amount of assets to repay\n    /// @param shares The amount of shares to repay\n    /// @param onBehalf The address of the user who is the owner of the borrow position\n    /// @return assets The amount of assets repaid\n    /// @return shares The amount of shares burned\n    /// @dev This decreases the `totalBorrowed` of the market and the `borrowShares` of the `onBehalf` user.\n    /// @dev Either assets or shares can be provided but not both.\n    /// Providing `assets` will repay exact amount of assets from the market on behalf of `onBehalf`.\n    /// Providing `shares` will repay shares from the market on behalf of `onBehalf`. `assets` should be used in majority\n    /// of the cases. Specifying `shares` may end up repaying more or less assets than expected because of the\n    /// slippage. But in the case of when user wants to repay all of their borrowed assets, `shares` should be used.\n    /// See AltoAdapter.sol for an example on how to handle slippage.\n    /// @dev This function will revert if `onBehalf`'s position is not solvent after the repayment.\n    function repay(uint256 assets, uint256 shares, address onBehalf) external returns (uint256, uint256);\n\n    /// @notice Function to accrue interest for the market.\n    /// @dev This function is called by the market when it needs to accrue interest.\n    /// It increases the `totalBorrowed` and `totalSupply` assets of the market.\n    /// @dev If `irm` is set to zero address, this function does nothing.\n    function accrueInterest() external;\n\n    /// @notice Function to liquidate an insolvent position.\n    /// @param borrower The address of the borrower being liquidated\n    /// @param callbackData Additional data for the liquidator contract\n    /// @param liquidationData Additional data for the liquidation engine\n    /// @dev If caller(msg.sender) is an authorized liquidation periphery, then liquidationData needs to be abi.encode(originalLiquidator, originalLiquidationData)\n    /// @dev originalLiquidationData will be passed to the liquidation engine\n    /// @dev originalLiquidator will be used for checks of priority liquidation\n    /// @dev if caller is not authorized liquidation periphery, then liquidationData will be passed directly to the liquidation engine\n    /// @return repaidBorrow The amount of borrow token repaid\n    /// @return repaidBorrowShares The amount of borrow shares repaid\n    /// @return protocolFee The amount of protocol credited to the fee recipient\n    /// @dev This function will calculate the liquidation amount and fee by itself. Liquidator\n    /// can't specify the amount of assets to repay.\n    /// @dev This function will revert if `borrower`'s position is not insolvent on not tagged.\n    /// @dev When `data` is provided `msg.sender` should be a contract implementing `ILiquidateCallback`.\n    /// This is used to perform a potential swap and to enough funds to repay the `borrower`'s position.\n    /// @dev Position has to be first tagged for liquidation using `tagLiquidablePosition` function.\n    /// This will start the timer in which the position can be liquidated in by the `priorityLiquidator` first.\n    /// Afterwards, if `priorityLiquidationGracePeriod` expired and position is not liquidated,\n    /// the liqudator that tagged the position can liquidate it. If `taggerLiquidationGracePeriod` expired\n    /// and position is not liquidated, anyone can liquidate it. If position becomes solvent and is not liquidated\n    /// after it was tagged, the tag will expire in `liquidationWindowTag` seconds after the tag was set.\n    /// @dev The underlying liquidation logic is well described in the docs.\n    function liquidate(address borrower, bytes calldata callbackData, bytes calldata liquidationData)\n        external\n        returns (uint256, uint256, uint256);\n\n    /// @notice Function to liquidate an insolvent position which is not possible to liquidate using normal liquidation\n    /// @dev Governance liquidation seizes full collateral of liquidated user and offsets the debt of the protocol\n    /// generating bad debt\n    /// @dev Market's liquidation engine should be reviewed before running this to ensure what implications does it have on the liquidation engine.\n    /// governanceLiquidate​ is not aware of liquidation engine.\n    /// @dev No fees are charged for this liquidation for the simplicity of implementation\n    /// @dev This function will only be used if normal liquidation reverts caused by its complexity\n    /// @param borrower The address of the borrower being liquidated\n    /// @param skipAccrueInterest Whether to skip interest accrual before liquidation\n    /// @return sizedCollateral The amount of collateral that was seized\n    /// @return badDebtAmount The amount of borrow token that was offset\n    function governanceLiquidate(address borrower, bool skipAccrueInterest) external returns (uint256, uint256);\n\n    /// @notice Function to set the liquidation engine for the market.\n    /// @param liquidationEngine The address of the liquidation engine\n    function setLiquidationEngine(address liquidationEngine) external;\n\n    /// @notice Address of the liquidation engine for the market.\n    /// @return The address of the liquidation engine for the market.\n    function liquidationEngine() external view returns (address);\n}\n\ninterface IMarket is IMarketBase {\n    /// @notice State of the user's position in market.\n    /// @param user The address of the user whose position is being queried\n    function position(address user) external view returns (Position memory);\n\n    /// @notice Total supply of borrow token of the market provided by the lenders.\n    function totalSupply() external view returns (Balance memory);\n\n    /// @notice Total borrowed assets of the market currently borrowed.\n    function totalBorrowed() external view returns (Balance memory);\n}\n\ninterface IMarketStaticTypes is IMarketBase {\n    /// @notice State of the user's position in market.\n    /// @param user The address of the user whose position is being queried\n    function position(address user)\n        external\n        view\n        returns (uint128 supplyShares, uint128 borrowShares, uint128 collateralAssets);\n\n    /// @notice Total supply of borrow token of the market provided by the lenders.\n    function totalSupply() external view returns (uint128 assets, uint128 shares);\n\n    /// @notice Total borrowed assets of the market currently borrowed.\n    function totalBorrowed() external view returns (uint128 assets, uint128 shares);\n}\n"},{"file_path":"contracts/lending/libraries/AssetShareConversionMath.sol","source_code":"// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity ^0.8.0;\n\nimport {FixedPointMath} from \"@alto/utils/FixedPointMath.sol\";\n\n/// @title AssetShareConversionMath\n/// @author GPM\n/// @custom:contact security@altofoundation.org\n/// @notice Library for converting between asset amounts and share amounts with precision control.\nlibrary AssetShareConversionMath {\n    using FixedPointMath for uint256;\n\n    // Precision constants for share and asset calculations\n    uint256 public constant VIRTUAL_SHARES = 1e6;\n    uint256 public constant VIRTUAL_ASSETS = 1;\n\n    /// @notice Converts assets to shares with ceiling rounding\n    /// @param assetAmount The amount of assets to convert\n    /// @param totalAssetSupply The total supply of assets\n    /// @param totalShareSupply The total supply of shares\n    /// @return The equivalent amount in shares, rounded up\n    function convertToSharesUp(uint256 assetAmount, uint256 totalAssetSupply, uint256 totalShareSupply)\n        internal\n        pure\n        returns (uint256)\n    {\n        return\n            assetAmount.divideWithRounding(totalShareSupply + VIRTUAL_SHARES, totalAssetSupply + VIRTUAL_ASSETS, true);\n    }\n\n    /// @notice Converts assets to shares with floor rounding\n    /// @param assetAmount The amount of assets to convert\n    /// @param totalAssetSupply The total supply of assets\n    /// @param totalShareSupply The total supply of shares\n    /// @return The equivalent amount in shares, rounded down\n    function convertToSharesDown(uint256 assetAmount, uint256 totalAssetSupply, uint256 totalShareSupply)\n        internal\n        pure\n        returns (uint256)\n    {\n        return\n            assetAmount.divideWithRounding(totalShareSupply + VIRTUAL_SHARES, totalAssetSupply + VIRTUAL_ASSETS, false);\n    }\n\n    /// @notice Converts shares to assets with ceiling rounding\n    /// @param shareAmount The amount of shares to convert\n    /// @param totalAssetSupply The total supply of assets\n    /// @param totalShareSupply The total supply of shares\n    /// @return The equivalent amount in assets, rounded up\n    function convertToAssetsUp(uint256 shareAmount, uint256 totalAssetSupply, uint256 totalShareSupply)\n        internal\n        pure\n        returns (uint256)\n    {\n        return\n            shareAmount.divideWithRounding(totalAssetSupply + VIRTUAL_ASSETS, totalShareSupply + VIRTUAL_SHARES, true);\n    }\n\n    /// @notice Converts shares to assets with floor rounding\n    /// @param shareAmount The amount of shares to convert\n    /// @param totalAssetSupply The total supply of assets\n    /// @param totalShareSupply The total supply of shares\n    /// @return The equivalent amount in assets, rounded down\n    function convertToAssetsDown(uint256 shareAmount, uint256 totalAssetSupply, uint256 totalShareSupply)\n        internal\n        pure\n        returns (uint256)\n    {\n        return\n            shareAmount.divideWithRounding(totalAssetSupply + VIRTUAL_ASSETS, totalShareSupply + VIRTUAL_SHARES, false);\n    }\n}\n"},{"file_path":"contracts/lending/credit-market/AltoConvexCreditLineLib.sol","source_code":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport {\n    IAltoConvexCreditLineMarketErrors,\n    IAltoConvexCreditLineMarketEvents\n} from \"@alto/lending/interfaces/IAltoConvexCreditLineMarket.sol\";\nimport {IConvexBooster} from \"@alto/lending/interfaces/vendor/IConvexBooster.sol\";\nimport {IConvexRewardPool} from \"@alto/lending/interfaces/vendor/IConvexRewardPool.sol\";\n\n/// @title Alto Convex Credit Line Library\n/// @author GPM\n/// @custom:contact security@altofoundation.org\n/// @notice Stateless Convex custody and reward operations for AltoConvexCreditLineMarket\n/// @dev Linked functions execute in the calling market's context, so `address(this)` and storage refer to the market.\n/// Custody assumes standard exact-transfer LP tokens and trusted Convex contracts with one-to-one receipt accounting.\nlibrary AltoConvexCreditLineLib {\n    using SafeERC20 for IERC20;\n\n    uint256 internal constant MAX_REWARD_TOKENS = 16;\n\n    /// @notice Validates the Convex pool configuration used to initialize the market.\n    /// @dev Confirms that the pool is active, matches the collateral token and is internally consistent with its\n    /// reward pool. The calling market separately validates the reward-token list.\n    /// @param convexBooster The Convex Booster that registers and accepts deposits for the pool.\n    /// @param convexPoolId The identifier of the pool registered in the Convex Booster.\n    /// @param collateralToken The Curve LP token used as market collateral.\n    /// @param rewardRecipient The account configured to receive claimed reward tokens.\n    /// @return convexDepositToken The Convex deposit token associated with the pool.\n    /// @return convexRewardPool The Convex reward pool in which collateral will be staked.\n    function validateConvexInitialization(\n        address convexBooster,\n        uint256 convexPoolId,\n        address collateralToken,\n        address rewardRecipient\n    ) external view returns (address convexDepositToken, address convexRewardPool) {\n        if (convexBooster == address(0) || rewardRecipient == address(0)) {\n            revert IAltoConvexCreditLineMarketErrors.AltoCreditMarketZeroAddress();\n        }\n\n        (address lpToken, address depositToken, address gauge, address rewardPool,, bool shutdown) =\n            IConvexBooster(convexBooster).poolInfo(convexPoolId);\n\n        if (lpToken == address(0) || depositToken == address(0) || gauge == address(0) || rewardPool == address(0)) {\n            revert IAltoConvexCreditLineMarketErrors.AltoCreditMarketZeroAddress();\n        }\n        if (shutdown || lpToken != collateralToken) {\n            revert IAltoConvexCreditLineMarketErrors.AltoCreditMarketInvalidInput();\n        }\n\n        IConvexRewardPool rewards = IConvexRewardPool(rewardPool);\n        if (\n            rewards.pid() != convexPoolId || rewards.operator() != convexBooster\n                || rewards.stakingToken() != depositToken\n        ) {\n            revert IAltoConvexCreditLineMarketErrors.AltoCreditMarketInvalidInput();\n        }\n\n        return (depositToken, rewardPool);\n    }\n\n    /// @notice Requests that Convex deposit collateral held by the market and stake the resulting deposit tokens.\n    /// @dev Does not independently verify the resulting collateral or stake balance changes.\n    /// @param collateralToken The Curve LP token deposited as collateral.\n    /// @param convexBooster The Convex Booster through which the collateral is deposited.\n    /// @param convexPoolId The Convex pool identifier used for the deposit.\n    /// @param assets The amount of collateral requested for deposit and staking.\n    function depositCollateralToConvex(\n        address collateralToken,\n        address convexBooster,\n        uint256 convexPoolId,\n        uint256 assets\n    ) external {\n        IERC20(collateralToken).forceApprove(convexBooster, assets);\n        bool success = IConvexBooster(convexBooster).deposit(convexPoolId, assets, true);\n        if (!success) {\n            revert IAltoConvexCreditLineMarketErrors.AltoConvexCreditLineExternalCallFailed();\n        }\n\n        IERC20(collateralToken).forceApprove(convexBooster, 0);\n        emit IAltoConvexCreditLineMarketEvents.CollateralStaked(msg.sender, assets);\n    }\n\n    /// @notice Requests withdrawal and unwrapping of collateral from Convex into the market.\n    /// @dev Does not independently verify the recovered collateral balance. The caller remains responsible for\n    /// transferring the recovered collateral to its final receiver.\n    /// @param convexRewardPool The reward pool from which the market withdraws its stake.\n    /// @param assets The amount of staked collateral requested for withdrawal and unwrapping.\n    function withdrawAndUnwrapCollateral(address convexRewardPool, uint256 assets) external {\n        bool success = IConvexRewardPool(convexRewardPool).withdrawAndUnwrap(assets, false);\n        if (!success) {\n            revert IAltoConvexCreditLineMarketErrors.AltoConvexCreditLineExternalCallFailed();\n        }\n    }\n\n    /// @notice Claims Convex rewards and forwards every configured reward-token balance to the recipient.\n    /// @dev Requests primary and extra rewards, then transfers each token's entire market balance, including any\n    /// balance held before the claim. A `RewardsClaimed` event is emitted for every configured token, including zero\n    /// amounts. Claims are atomic across Convex and every configured token. A failed claim, balance read or transfer\n    /// reverts the whole operation. Reward configuration must track changes to Convex extra rewards and wrappers.\n    /// @param convexRewardPool The reward pool from which rewards are claimed.\n    /// @param recipient The account that receives every claimed reward token.\n    /// @param rewardTokens The market's configured reward-token list, processed in storage order.\n    /// @return claimedAmounts The amount forwarded for each token at the corresponding list index.\n    function claimRewards(address convexRewardPool, address recipient, address[] storage rewardTokens)\n        external\n        returns (uint256[] memory claimedAmounts)\n    {\n        bool success = IConvexRewardPool(convexRewardPool).getReward(address(this), true);\n        if (!success) {\n            revert IAltoConvexCreditLineMarketErrors.AltoConvexCreditLineExternalCallFailed();\n        }\n\n        uint256 tokenCount = rewardTokens.length;\n        claimedAmounts = new uint256[](tokenCount);\n        for (uint256 i; i < tokenCount; ++i) {\n            IERC20 token = IERC20(rewardTokens[i]);\n            uint256 amount = token.balanceOf(address(this));\n            claimedAmounts[i] = amount;\n\n            if (amount != 0) {\n                token.safeTransfer(recipient, amount);\n            }\n\n            emit IAltoConvexCreditLineMarketEvents.RewardsClaimed(msg.sender, recipient, address(token), amount);\n        }\n    }\n\n    /// @notice Requests withdrawal and unwrapping of the market's entire reported Convex position.\n    /// @dev Skips the external withdrawal when no collateral is staked and does not independently verify the recovered\n    /// collateral balance.\n    /// @param convexRewardPool The reward pool from which the full position is withdrawn.\n    /// @return assets The reward-pool stake balance requested for withdrawal.\n    function emergencyWithdraw(address convexRewardPool) external returns (uint256 assets) {\n        assets = IConvexRewardPool(convexRewardPool).balanceOf(address(this));\n        if (assets != 0) {\n            bool success = IConvexRewardPool(convexRewardPool).withdrawAndUnwrap(assets, false);\n            if (!success) {\n                revert IAltoConvexCreditLineMarketErrors.AltoConvexCreditLineExternalCallFailed();\n            }\n        }\n    }\n\n    /// @notice Validates a token before it is added to the reward forwarding list.\n    /// @dev Rejects zero addresses, non-contracts, duplicates, reserved market tokens and additions beyond the list\n    /// limit.\n    /// @param rewardTokenCount The current number of configured reward tokens.\n    /// @param tokenAlreadyAdded Whether the token is already present in the reward-token mapping.\n    /// @param token The candidate reward-token address.\n    /// @param collateralToken The market collateral token, which cannot be added as a reward token.\n    /// @param borrowToken The market borrow token, which cannot be added as a reward token.\n    /// @param convexRewardPool The Convex reward pool whose staking token cannot be added as a reward token.\n    function validateRewardTokenAddition(\n        uint256 rewardTokenCount,\n        bool tokenAlreadyAdded,\n        address token,\n        address collateralToken,\n        address borrowToken,\n        address convexRewardPool\n    ) external view {\n        if (\n            token.code.length == 0 || rewardTokenCount >= MAX_REWARD_TOKENS || token == collateralToken\n                || token == borrowToken || token == IConvexRewardPool(convexRewardPool).stakingToken()\n                || tokenAlreadyAdded\n        ) {\n            revert IAltoConvexCreditLineMarketErrors.AltoCreditMarketInvalidInput();\n        }\n    }\n\n    /// @notice Removes a non-primary reward token that has no balance held by the market.\n    /// @dev Removes the token with swap-and-pop, so the ordering of the remaining list may change. The current primary\n    /// reward token cannot be removed. A token with a nonzero balance or a reverting `balanceOf` cannot be removed\n    /// through this path, so checking code presence when adding a token does not replace ERC-20 compatibility review.\n    /// @param rewardTokens The market's reward-token list.\n    /// @param isRewardToken The mapping that records whether a token is configured.\n    /// @param convexRewardPool The reward pool used to identify the current primary reward token.\n    /// @param token The configured reward token to remove.\n    function removeRewardToken(\n        address[] storage rewardTokens,\n        mapping(address => bool) storage isRewardToken,\n        address convexRewardPool,\n        address token\n    ) external {\n        if (\n            !isRewardToken[token] || token == IConvexRewardPool(convexRewardPool).rewardToken()\n                || IERC20(token).balanceOf(address(this)) != 0\n        ) {\n            revert IAltoConvexCreditLineMarketErrors.AltoCreditMarketInvalidInput();\n        }\n\n        uint256 tokenCount = rewardTokens.length;\n        uint256 tokenIndex = tokenCount;\n\n        for (uint256 i; i < tokenCount; ++i) {\n            if (rewardTokens[i] == token) {\n                tokenIndex = i;\n                break;\n            }\n        }\n\n        if (tokenIndex == tokenCount) {\n            revert IAltoConvexCreditLineMarketErrors.AltoCreditMarketInvalidInput();\n        }\n\n        uint256 lastIndex = tokenCount - 1;\n        if (tokenIndex != lastIndex) {\n            rewardTokens[tokenIndex] = rewardTokens[lastIndex];\n        }\n        rewardTokens.pop();\n        delete isRewardToken[token];\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\nimport {IERC1363} from \"../../../interfaces/IERC1363.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC-20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    /**\n     * @dev An operation with an ERC-20 token failed.\n     */\n    error SafeERC20FailedOperation(address token);\n\n    /**\n     * @dev Indicates a failed `decreaseAllowance` request.\n     */\n    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n    }\n\n    /**\n     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.\n     */\n    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {\n        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));\n    }\n\n    /**\n     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.\n     */\n    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {\n        return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     *\n     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n     * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        forceApprove(token, spender, oldAllowance + value);\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n     * value, non-reverting calls are assumed to be successful.\n     *\n     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n     * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n        unchecked {\n            uint256 currentAllowance = token.allowance(address(this), spender);\n            if (currentAllowance < requestedDecrease) {\n                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n            }\n            forceApprove(token, spender, currentAllowance - requestedDecrease);\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     *\n     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function\n     * only sets the \"standard\" allowance. Any temporary allowance will remain active, in addition to the value being\n     * set here.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no\n     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {\n        if (to.code.length == 0) {\n            safeTransfer(token, to, value);\n        } else if (!token.transferAndCall(to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target\n     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function transferFromAndCallRelaxed(\n        IERC1363 token,\n        address from,\n        address to,\n        uint256 value,\n        bytes memory data\n    ) internal {\n        if (to.code.length == 0) {\n            safeTransferFrom(token, from, to, value);\n        } else if (!token.transferFromAndCall(from, to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no\n     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.\n     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}\n     * once without retrying, and relies on the returned value to be true.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {\n        if (to.code.length == 0) {\n            forceApprove(token, to, value);\n        } else if (!token.approveAndCall(to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        uint256 returnSize;\n        uint256 returnValue;\n        assembly (\"memory-safe\") {\n            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n            // bubble errors\n            if iszero(success) {\n                let ptr := mload(0x40)\n                returndatacopy(ptr, 0, returndatasize())\n                revert(ptr, returndatasize())\n            }\n            returnSize := returndatasize()\n            returnValue := mload(0)\n        }\n\n        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        bool success;\n        uint256 returnSize;\n        uint256 returnValue;\n        assembly (\"memory-safe\") {\n            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n            returnSize := returndatasize()\n            returnValue := mload(0)\n        }\n        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Strings.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/Strings.sol)\n\npragma solidity ^0.8.20;\n\nimport {Math} from \"./math/Math.sol\";\nimport {SafeCast} from \"./math/SafeCast.sol\";\nimport {SignedMath} from \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    using SafeCast for *;\n\n    bytes16 private constant HEX_DIGITS = \"0123456789abcdef\";\n    uint8 private constant ADDRESS_LENGTH = 20;\n    uint256 private constant SPECIAL_CHARS_LOOKUP =\n        (1 << 0x08) | // backspace\n            (1 << 0x09) | // tab\n            (1 << 0x0a) | // newline\n            (1 << 0x0c) | // form feed\n            (1 << 0x0d) | // carriage return\n            (1 << 0x22) | // double quote\n            (1 << 0x5c); // backslash\n\n    /**\n     * @dev The `value` string doesn't fit in the specified `length`.\n     */\n    error StringsInsufficientHexLength(uint256 value, uint256 length);\n\n    /**\n     * @dev The string being parsed contains characters that are not in scope of the given base.\n     */\n    error StringsInvalidChar();\n\n    /**\n     * @dev The string being parsed is not a properly formatted address.\n     */\n    error StringsInvalidAddressFormat();\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            uint256 length = Math.log10(value) + 1;\n            string memory buffer = new string(length);\n            uint256 ptr;\n            assembly (\"memory-safe\") {\n                ptr := add(add(buffer, 0x20), length)\n            }\n            while (true) {\n                ptr--;\n                assembly (\"memory-safe\") {\n                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))\n                }\n                value /= 10;\n                if (value == 0) break;\n            }\n            return buffer;\n        }\n    }\n\n    /**\n     * @dev Converts a `int256` to its ASCII `string` decimal representation.\n     */\n    function toStringSigned(int256 value) internal pure returns (string memory) {\n        return string.concat(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value)));\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            return toHexString(value, Math.log256(value) + 1);\n        }\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        uint256 localValue = value;\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = HEX_DIGITS[localValue & 0xf];\n            localValue >>= 4;\n        }\n        if (localValue != 0) {\n            revert StringsInsufficientHexLength(value, length);\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal\n     * representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal\n     * representation, according to EIP-55.\n     */\n    function toChecksumHexString(address addr) internal pure returns (string memory) {\n        bytes memory buffer = bytes(toHexString(addr));\n\n        // hash the hex part of buffer (skip length + 2 bytes, length 40)\n        uint256 hashValue;\n        assembly (\"memory-safe\") {\n            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))\n        }\n\n        for (uint256 i = 41; i > 1; --i) {\n            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)\n            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {\n                // case shift by xoring with 0x20\n                buffer[i] ^= 0x20;\n            }\n            hashValue >>= 4;\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Returns true if the two strings are equal.\n     */\n    function equal(string memory a, string memory b) internal pure returns (bool) {\n        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));\n    }\n\n    /**\n     * @dev Parse a decimal string and returns the value as a `uint256`.\n     *\n     * Requirements:\n     * - The string must be formatted as `[0-9]*`\n     * - The result must fit into an `uint256` type\n     */\n    function parseUint(string memory input) internal pure returns (uint256) {\n        return parseUint(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `[0-9]*`\n     * - The result must fit into an `uint256` type\n     */\n    function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {\n        (bool success, uint256 value) = tryParseUint(input, begin, end);\n        if (!success) revert StringsInvalidChar();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {\n        return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid\n     * character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseUint(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, uint256 value) {\n        if (end > bytes(input).length || begin > end) return (false, 0);\n        return _tryParseUintUncheckedBounds(input, begin, end);\n    }\n\n    /**\n     * @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that\n     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.\n     */\n    function _tryParseUintUncheckedBounds(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) private pure returns (bool success, uint256 value) {\n        bytes memory buffer = bytes(input);\n\n        uint256 result = 0;\n        for (uint256 i = begin; i < end; ++i) {\n            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));\n            if (chr > 9) return (false, 0);\n            result *= 10;\n            result += chr;\n        }\n        return (true, result);\n    }\n\n    /**\n     * @dev Parse a decimal string and returns the value as a `int256`.\n     *\n     * Requirements:\n     * - The string must be formatted as `[-+]?[0-9]*`\n     * - The result must fit in an `int256` type.\n     */\n    function parseInt(string memory input) internal pure returns (int256) {\n        return parseInt(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `[-+]?[0-9]*`\n     * - The result must fit in an `int256` type.\n     */\n    function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {\n        (bool success, int256 value) = tryParseInt(input, begin, end);\n        if (!success) revert StringsInvalidChar();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if\n     * the result does not fit in a `int256`.\n     *\n     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.\n     */\n    function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {\n        return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);\n    }\n\n    uint256 private constant ABS_MIN_INT256 = 2 ** 255;\n\n    /**\n     * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid\n     * character or if the result does not fit in a `int256`.\n     *\n     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.\n     */\n    function tryParseInt(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, int256 value) {\n        if (end > bytes(input).length || begin > end) return (false, 0);\n        return _tryParseIntUncheckedBounds(input, begin, end);\n    }\n\n    /**\n     * @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that\n     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.\n     */\n    function _tryParseIntUncheckedBounds(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) private pure returns (bool success, int256 value) {\n        bytes memory buffer = bytes(input);\n\n        // Check presence of a negative sign.\n        bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty\n        bool positiveSign = sign == bytes1(\"+\");\n        bool negativeSign = sign == bytes1(\"-\");\n        uint256 offset = (positiveSign || negativeSign).toUint();\n\n        (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);\n\n        if (absSuccess && absValue < ABS_MIN_INT256) {\n            return (true, negativeSign ? -int256(absValue) : int256(absValue));\n        } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {\n            return (true, type(int256).min);\n        } else return (false, 0);\n    }\n\n    /**\n     * @dev Parse a hexadecimal string (with or without \"0x\" prefix), and returns the value as a `uint256`.\n     *\n     * Requirements:\n     * - The string must be formatted as `(0x)?[0-9a-fA-F]*`\n     * - The result must fit in an `uint256` type.\n     */\n    function parseHexUint(string memory input) internal pure returns (uint256) {\n        return parseHexUint(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`\n     * - The result must fit in an `uint256` type.\n     */\n    function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {\n        (bool success, uint256 value) = tryParseHexUint(input, begin, end);\n        if (!success) revert StringsInvalidChar();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {\n        return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an\n     * invalid character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseHexUint(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, uint256 value) {\n        if (end > bytes(input).length || begin > end) return (false, 0);\n        return _tryParseHexUintUncheckedBounds(input, begin, end);\n    }\n\n    /**\n     * @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that\n     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.\n     */\n    function _tryParseHexUintUncheckedBounds(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) private pure returns (bool success, uint256 value) {\n        bytes memory buffer = bytes(input);\n\n        // skip 0x prefix if present\n        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2(\"0x\"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty\n        uint256 offset = hasPrefix.toUint() * 2;\n\n        uint256 result = 0;\n        for (uint256 i = begin + offset; i < end; ++i) {\n            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));\n            if (chr > 15) return (false, 0);\n            result *= 16;\n            unchecked {\n                // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).\n                // This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.\n                result += chr;\n            }\n        }\n        return (true, result);\n    }\n\n    /**\n     * @dev Parse a hexadecimal string (with or without \"0x\" prefix), and returns the value as an `address`.\n     *\n     * Requirements:\n     * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`\n     */\n    function parseAddress(string memory input) internal pure returns (address) {\n        return parseAddress(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`\n     */\n    function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {\n        (bool success, address value) = tryParseAddress(input, begin, end);\n        if (!success) revert StringsInvalidAddressFormat();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly\n     * formatted address. See {parseAddress-string} requirements.\n     */\n    function tryParseAddress(string memory input) internal pure returns (bool success, address value) {\n        return tryParseAddress(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly\n     * formatted address. See {parseAddress-string-uint256-uint256} requirements.\n     */\n    function tryParseAddress(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, address value) {\n        if (end > bytes(input).length || begin > end) return (false, address(0));\n\n        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2(\"0x\"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty\n        uint256 expectedLength = 40 + hasPrefix.toUint() * 2;\n\n        // check that input is the correct length\n        if (end - begin == expectedLength) {\n            // length guarantees that this does not overflow, and value is at most type(uint160).max\n            (bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);\n            return (s, address(uint160(v)));\n        } else {\n            return (false, address(0));\n        }\n    }\n\n    function _tryParseChr(bytes1 chr) private pure returns (uint8) {\n        uint8 value = uint8(chr);\n\n        // Try to parse `chr`:\n        // - Case 1: [0-9]\n        // - Case 2: [a-f]\n        // - Case 3: [A-F]\n        // - otherwise not supported\n        unchecked {\n            if (value > 47 && value < 58) value -= 48;\n            else if (value > 96 && value < 103) value -= 87;\n            else if (value > 64 && value < 71) value -= 55;\n            else return type(uint8).max;\n        }\n\n        return value;\n    }\n\n    /**\n     * @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.\n     *\n     * WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.\n     *\n     * NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of\n     * RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode\n     * characters that are not in this range, but other tooling may provide different results.\n     */\n    function escapeJSON(string memory input) internal pure returns (string memory) {\n        bytes memory buffer = bytes(input);\n        bytes memory output = new bytes(2 * buffer.length); // worst case scenario\n        uint256 outputLength = 0;\n\n        for (uint256 i; i < buffer.length; ++i) {\n            bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));\n            if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {\n                output[outputLength++] = \"\\\\\";\n                if (char == 0x08) output[outputLength++] = \"b\";\n                else if (char == 0x09) output[outputLength++] = \"t\";\n                else if (char == 0x0a) output[outputLength++] = \"n\";\n                else if (char == 0x0c) output[outputLength++] = \"f\";\n                else if (char == 0x0d) output[outputLength++] = \"r\";\n                else if (char == 0x5c) output[outputLength++] = \"\\\\\";\n                else if (char == 0x22) {\n                    // solhint-disable-next-line quotes\n                    output[outputLength++] = '\"';\n                }\n            } else {\n                output[outputLength++] = char;\n            }\n        }\n        // write the actual length and deallocate unused memory\n        assembly (\"memory-safe\") {\n            mstore(output, outputLength)\n            mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))\n        }\n\n        return string(output);\n    }\n\n    /**\n     * @dev Reads a bytes32 from a bytes array without bounds checking.\n     *\n     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the\n     * assembly block as such would prevent some optimizations.\n     */\n    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {\n        // This is not memory safe in the general case, but all calls to this private function are within bounds.\n        assembly (\"memory-safe\") {\n            value := mload(add(add(buffer, 0x20), offset))\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)\n\npragma solidity >=0.4.11;\n\n/**\n * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.\n */\ninterface IERC1967 {\n    /**\n     * @dev Emitted when the implementation is upgraded.\n     */\n    event Upgraded(address indexed implementation);\n\n    /**\n     * @dev Emitted when the admin account has changed.\n     */\n    event AdminChanged(address previousAdmin, address newAdmin);\n\n    /**\n     * @dev Emitted when the beacon is changed.\n     */\n    event BeaconUpgraded(address indexed beacon);\n}\n"},{"file_path":"contracts/lending/interfaces/vendor/IConvexBooster.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Convex Booster Interface\n/// @notice Minimal Ethereum Convex Booster surface used by the credit line.\ninterface IConvexBooster {\n    /// @notice Returns the configuration for a Convex pool\n    function poolInfo(uint256 pid)\n        external\n        view\n        returns (address lpToken, address depositToken, address gauge, address rewardPool, address stash, bool shutdown);\n\n    /// @notice Deposits LP tokens into a Convex pool\n    function deposit(uint256 pid, uint256 amount, bool stake) external returns (bool);\n}\n"},{"file_path":"contracts/utils/interfaces/IPausable.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IPausable {\n    event PauserUpdated(address indexed pauser, bytes32 pauseType, bool status);\n    event Paused(address indexed pauser, bytes32 pauseType, bool paused);\n\n    error Unauthorized(address pauser, bytes32 pauseType);\n    error IsPaused(bytes32 pauseType);\n    error StateNotChanged(bytes32 pauseType, bool currentState, bool newState);\n\n    function paused(bytes32 pauseType) external view returns (bool);\n    function setPauser(address pauser, bytes32 pauseType, bool status) external;\n    function pause(bytes32 pauseType, bool _paused) external;\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/MessageHashUtils.sol)\n\npragma solidity ^0.8.20;\n\nimport {Strings} from \"../Strings.sol\";\n\n/**\n * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.\n *\n * The library provides methods for generating a hash of a message that conforms to the\n * https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]\n * specifications.\n */\nlibrary MessageHashUtils {\n    /**\n     * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n     * `0x45` (`personal_sign` messages).\n     *\n     * The digest is calculated by prefixing a bytes32 `messageHash` with\n     * `\"\\x19Ethereum Signed Message:\\n32\"` and hashing the result. It corresponds with the\n     * hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.\n     *\n     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with\n     * keccak256, although any bytes32 value can be safely used because the final digest will\n     * be re-hashed.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {\n        assembly (\"memory-safe\") {\n            mstore(0x00, \"\\x19Ethereum Signed Message:\\n32\") // 32 is the bytes-length of messageHash\n            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix\n            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)\n        }\n    }\n\n    /**\n     * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n     * `0x45` (`personal_sign` messages).\n     *\n     * The digest is calculated by prefixing an arbitrary `message` with\n     * `\"\\x19Ethereum Signed Message:\\n\" + len(message)` and hashing the result. It corresponds with the\n     * hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {\n        return\n            keccak256(bytes.concat(\"\\x19Ethereum Signed Message:\\n\", bytes(Strings.toString(message.length)), message));\n    }\n\n    /**\n     * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n     * `0x00` (data with intended validator).\n     *\n     * The digest is calculated by prefixing an arbitrary `data` with `\"\\x19\\x00\"` and the intended\n     * `validator` address. Then hashing the result.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(hex\"19_00\", validator, data));\n    }\n\n    /**\n     * @dev Variant of {toDataWithIntendedValidatorHash-address-bytes} optimized for cases where `data` is a bytes32.\n     */\n    function toDataWithIntendedValidatorHash(\n        address validator,\n        bytes32 messageHash\n    ) internal pure returns (bytes32 digest) {\n        assembly (\"memory-safe\") {\n            mstore(0x00, hex\"19_00\")\n            mstore(0x02, shl(96, validator))\n            mstore(0x16, messageHash)\n            digest := keccak256(0x00, 0x36)\n        }\n    }\n\n    /**\n     * @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).\n     *\n     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with\n     * `\\x19\\x01` and hashing the result. It corresponds to the hash signed by the\n     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40)\n            mstore(ptr, hex\"19_01\")\n            mstore(add(ptr, 0x02), domainSeparator)\n            mstore(add(ptr, 0x22), structHash)\n            digest := keccak256(ptr, 0x42)\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (proxy/ERC1967/ERC1967Utils.sol)\n\npragma solidity ^0.8.21;\n\nimport {IBeacon} from \"../beacon/IBeacon.sol\";\nimport {IERC1967} from \"../../interfaces/IERC1967.sol\";\nimport {Address} from \"../../utils/Address.sol\";\nimport {StorageSlot} from \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This library provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.\n */\nlibrary ERC1967Utils {\n    /**\n     * @dev Storage slot with the address of the current implementation.\n     * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n    /**\n     * @dev The `implementation` of the proxy is invalid.\n     */\n    error ERC1967InvalidImplementation(address implementation);\n\n    /**\n     * @dev The `admin` of the proxy is invalid.\n     */\n    error ERC1967InvalidAdmin(address admin);\n\n    /**\n     * @dev The `beacon` of the proxy is invalid.\n     */\n    error ERC1967InvalidBeacon(address beacon);\n\n    /**\n     * @dev An upgrade function sees `msg.value > 0` that may be lost.\n     */\n    error ERC1967NonPayable();\n\n    /**\n     * @dev Returns the current implementation address.\n     */\n    function getImplementation() internal view returns (address) {\n        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the ERC-1967 implementation slot.\n     */\n    function _setImplementation(address newImplementation) private {\n        if (newImplementation.code.length == 0) {\n            revert ERC1967InvalidImplementation(newImplementation);\n        }\n        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;\n    }\n\n    /**\n     * @dev Performs implementation upgrade with additional setup call if data is nonempty.\n     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n     * to avoid stuck value in the contract.\n     *\n     * Emits an {IERC1967-Upgraded} event.\n     */\n    function upgradeToAndCall(address newImplementation, bytes memory data) internal {\n        _setImplementation(newImplementation);\n        emit IERC1967.Upgraded(newImplementation);\n\n        if (data.length > 0) {\n            Address.functionDelegateCall(newImplementation, data);\n        } else {\n            _checkNonPayable();\n        }\n    }\n\n    /**\n     * @dev Storage slot with the admin of the contract.\n     * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n    /**\n     * @dev Returns the current admin.\n     *\n     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n     */\n    function getAdmin() internal view returns (address) {\n        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the ERC-1967 admin slot.\n     */\n    function _setAdmin(address newAdmin) private {\n        if (newAdmin == address(0)) {\n            revert ERC1967InvalidAdmin(address(0));\n        }\n        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;\n    }\n\n    /**\n     * @dev Changes the admin of the proxy.\n     *\n     * Emits an {IERC1967-AdminChanged} event.\n     */\n    function changeAdmin(address newAdmin) internal {\n        emit IERC1967.AdminChanged(getAdmin(), newAdmin);\n        _setAdmin(newAdmin);\n    }\n\n    /**\n     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n     * This is the keccak-256 hash of \"eip1967.proxy.beacon\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n    /**\n     * @dev Returns the current beacon.\n     */\n    function getBeacon() internal view returns (address) {\n        return StorageSlot.getAddressSlot(BEACON_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new beacon in the ERC-1967 beacon slot.\n     */\n    function _setBeacon(address newBeacon) private {\n        if (newBeacon.code.length == 0) {\n            revert ERC1967InvalidBeacon(newBeacon);\n        }\n\n        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;\n\n        address beaconImplementation = IBeacon(newBeacon).implementation();\n        if (beaconImplementation.code.length == 0) {\n            revert ERC1967InvalidImplementation(beaconImplementation);\n        }\n    }\n\n    /**\n     * @dev Change the beacon and trigger a setup call if data is nonempty.\n     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n     * to avoid stuck value in the contract.\n     *\n     * Emits an {IERC1967-BeaconUpgraded} event.\n     *\n     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since\n     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for\n     * efficiency.\n     */\n    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {\n        _setBeacon(newBeacon);\n        emit IERC1967.BeaconUpgraded(newBeacon);\n\n        if (data.length > 0) {\n            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n        } else {\n            _checkNonPayable();\n        }\n    }\n\n    /**\n     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract\n     * if an upgrade doesn't perform an initialization call.\n     */\n    function _checkNonPayable() private {\n        if (msg.value > 0) {\n            revert ERC1967NonPayable();\n        }\n    }\n}\n"},{"file_path":"contracts/utils/interfaces/IAuth.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nstruct Authorization {\n    address owner;\n    address spender;\n    bool isAuthorizedStatus;\n    uint256 nonce;\n    uint256 deadline;\n}\n\nstruct Signature {\n    uint8 v;\n    bytes32 r;\n    bytes32 s;\n}\n\ninterface IAuth {\n    /// @notice Emitted when the authorization is set.\n    /// @param caller The address of the caller.\n    /// @param owner The address of the owner.\n    /// @param spender The address of the spender.\n    /// @param isAuthorized The authorization status.\n    event SetAuthorization(address indexed caller, address indexed owner, address indexed spender, bool isAuthorized);\n\n    /// @notice Emitted when the nonce is incremented.\n    /// @param caller The address of the caller.\n    /// @param owner The address of the owner.\n    /// @param nonce The nonce.\n    event IncrementNonce(address indexed caller, address indexed owner, uint256 nonce);\n\n    /// @notice Error thrown when the authorization is already set.\n    error AuthAuthorizationAlreadySet();\n\n    /// @notice Error thrown when the signature's deadline expired.\n    error AuthSignatureExpired();\n\n    /// @notice Error thrown when the nonce is invalid.\n    error AuthInvalidNonce();\n\n    /// @notice Error thrown when the signature is invalid because of various reasons.\n    error AuthInvalidSignature();\n\n    /// @dev Returns whether the sender is authorized to manage `owner`'s positions.\n    /// @param owner The address of the owner.\n    /// @param spender The address of the spender.\n    /// @return isAuthorized Whether the sender is authorized to manage `owner`'s positions.\n    function isAuthorized(address owner, address spender) external view returns (bool);\n\n    /// @dev Returns the nonce for the owner.\n    /// @param owner The address of the owner.\n    /// @return nonce The nonce for the owner.\n    function nonce(address owner) external view returns (uint256);\n\n    /// @dev Sets the authorization for `spender` to `isAuthorizedStatus`.\n    /// @param spender The address to set the authorization for.\n    /// @param isAuthorizedStatus The authorization status to set.\n    function setAuthorization(address spender, bool isAuthorizedStatus) external;\n\n    /// @dev Sets the authorization for `spender` to `isAuthorizedStatus` status using a signature.\n    /// @param authData The authorization to set.\n    /// @param sigData The signature of the owner.\n    function setAuthorizationWithSignature(Authorization memory authData, Signature calldata sigData) external;\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-20 standard as defined in the ERC.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 value) external returns (bool);\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/UUPSUpgradeable.sol)\n\npragma solidity ^0.8.22;\n\nimport {IERC1822Proxiable} from \"@openzeppelin/contracts/interfaces/draft-IERC1822.sol\";\nimport {ERC1967Utils} from \"@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol\";\nimport {Initializable} from \"./Initializable.sol\";\n\n/**\n * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an\n * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.\n *\n * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is\n * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing\n * `UUPSUpgradeable` with a custom implementation of upgrades.\n *\n * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.\n */\nabstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {\n    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n    address private immutable __self = address(this);\n\n    /**\n     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`\n     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,\n     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.\n     * If the getter returns `\"5.0.0\"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must\n     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function\n     * during an upgrade.\n     */\n    string public constant UPGRADE_INTERFACE_VERSION = \"5.0.0\";\n\n    /**\n     * @dev The call is from an unauthorized context.\n     */\n    error UUPSUnauthorizedCallContext();\n\n    /**\n     * @dev The storage `slot` is unsupported as a UUID.\n     */\n    error UUPSUnsupportedProxiableUUID(bytes32 slot);\n\n    /**\n     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is\n     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case\n     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a\n     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to\n     * fail.\n     */\n    modifier onlyProxy() {\n        _checkProxy();\n        _;\n    }\n\n    /**\n     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be\n     * callable on the implementing contract but not through proxies.\n     */\n    modifier notDelegated() {\n        _checkNotDelegated();\n        _;\n    }\n\n    function __UUPSUpgradeable_init() internal onlyInitializing {\n    }\n\n    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the\n     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.\n     *\n     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.\n     */\n    function proxiableUUID() external view virtual notDelegated returns (bytes32) {\n        return ERC1967Utils.IMPLEMENTATION_SLOT;\n    }\n\n    /**\n     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call\n     * encoded in `data`.\n     *\n     * Calls {_authorizeUpgrade}.\n     *\n     * Emits an {Upgraded} event.\n     *\n     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall\n     */\n    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {\n        _authorizeUpgrade(newImplementation);\n        _upgradeToAndCallUUPS(newImplementation, data);\n    }\n\n    /**\n     * @dev Reverts if the execution is not performed via delegatecall or the execution\n     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.\n     */\n    function _checkProxy() internal view virtual {\n        if (\n            address(this) == __self || // Must be called through delegatecall\n            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy\n        ) {\n            revert UUPSUnauthorizedCallContext();\n        }\n    }\n\n    /**\n     * @dev Reverts if the execution is performed via delegatecall.\n     * See {notDelegated}.\n     */\n    function _checkNotDelegated() internal view virtual {\n        if (address(this) != __self) {\n            // Must not be called through delegatecall\n            revert UUPSUnauthorizedCallContext();\n        }\n    }\n\n    /**\n     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by\n     * {upgradeToAndCall}.\n     *\n     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.\n     *\n     * ```solidity\n     * function _authorizeUpgrade(address) internal onlyOwner {}\n     * ```\n     */\n    function _authorizeUpgrade(address newImplementation) internal virtual;\n\n    /**\n     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.\n     *\n     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value\n     * is expected to be the implementation slot in ERC-1967.\n     *\n     * Emits an {IERC1967-Upgraded} event.\n     */\n    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {\n        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {\n                revert UUPSUnsupportedProxiableUUID(slot);\n            }\n            ERC1967Utils.upgradeToAndCall(newImplementation, data);\n        } catch {\n            // The implementation is not UUPS\n            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);\n        }\n    }\n}\n"},{"file_path":"contracts/utils/Constants.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nbytes32 constant PAUSE_TYPE = keccak256(\"PAUSE_TYPE\");\n\nbytes32 constant RESCUE_TYPE = keccak256(\"RESCUE_TYPE\");\n\nbytes32 constant FROZEN_TYPE = keccak256(\"FROZEN_TYPE\");\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)\n\npragma solidity >=0.4.16;\n\nimport {IERC20} from \"../token/ERC20/IERC20.sol\";\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {IERC165} from \"./IERC165.sol\";\n\n/**\n * @title IERC1363\n * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].\n *\n * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract\n * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.\n */\ninterface IERC1363 is IERC20, IERC165 {\n    /*\n     * Note: the ERC-165 identifier for this interface is 0xb0202a11.\n     * 0xb0202a11 ===\n     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^\n     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^\n     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^\n     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^\n     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^\n     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))\n     */\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferAndCall(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @param data Additional data with no specified format, sent in call to `to`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param from The address which you want to send tokens from.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param from The address which you want to send tokens from.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @param data Additional data with no specified format, sent in call to `to`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.\n     * @param spender The address which will spend the funds.\n     * @param value The amount of tokens to be spent.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function approveAndCall(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.\n     * @param spender The address which will spend the funds.\n     * @param value The amount of tokens to be spent.\n     * @param data Additional data with no specified format, sent in call to `spender`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n    /**\n     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n     * address.\n     *\n     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n     * function revert if invoked through a proxy.\n     */\n    function proxiableUUID() external view returns (bytes32);\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ContextUpgradeable} from \"../utils/ContextUpgradeable.sol\";\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is set to the address provided by the deployer. This can\n * later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable\n    struct OwnableStorage {\n        address _owner;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Ownable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;\n\n    function _getOwnableStorage() private pure returns (OwnableStorage storage $) {\n        assembly {\n            $.slot := OwnableStorageLocation\n        }\n    }\n\n    /**\n     * @dev The caller account is not authorized to perform an operation.\n     */\n    error OwnableUnauthorizedAccount(address account);\n\n    /**\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\n     */\n    error OwnableInvalidOwner(address owner);\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n     */\n    function __Ownable_init(address initialOwner) internal onlyInitializing {\n        __Ownable_init_unchained(initialOwner);\n    }\n\n    function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {\n        if (initialOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(initialOwner);\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        OwnableStorage storage $ = _getOwnableStorage();\n        return $._owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        if (owner() != _msgSender()) {\n            revert OwnableUnauthorizedAccount(_msgSender());\n        }\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        if (newOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        OwnableStorage storage $ = _getOwnableStorage();\n        address oldOwner = $._owner;\n        $._owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1271.sol)\n\npragma solidity >=0.5.0;\n\n/**\n * @dev Interface of the ERC-1271 standard signature validation method for\n * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].\n */\ninterface IERC1271 {\n    /**\n     * @dev Should return whether the signature provided is valid for the provided data\n     * @param hash      Hash of the data to be signed\n     * @param signature Signature byte array associated with `hash`\n     */\n    function isValidSignature(bytes32 hash, bytes calldata signature) external view returns (bytes4 magicValue);\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)\n\npragma solidity >=0.4.16;\n\nimport {IERC165} from \"../utils/introspection/IERC165.sol\";\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\nimport {Panic} from \"../Panic.sol\";\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    enum Rounding {\n        Floor, // Toward negative infinity\n        Ceil, // Toward positive infinity\n        Trunc, // Toward zero\n        Expand // Away from zero\n    }\n\n    /**\n     * @dev Return the 512-bit addition of two uint256.\n     *\n     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.\n     */\n    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {\n        assembly (\"memory-safe\") {\n            low := add(a, b)\n            high := lt(low, a)\n        }\n    }\n\n    /**\n     * @dev Return the 512-bit multiplication of two uint256.\n     *\n     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.\n     */\n    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {\n        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use\n        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n        // variables such that product = high * 2²⁵⁶ + low.\n        assembly (\"memory-safe\") {\n            let mm := mulmod(a, b, not(0))\n            low := mul(a, b)\n            high := sub(sub(mm, low), lt(mm, low))\n        }\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a + b;\n            success = c >= a;\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a - b;\n            success = c <= a;\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a * b;\n            assembly (\"memory-safe\") {\n                // Only true when the multiplication doesn't overflow\n                // (c / a == b) || (a == 0)\n                success := or(eq(div(c, a), b), iszero(a))\n            }\n            // equivalent to: success ? c : 0\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            success = b > 0;\n            assembly (\"memory-safe\") {\n                // The `DIV` opcode returns zero when the denominator is 0.\n                result := div(a, b)\n            }\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            success = b > 0;\n            assembly (\"memory-safe\") {\n                // The `MOD` opcode returns zero when the denominator is 0.\n                result := mod(a, b)\n            }\n        }\n    }\n\n    /**\n     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.\n     */\n    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {\n        (bool success, uint256 result) = tryAdd(a, b);\n        return ternary(success, result, type(uint256).max);\n    }\n\n    /**\n     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.\n     */\n    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {\n        (, uint256 result) = trySub(a, b);\n        return result;\n    }\n\n    /**\n     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.\n     */\n    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {\n        (bool success, uint256 result) = tryMul(a, b);\n        return ternary(success, result, type(uint256).max);\n    }\n\n    /**\n     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.\n     *\n     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.\n     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute\n     * one branch when needed, making this function more expensive.\n     */\n    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {\n        unchecked {\n            // branchless ternary works because:\n            // b ^ (a ^ b) == a\n            // b ^ 0 == b\n            return b ^ ((a ^ b) * SafeCast.toUint(condition));\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return ternary(a > b, a, b);\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return ternary(a < b, a, b);\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds towards infinity instead\n     * of rounding towards zero.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (b == 0) {\n            // Guarantee the same behavior as in a regular Solidity division.\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n\n        // The following calculation ensures accurate ceiling division without overflow.\n        // Since a is non-zero, (a - 1) / b will not overflow.\n        // The largest possible result occurs when (a - 1) / b is type(uint256).max,\n        // but the largest value we can obtain is type(uint256).max - 1, which happens\n        // when a = type(uint256).max and b = 1.\n        unchecked {\n            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);\n        }\n    }\n\n    /**\n     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n     * denominator == 0.\n     *\n     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n     * Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            (uint256 high, uint256 low) = mul512(x, y);\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (high == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return low / denominator;\n            }\n\n            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.\n            if (denominator <= high) {\n                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));\n            }\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [high low].\n            uint256 remainder;\n            assembly (\"memory-safe\") {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                high := sub(high, gt(remainder, low))\n                low := sub(low, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n            uint256 twos = denominator & (0 - denominator);\n            assembly (\"memory-safe\") {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [high low] by twos.\n                low := div(low, twos)\n\n                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from high into low.\n            low |= high * twos;\n\n            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such\n            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n            // works in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2⁸\n            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶\n            inverse *= 2 - denominator * inverse; // inverse mod 2³²\n            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴\n            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸\n            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is\n            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high\n            // is no longer required.\n            result = low * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);\n    }\n\n    /**\n     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.\n     */\n    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {\n        unchecked {\n            (uint256 high, uint256 low) = mul512(x, y);\n            if (high >= 1 << n) {\n                Panic.panic(Panic.UNDER_OVERFLOW);\n            }\n            return (high << (256 - n)) | (low >> n);\n        }\n    }\n\n    /**\n     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.\n     */\n    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {\n        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);\n    }\n\n    /**\n     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.\n     *\n     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.\n     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.\n     *\n     * If the input value is not inversible, 0 is returned.\n     *\n     * 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\n     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.\n     */\n    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {\n        unchecked {\n            if (n == 0) return 0;\n\n            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)\n            // Used to compute integers x and y such that: ax + ny = gcd(a, n).\n            // When the gcd is 1, then the inverse of a modulo n exists and it's x.\n            // ax + ny = 1\n            // ax = 1 + (-y)n\n            // ax ≡ 1 (mod n) # x is the inverse of a modulo n\n\n            // If the remainder is 0 the gcd is n right away.\n            uint256 remainder = a % n;\n            uint256 gcd = n;\n\n            // Therefore the initial coefficients are:\n            // ax + ny = gcd(a, n) = n\n            // 0a + 1n = n\n            int256 x = 0;\n            int256 y = 1;\n\n            while (remainder != 0) {\n                uint256 quotient = gcd / remainder;\n\n                (gcd, remainder) = (\n                    // The old remainder is the next gcd to try.\n                    remainder,\n                    // Compute the next remainder.\n                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd\n                    // where gcd is at most n (capped to type(uint256).max)\n                    gcd - remainder * quotient\n                );\n\n                (x, y) = (\n                    // Increment the coefficient of a.\n                    y,\n                    // Decrement the coefficient of n.\n                    // Can overflow, but the result is casted to uint256 so that the\n                    // next value of y is \"wrapped around\" to a value between 0 and n - 1.\n                    x - y * int256(quotient)\n                );\n            }\n\n            if (gcd != 1) return 0; // No inverse exists.\n            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.\n        }\n    }\n\n    /**\n     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.\n     *\n     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is\n     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that\n     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.\n     *\n     * NOTE: this function does NOT check that `p` is a prime greater than `2`.\n     */\n    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {\n        unchecked {\n            return Math.modExp(a, p - 2, p);\n        }\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)\n     *\n     * Requirements:\n     * - modulus can't be zero\n     * - underlying staticcall to precompile must succeed\n     *\n     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make\n     * sure the chain you're using it on supports the precompiled contract for modular exponentiation\n     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,\n     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly\n     * interpreted as 0.\n     */\n    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {\n        (bool success, uint256 result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).\n     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying\n     * to operate modulo 0 or if the underlying precompile reverted.\n     *\n     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain\n     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in\n     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack\n     * of a revert, but the result may be incorrectly interpreted as 0.\n     */\n    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {\n        if (m == 0) return (false, 0);\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40)\n            // | Offset    | Content    | Content (Hex)                                                      |\n            // |-----------|------------|--------------------------------------------------------------------|\n            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x60:0x7f | value of b | 0x<.............................................................b> |\n            // | 0x80:0x9f | value of e | 0x<.............................................................e> |\n            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |\n            mstore(ptr, 0x20)\n            mstore(add(ptr, 0x20), 0x20)\n            mstore(add(ptr, 0x40), 0x20)\n            mstore(add(ptr, 0x60), b)\n            mstore(add(ptr, 0x80), e)\n            mstore(add(ptr, 0xa0), m)\n\n            // Given the result < m, it's guaranteed to fit in 32 bytes,\n            // so we can use the memory scratch space located at offset 0.\n            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)\n            result := mload(0x00)\n        }\n    }\n\n    /**\n     * @dev Variant of {modExp} that supports inputs of arbitrary length.\n     */\n    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {\n        (bool success, bytes memory result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.\n     */\n    function tryModExp(\n        bytes memory b,\n        bytes memory e,\n        bytes memory m\n    ) internal view returns (bool success, bytes memory result) {\n        if (_zeroBytes(m)) return (false, new bytes(0));\n\n        uint256 mLen = m.length;\n\n        // Encode call args in result and move the free memory pointer\n        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);\n\n        assembly (\"memory-safe\") {\n            let dataPtr := add(result, 0x20)\n            // Write result on top of args to avoid allocating extra memory.\n            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)\n            // Overwrite the length.\n            // result.length > returndatasize() is guaranteed because returndatasize() == m.length\n            mstore(result, mLen)\n            // Set the memory pointer after the returned data.\n            mstore(0x40, add(dataPtr, mLen))\n        }\n    }\n\n    /**\n     * @dev Returns whether the provided byte array is zero.\n     */\n    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {\n        for (uint256 i = 0; i < byteArray.length; ++i) {\n            if (byteArray[i] != 0) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n     * towards zero.\n     *\n     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only\n     * using integer operations.\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        unchecked {\n            // Take care of easy edge cases when a == 0 or a == 1\n            if (a <= 1) {\n                return a;\n            }\n\n            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a\n            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between\n            // the current value as `ε_n = | x_n - sqrt(a) |`.\n            //\n            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root\n            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is\n            // bigger than any uint256.\n            //\n            // By noticing that\n            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`\n            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar\n            // to the msb function.\n            uint256 aa = a;\n            uint256 xn = 1;\n\n            if (aa >= (1 << 128)) {\n                aa >>= 128;\n                xn <<= 64;\n            }\n            if (aa >= (1 << 64)) {\n                aa >>= 64;\n                xn <<= 32;\n            }\n            if (aa >= (1 << 32)) {\n                aa >>= 32;\n                xn <<= 16;\n            }\n            if (aa >= (1 << 16)) {\n                aa >>= 16;\n                xn <<= 8;\n            }\n            if (aa >= (1 << 8)) {\n                aa >>= 8;\n                xn <<= 4;\n            }\n            if (aa >= (1 << 4)) {\n                aa >>= 4;\n                xn <<= 2;\n            }\n            if (aa >= (1 << 2)) {\n                xn <<= 1;\n            }\n\n            // 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).\n            //\n            // We can refine our estimation by noticing that the middle of that interval minimizes the error.\n            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).\n            // This is going to be our x_0 (and ε_0)\n            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)\n\n            // From here, Newton's method give us:\n            // x_{n+1} = (x_n + a / x_n) / 2\n            //\n            // One should note that:\n            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a\n            //              = ((x_n² + a) / (2 * x_n))² - a\n            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a\n            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)\n            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)\n            //              = (x_n² - a)² / (2 * x_n)²\n            //              = ((x_n² - a) / (2 * x_n))²\n            //              ≥ 0\n            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n\n            //\n            // This gives us the proof of quadratic convergence of the sequence:\n            // ε_{n+1} = | x_{n+1} - sqrt(a) |\n            //         = | (x_n + a / x_n) / 2 - sqrt(a) |\n            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |\n            //         = | (x_n - sqrt(a))² / (2 * x_n) |\n            //         = | ε_n² / (2 * x_n) |\n            //         = ε_n² / | (2 * x_n) |\n            //\n            // For the first iteration, we have a special case where x_0 is known:\n            // ε_1 = ε_0² / | (2 * x_0) |\n            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))\n            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))\n            //     ≤ 2**(e-3) / 3\n            //     ≤ 2**(e-3-log2(3))\n            //     ≤ 2**(e-4.5)\n            //\n            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:\n            // ε_{n+1} = ε_n² / | (2 * x_n) |\n            //         ≤ (2**(e-k))² / (2 * 2**(e-1))\n            //         ≤ 2**(2*e-2*k) / 2**e\n            //         ≤ 2**(e-2*k)\n            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above\n            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5\n            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9\n            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18\n            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36\n            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72\n\n            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision\n            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either\n            // sqrt(a) or sqrt(a) + 1.\n            return xn - SafeCast.toUint(xn > a / xn);\n        }\n    }\n\n    /**\n     * @dev Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 x) internal pure returns (uint256 r) {\n        // If value has upper 128 bits set, log2 result is at least 128\n        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;\n        // If upper 64 bits of 128-bit half set, add 64 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;\n        // If upper 32 bits of 64-bit half set, add 32 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;\n        // If upper 16 bits of 32-bit half set, add 16 to result\n        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;\n        // If upper 8 bits of 16-bit half set, add 8 to result\n        r |= SafeCast.toUint((x >> r) > 0xff) << 3;\n        // If upper 4 bits of 8-bit half set, add 4 to result\n        r |= SafeCast.toUint((x >> r) > 0xf) << 2;\n\n        // Shifts value right by the current result and use it as an index into this lookup table:\n        //\n        // | x (4 bits) |  index  | table[index] = MSB position |\n        // |------------|---------|-----------------------------|\n        // |    0000    |    0    |        table[0] = 0         |\n        // |    0001    |    1    |        table[1] = 0         |\n        // |    0010    |    2    |        table[2] = 1         |\n        // |    0011    |    3    |        table[3] = 1         |\n        // |    0100    |    4    |        table[4] = 2         |\n        // |    0101    |    5    |        table[5] = 2         |\n        // |    0110    |    6    |        table[6] = 2         |\n        // |    0111    |    7    |        table[7] = 2         |\n        // |    1000    |    8    |        table[8] = 3         |\n        // |    1001    |    9    |        table[9] = 3         |\n        // |    1010    |   10    |        table[10] = 3        |\n        // |    1011    |   11    |        table[11] = 3        |\n        // |    1100    |   12    |        table[12] = 3        |\n        // |    1101    |   13    |        table[13] = 3        |\n        // |    1110    |   14    |        table[14] = 3        |\n        // |    1111    |   15    |        table[15] = 3        |\n        //\n        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.\n        assembly (\"memory-safe\") {\n            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 x) internal pure returns (uint256 r) {\n        // If value has upper 128 bits set, log2 result is at least 128\n        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;\n        // If upper 64 bits of 128-bit half set, add 64 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;\n        // If upper 32 bits of 64-bit half set, add 32 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;\n        // If upper 16 bits of 32-bit half set, add 16 to result\n        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;\n        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8\n        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);\n        }\n    }\n\n    /**\n     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n     */\n    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n        return uint8(rounding) % 2 == 1;\n    }\n}\n"},{"file_path":"contracts/utils/Pausable.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPausable} from \"./interfaces/IPausable.sol\";\n\nabstract contract Pausable is IPausable {\n    mapping(bytes32 => bool) public paused;\n    mapping(address => mapping(bytes32 => bool)) public pausers;\n\n    function setPauser(address pauser, bytes32 pauseType, bool status) external virtual;\n\n    /// @notice Modifier to check if the caller is a pauser\n    modifier onlyPauser(bytes32 pauseType) {\n        if (!pausers[msg.sender][pauseType]) revert Unauthorized(msg.sender, pauseType);\n        _;\n    }\n\n    /// @notice Modifier to check if the market is not paused\n    modifier whenNot(bytes32 pauseType) {\n        if (paused[pauseType]) revert IsPaused(pauseType);\n        _;\n    }\n\n    /// @notice Pauses or unpauses the market\n    /// @param _paused The new paused state\n    function pause(bytes32 pauseType, bool _paused) external onlyPauser(pauseType) {\n        _onPause(pauseType, _paused);\n        if (paused[pauseType] == _paused) {\n            revert StateNotChanged(pauseType, paused[pauseType], _paused);\n        }\n        paused[pauseType] = _paused;\n        emit Paused(msg.sender, pauseType, _paused);\n    }\n\n    /// @notice Virtual function to allow for custom logic when pausing/unpausing\n    /// @param pauseType The type of pause\n    /// @param _paused The new paused state\n    /// @dev This function is called before the pause/unpause is applied to the paused state.\n    function _onPause(bytes32 pauseType, bool _paused) internal virtual {}\n\n    /// @param pauser The address of the pauser\n    /// @param pauseType The type of pause\n    /// @param status The new status of the pauser\n    function _setPauser(address pauser, bytes32 pauseType, bool status) internal {\n        pausers[pauser][pauseType] = status;\n        emit PauserUpdated(pauser, pauseType, status);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Errors.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of common custom errors used in multiple contracts\n *\n * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.\n * It is recommended to avoid relying on the error API for critical functionality.\n *\n * _Available since v5.1._\n */\nlibrary Errors {\n    /**\n     * @dev The ETH balance of the account is not enough to perform the operation.\n     */\n    error InsufficientBalance(uint256 balance, uint256 needed);\n\n    /**\n     * @dev A call to an address target failed. The target may have reverted.\n     */\n    error FailedCall();\n\n    /**\n     * @dev The deployment failed.\n     */\n    error FailedDeployment();\n\n    /**\n     * @dev A necessary precompile is missing.\n     */\n    error MissingPrecompile(address);\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n    function __Context_init() internal onlyInitializing {\n    }\n\n    function __Context_init_unchained() internal onlyInitializing {\n    }\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.20;\n\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n    /**\n     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.\n     *\n     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.\n     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute\n     * one branch when needed, making this function more expensive.\n     */\n    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {\n        unchecked {\n            // branchless ternary works because:\n            // b ^ (a ^ b) == a\n            // b ^ 0 == b\n            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two signed numbers.\n     */\n    function max(int256 a, int256 b) internal pure returns (int256) {\n        return ternary(a > b, a, b);\n    }\n\n    /**\n     * @dev Returns the smallest of two signed numbers.\n     */\n    function min(int256 a, int256 b) internal pure returns (int256) {\n        return ternary(a < b, a, b);\n    }\n\n    /**\n     * @dev Returns the average of two signed numbers without overflow.\n     * The result is rounded towards zero.\n     */\n    function average(int256 a, int256 b) internal pure returns (int256) {\n        // Formula from the book \"Hacker's Delight\"\n        int256 x = (a & b) + ((a ^ b) >> 1);\n        return x + (int256(uint256(x) >> 255) & (a ^ b));\n    }\n\n    /**\n     * @dev Returns the absolute unsigned value of a signed value.\n     */\n    function abs(int256 n) internal pure returns (uint256) {\n        unchecked {\n            // Formula from the \"Bit Twiddling Hacks\" by Sean Eron Anderson.\n            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,\n            // taking advantage of the most significant (or \"sign\" bit) in two's complement representation.\n            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,\n            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).\n            int256 mask = n >> 255;\n\n            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.\n            return uint256((n + mask) ^ mask);\n        }\n    }\n}\n"},{"file_path":"contracts/utils/AuthUpgradeable.sol","source_code":"// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity ^0.8.19;\n\nimport {IAuth, Authorization, Signature} from \"./interfaces/IAuth.sol\";\nimport {EIP712Upgradeable} from \"@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol\";\nimport {SignatureChecker} from \"@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol\";\n\n/// @title AuthUpgradeable\n/// @author GPM\n/// @custom:contact security@altofoundation.org\n/// @notice A contract that allows for authorization of addresses (upgradeable version).\n/// @dev This is used in several Alto contracts to authorize addresses to manage positions.\n/// The main purpose is to allow for transaction bundling.\nabstract contract AuthUpgradeable is IAuth, EIP712Upgradeable {\n    bytes32 internal constant _AUTHORIZATION_TYPEHASH = keccak256(\n        \"Authorization(address owner,address spender,bool isAuthorizedStatus,uint256 nonce,uint256 deadline)\"\n    );\n\n    /// @inheritdoc IAuth\n    mapping(address => mapping(address => bool)) public isAuthorized;\n    /// @inheritdoc IAuth\n    mapping(address => uint256) public nonce;\n\n    function __Auth_init() internal onlyInitializing {\n        __EIP712_init(\"Alto\", \"1\");\n    }\n\n    /// @inheritdoc IAuth\n    function setAuthorization(address spender, bool isAuthorizedStatus) external {\n        if (isAuthorizedStatus == isAuthorized[msg.sender][spender]) {\n            revert AuthAuthorizationAlreadySet();\n        }\n\n        isAuthorized[msg.sender][spender] = isAuthorizedStatus;\n\n        emit SetAuthorization(msg.sender, msg.sender, spender, isAuthorizedStatus);\n    }\n\n    /// @inheritdoc IAuth\n    function setAuthorizationWithSignature(Authorization memory authData, Signature calldata sigData) external {\n        if (block.timestamp > authData.deadline) {\n            revert AuthSignatureExpired();\n        }\n        if (authData.nonce != nonce[authData.owner]++) {\n            revert AuthInvalidNonce();\n        }\n\n        bytes32 structHash = keccak256(abi.encode(_AUTHORIZATION_TYPEHASH, authData));\n        bytes32 hash = _hashTypedDataV4(structHash);\n\n        bool isValid = SignatureChecker.isValidSignatureNow(\n            authData.owner, hash, abi.encodePacked(sigData.r, sigData.s, sigData.v)\n        );\n        if (!isValid) {\n            revert AuthInvalidSignature();\n        }\n\n        isAuthorized[authData.owner][authData.spender] = authData.isAuthorizedStatus;\n\n        emit IncrementNonce(msg.sender, authData.owner, authData.nonce);\n        emit SetAuthorization(msg.sender, authData.owner, authData.spender, authData.isAuthorizedStatus);\n    }\n\n    /// @dev Returns whether the sender is authorized to manage `owner`'s positions.\n    function _isSenderAuthorized(address owner) internal view returns (bool) {\n        return msg.sender == owner || isAuthorized[owner][msg.sender];\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/cryptography/SignatureChecker.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/cryptography/SignatureChecker.sol)\n\npragma solidity ^0.8.24;\n\nimport {ECDSA} from \"./ECDSA.sol\";\nimport {IERC1271} from \"../../interfaces/IERC1271.sol\";\nimport {IERC7913SignatureVerifier} from \"../../interfaces/IERC7913.sol\";\nimport {Bytes} from \"../../utils/Bytes.sol\";\n\n/**\n * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support:\n *\n * * ECDSA signatures from externally owned accounts (EOAs)\n * * ERC-1271 signatures from smart contract wallets like Argent and Safe Wallet (previously Gnosis Safe)\n * * ERC-7913 signatures from keys that do not have an Ethereum address of their own\n *\n * See https://eips.ethereum.org/EIPS/eip-1271[ERC-1271] and https://eips.ethereum.org/EIPS/eip-7913[ERC-7913].\n */\nlibrary SignatureChecker {\n    using Bytes for bytes;\n\n    /**\n     * @dev Checks if a signature is valid for a given signer and data hash. If the signer has code, the\n     * signature is validated against it using ERC-1271, otherwise it's validated using `ECDSA.recover`.\n     *\n     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus\n     * change through time. It could return true at block N and false at block N+1 (or the opposite).\n     *\n     * NOTE: For an extended version of this function that supports ERC-7913 signatures, see {isValidSignatureNow-bytes-bytes32-bytes-}.\n     */\n    function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {\n        if (signer.code.length == 0) {\n            (address recovered, ECDSA.RecoverError err, ) = ECDSA.tryRecover(hash, signature);\n            return err == ECDSA.RecoverError.NoError && recovered == signer;\n        } else {\n            return isValidERC1271SignatureNow(signer, hash, signature);\n        }\n    }\n\n    /**\n     * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated\n     * against the signer smart contract using ERC-1271.\n     *\n     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus\n     * change through time. It could return true at block N and false at block N+1 (or the opposite).\n     */\n    function isValidERC1271SignatureNow(\n        address signer,\n        bytes32 hash,\n        bytes memory signature\n    ) internal view returns (bool) {\n        (bool success, bytes memory result) = signer.staticcall(\n            abi.encodeCall(IERC1271.isValidSignature, (hash, signature))\n        );\n        return (success &&\n            result.length >= 32 &&\n            abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));\n    }\n\n    /**\n     * @dev Verifies a signature for a given ERC-7913 signer and hash.\n     *\n     * The signer is a `bytes` object that is the concatenation of an address and optionally a key:\n     * `verifier || key`. A signer must be at least 20 bytes long.\n     *\n     * Verification is done as follows:\n     *\n     * * If `signer.length < 20`: verification fails\n     * * If `signer.length == 20`: verification is done using {isValidSignatureNow}\n     * * Otherwise: verification is done using {IERC7913SignatureVerifier}\n     *\n     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus\n     * change through time. It could return true at block N and false at block N+1 (or the opposite).\n     */\n    function isValidSignatureNow(\n        bytes memory signer,\n        bytes32 hash,\n        bytes memory signature\n    ) internal view returns (bool) {\n        if (signer.length < 20) {\n            return false;\n        } else if (signer.length == 20) {\n            return isValidSignatureNow(address(bytes20(signer)), hash, signature);\n        } else {\n            (bool success, bytes memory result) = address(bytes20(signer)).staticcall(\n                abi.encodeCall(IERC7913SignatureVerifier.verify, (signer.slice(20), hash, signature))\n            );\n            return (success &&\n                result.length >= 32 &&\n                abi.decode(result, (bytes32)) == bytes32(IERC7913SignatureVerifier.verify.selector));\n        }\n    }\n\n    /**\n     * @dev Verifies multiple ERC-7913 `signatures` for a given `hash` using a set of `signers`.\n     * Returns `false` if the number of signers and signatures is not the same.\n     *\n     * The signers should be ordered by their `keccak256` hash to ensure efficient duplication check. Unordered\n     * signers are supported, but the uniqueness check will be more expensive.\n     *\n     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus\n     * change through time. It could return true at block N and false at block N+1 (or the opposite).\n     */\n    function areValidSignaturesNow(\n        bytes32 hash,\n        bytes[] memory signers,\n        bytes[] memory signatures\n    ) internal view returns (bool) {\n        if (signers.length != signatures.length) return false;\n\n        bytes32 lastId = bytes32(0);\n\n        for (uint256 i = 0; i < signers.length; ++i) {\n            bytes memory signer = signers[i];\n\n            // If one of the signatures is invalid, reject the batch\n            if (!isValidSignatureNow(signer, hash, signatures[i])) return false;\n\n            bytes32 id = keccak256(signer);\n            // If the current signer ID is greater than all previous IDs, then this is a new signer.\n            if (lastId < id) {\n                lastId = id;\n            } else {\n                // If this signer id is not greater than all the previous ones, verify that it is not a duplicate of a previous one\n                // This loop is never executed if the signers are ordered by id.\n                for (uint256 j = 0; j < i; ++j) {\n                    if (id == keccak256(signers[j])) return false;\n                }\n            }\n        }\n\n        return true;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Panic.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Helper library for emitting standardized panic codes.\n *\n * ```solidity\n * contract Example {\n *      using Panic for uint256;\n *\n *      // Use any of the declared internal constants\n *      function foo() { Panic.GENERIC.panic(); }\n *\n *      // Alternatively\n *      function foo() { Panic.panic(Panic.GENERIC); }\n * }\n * ```\n *\n * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].\n *\n * _Available since v5.1._\n */\n// slither-disable-next-line unused-state\nlibrary Panic {\n    /// @dev generic / unspecified error\n    uint256 internal constant GENERIC = 0x00;\n    /// @dev used by the assert() builtin\n    uint256 internal constant ASSERT = 0x01;\n    /// @dev arithmetic underflow or overflow\n    uint256 internal constant UNDER_OVERFLOW = 0x11;\n    /// @dev division or modulo by zero\n    uint256 internal constant DIVISION_BY_ZERO = 0x12;\n    /// @dev enum conversion error\n    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;\n    /// @dev invalid encoding in storage\n    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;\n    /// @dev empty array pop\n    uint256 internal constant EMPTY_ARRAY_POP = 0x31;\n    /// @dev array out of bounds access\n    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;\n    /// @dev resource error (too large allocation or too large array)\n    uint256 internal constant RESOURCE_ERROR = 0x41;\n    /// @dev calling invalid internal function\n    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;\n\n    /// @dev Reverts with a panic code. Recommended to use with\n    /// the internal constants with predefined codes.\n    function panic(uint256 code) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0x00, 0x4e487b71)\n            mstore(0x20, code)\n            revert(0x1c, 0x24)\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n    /**\n     * @dev Must return an address that can be used as a delegate call target.\n     *\n     * {UpgradeableBeacon} will check that this address is a contract.\n     */\n    function implementation() external view returns (address);\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeCast {\n    /**\n     * @dev Value doesn't fit in an uint of `bits` size.\n     */\n    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);\n\n    /**\n     * @dev An int value doesn't fit in an uint of `bits` size.\n     */\n    error SafeCastOverflowedIntToUint(int256 value);\n\n    /**\n     * @dev Value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);\n\n    /**\n     * @dev An uint value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedUintToInt(uint256 value);\n\n    /**\n     * @dev Returns the downcasted uint248 from uint256, reverting on\n     * overflow (when the input is greater than largest uint248).\n     *\n     * Counterpart to Solidity's `uint248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     */\n    function toUint248(uint256 value) internal pure returns (uint248) {\n        if (value > type(uint248).max) {\n            revert SafeCastOverflowedUintDowncast(248, value);\n        }\n        return uint248(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint240 from uint256, reverting on\n     * overflow (when the input is greater than largest uint240).\n     *\n     * Counterpart to Solidity's `uint240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     */\n    function toUint240(uint256 value) internal pure returns (uint240) {\n        if (value > type(uint240).max) {\n            revert SafeCastOverflowedUintDowncast(240, value);\n        }\n        return uint240(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint232 from uint256, reverting on\n     * overflow (when the input is greater than largest uint232).\n     *\n     * Counterpart to Solidity's `uint232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     */\n    function toUint232(uint256 value) internal pure returns (uint232) {\n        if (value > type(uint232).max) {\n            revert SafeCastOverflowedUintDowncast(232, value);\n        }\n        return uint232(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint224 from uint256, reverting on\n     * overflow (when the input is greater than largest uint224).\n     *\n     * Counterpart to Solidity's `uint224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toUint224(uint256 value) internal pure returns (uint224) {\n        if (value > type(uint224).max) {\n            revert SafeCastOverflowedUintDowncast(224, value);\n        }\n        return uint224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint216 from uint256, reverting on\n     * overflow (when the input is greater than largest uint216).\n     *\n     * Counterpart to Solidity's `uint216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     */\n    function toUint216(uint256 value) internal pure returns (uint216) {\n        if (value > type(uint216).max) {\n            revert SafeCastOverflowedUintDowncast(216, value);\n        }\n        return uint216(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint208 from uint256, reverting on\n     * overflow (when the input is greater than largest uint208).\n     *\n     * Counterpart to Solidity's `uint208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     */\n    function toUint208(uint256 value) internal pure returns (uint208) {\n        if (value > type(uint208).max) {\n            revert SafeCastOverflowedUintDowncast(208, value);\n        }\n        return uint208(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint200 from uint256, reverting on\n     * overflow (when the input is greater than largest uint200).\n     *\n     * Counterpart to Solidity's `uint200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     */\n    function toUint200(uint256 value) internal pure returns (uint200) {\n        if (value > type(uint200).max) {\n            revert SafeCastOverflowedUintDowncast(200, value);\n        }\n        return uint200(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint192 from uint256, reverting on\n     * overflow (when the input is greater than largest uint192).\n     *\n     * Counterpart to Solidity's `uint192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     */\n    function toUint192(uint256 value) internal pure returns (uint192) {\n        if (value > type(uint192).max) {\n            revert SafeCastOverflowedUintDowncast(192, value);\n        }\n        return uint192(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint184 from uint256, reverting on\n     * overflow (when the input is greater than largest uint184).\n     *\n     * Counterpart to Solidity's `uint184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     */\n    function toUint184(uint256 value) internal pure returns (uint184) {\n        if (value > type(uint184).max) {\n            revert SafeCastOverflowedUintDowncast(184, value);\n        }\n        return uint184(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint176 from uint256, reverting on\n     * overflow (when the input is greater than largest uint176).\n     *\n     * Counterpart to Solidity's `uint176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     */\n    function toUint176(uint256 value) internal pure returns (uint176) {\n        if (value > type(uint176).max) {\n            revert SafeCastOverflowedUintDowncast(176, value);\n        }\n        return uint176(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint168 from uint256, reverting on\n     * overflow (when the input is greater than largest uint168).\n     *\n     * Counterpart to Solidity's `uint168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     */\n    function toUint168(uint256 value) internal pure returns (uint168) {\n        if (value > type(uint168).max) {\n            revert SafeCastOverflowedUintDowncast(168, value);\n        }\n        return uint168(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint160 from uint256, reverting on\n     * overflow (when the input is greater than largest uint160).\n     *\n     * Counterpart to Solidity's `uint160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     */\n    function toUint160(uint256 value) internal pure returns (uint160) {\n        if (value > type(uint160).max) {\n            revert SafeCastOverflowedUintDowncast(160, value);\n        }\n        return uint160(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint152 from uint256, reverting on\n     * overflow (when the input is greater than largest uint152).\n     *\n     * Counterpart to Solidity's `uint152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     */\n    function toUint152(uint256 value) internal pure returns (uint152) {\n        if (value > type(uint152).max) {\n            revert SafeCastOverflowedUintDowncast(152, value);\n        }\n        return uint152(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint144 from uint256, reverting on\n     * overflow (when the input is greater than largest uint144).\n     *\n     * Counterpart to Solidity's `uint144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     */\n    function toUint144(uint256 value) internal pure returns (uint144) {\n        if (value > type(uint144).max) {\n            revert SafeCastOverflowedUintDowncast(144, value);\n        }\n        return uint144(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint136 from uint256, reverting on\n     * overflow (when the input is greater than largest uint136).\n     *\n     * Counterpart to Solidity's `uint136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     */\n    function toUint136(uint256 value) internal pure returns (uint136) {\n        if (value > type(uint136).max) {\n            revert SafeCastOverflowedUintDowncast(136, value);\n        }\n        return uint136(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint128 from uint256, reverting on\n     * overflow (when the input is greater than largest uint128).\n     *\n     * Counterpart to Solidity's `uint128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        if (value > type(uint128).max) {\n            revert SafeCastOverflowedUintDowncast(128, value);\n        }\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint120 from uint256, reverting on\n     * overflow (when the input is greater than largest uint120).\n     *\n     * Counterpart to Solidity's `uint120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     */\n    function toUint120(uint256 value) internal pure returns (uint120) {\n        if (value > type(uint120).max) {\n            revert SafeCastOverflowedUintDowncast(120, value);\n        }\n        return uint120(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint112 from uint256, reverting on\n     * overflow (when the input is greater than largest uint112).\n     *\n     * Counterpart to Solidity's `uint112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     */\n    function toUint112(uint256 value) internal pure returns (uint112) {\n        if (value > type(uint112).max) {\n            revert SafeCastOverflowedUintDowncast(112, value);\n        }\n        return uint112(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint104 from uint256, reverting on\n     * overflow (when the input is greater than largest uint104).\n     *\n     * Counterpart to Solidity's `uint104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     */\n    function toUint104(uint256 value) internal pure returns (uint104) {\n        if (value > type(uint104).max) {\n            revert SafeCastOverflowedUintDowncast(104, value);\n        }\n        return uint104(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint96 from uint256, reverting on\n     * overflow (when the input is greater than largest uint96).\n     *\n     * Counterpart to Solidity's `uint96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toUint96(uint256 value) internal pure returns (uint96) {\n        if (value > type(uint96).max) {\n            revert SafeCastOverflowedUintDowncast(96, value);\n        }\n        return uint96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint88 from uint256, reverting on\n     * overflow (when the input is greater than largest uint88).\n     *\n     * Counterpart to Solidity's `uint88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     */\n    function toUint88(uint256 value) internal pure returns (uint88) {\n        if (value > type(uint88).max) {\n            revert SafeCastOverflowedUintDowncast(88, value);\n        }\n        return uint88(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint80 from uint256, reverting on\n     * overflow (when the input is greater than largest uint80).\n     *\n     * Counterpart to Solidity's `uint80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     */\n    function toUint80(uint256 value) internal pure returns (uint80) {\n        if (value > type(uint80).max) {\n            revert SafeCastOverflowedUintDowncast(80, value);\n        }\n        return uint80(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint72 from uint256, reverting on\n     * overflow (when the input is greater than largest uint72).\n     *\n     * Counterpart to Solidity's `uint72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     */\n    function toUint72(uint256 value) internal pure returns (uint72) {\n        if (value > type(uint72).max) {\n            revert SafeCastOverflowedUintDowncast(72, value);\n        }\n        return uint72(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint64 from uint256, reverting on\n     * overflow (when the input is greater than largest uint64).\n     *\n     * Counterpart to Solidity's `uint64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        if (value > type(uint64).max) {\n            revert SafeCastOverflowedUintDowncast(64, value);\n        }\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint56 from uint256, reverting on\n     * overflow (when the input is greater than largest uint56).\n     *\n     * Counterpart to Solidity's `uint56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     */\n    function toUint56(uint256 value) internal pure returns (uint56) {\n        if (value > type(uint56).max) {\n            revert SafeCastOverflowedUintDowncast(56, value);\n        }\n        return uint56(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint48 from uint256, reverting on\n     * overflow (when the input is greater than largest uint48).\n     *\n     * Counterpart to Solidity's `uint48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     */\n    function toUint48(uint256 value) internal pure returns (uint48) {\n        if (value > type(uint48).max) {\n            revert SafeCastOverflowedUintDowncast(48, value);\n        }\n        return uint48(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint40 from uint256, reverting on\n     * overflow (when the input is greater than largest uint40).\n     *\n     * Counterpart to Solidity's `uint40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     */\n    function toUint40(uint256 value) internal pure returns (uint40) {\n        if (value > type(uint40).max) {\n            revert SafeCastOverflowedUintDowncast(40, value);\n        }\n        return uint40(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint32 from uint256, reverting on\n     * overflow (when the input is greater than largest uint32).\n     *\n     * Counterpart to Solidity's `uint32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        if (value > type(uint32).max) {\n            revert SafeCastOverflowedUintDowncast(32, value);\n        }\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint24 from uint256, reverting on\n     * overflow (when the input is greater than largest uint24).\n     *\n     * Counterpart to Solidity's `uint24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     */\n    function toUint24(uint256 value) internal pure returns (uint24) {\n        if (value > type(uint24).max) {\n            revert SafeCastOverflowedUintDowncast(24, value);\n        }\n        return uint24(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint16 from uint256, reverting on\n     * overflow (when the input is greater than largest uint16).\n     *\n     * Counterpart to Solidity's `uint16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        if (value > type(uint16).max) {\n            revert SafeCastOverflowedUintDowncast(16, value);\n        }\n        return uint16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint8 from uint256, reverting on\n     * overflow (when the input is greater than largest uint8).\n     *\n     * Counterpart to Solidity's `uint8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        if (value > type(uint8).max) {\n            revert SafeCastOverflowedUintDowncast(8, value);\n        }\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        if (value < 0) {\n            revert SafeCastOverflowedIntToUint(value);\n        }\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int248 from int256, reverting on\n     * overflow (when the input is less than smallest int248 or\n     * greater than largest int248).\n     *\n     * Counterpart to Solidity's `int248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     */\n    function toInt248(int256 value) internal pure returns (int248 downcasted) {\n        downcasted = int248(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(248, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int240 from int256, reverting on\n     * overflow (when the input is less than smallest int240 or\n     * greater than largest int240).\n     *\n     * Counterpart to Solidity's `int240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     */\n    function toInt240(int256 value) internal pure returns (int240 downcasted) {\n        downcasted = int240(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(240, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int232 from int256, reverting on\n     * overflow (when the input is less than smallest int232 or\n     * greater than largest int232).\n     *\n     * Counterpart to Solidity's `int232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     */\n    function toInt232(int256 value) internal pure returns (int232 downcasted) {\n        downcasted = int232(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(232, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int224 from int256, reverting on\n     * overflow (when the input is less than smallest int224 or\n     * greater than largest int224).\n     *\n     * Counterpart to Solidity's `int224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toInt224(int256 value) internal pure returns (int224 downcasted) {\n        downcasted = int224(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(224, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int216 from int256, reverting on\n     * overflow (when the input is less than smallest int216 or\n     * greater than largest int216).\n     *\n     * Counterpart to Solidity's `int216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     */\n    function toInt216(int256 value) internal pure returns (int216 downcasted) {\n        downcasted = int216(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(216, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int208 from int256, reverting on\n     * overflow (when the input is less than smallest int208 or\n     * greater than largest int208).\n     *\n     * Counterpart to Solidity's `int208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     */\n    function toInt208(int256 value) internal pure returns (int208 downcasted) {\n        downcasted = int208(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(208, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int200 from int256, reverting on\n     * overflow (when the input is less than smallest int200 or\n     * greater than largest int200).\n     *\n     * Counterpart to Solidity's `int200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     */\n    function toInt200(int256 value) internal pure returns (int200 downcasted) {\n        downcasted = int200(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(200, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int192 from int256, reverting on\n     * overflow (when the input is less than smallest int192 or\n     * greater than largest int192).\n     *\n     * Counterpart to Solidity's `int192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     */\n    function toInt192(int256 value) internal pure returns (int192 downcasted) {\n        downcasted = int192(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(192, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int184 from int256, reverting on\n     * overflow (when the input is less than smallest int184 or\n     * greater than largest int184).\n     *\n     * Counterpart to Solidity's `int184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     */\n    function toInt184(int256 value) internal pure returns (int184 downcasted) {\n        downcasted = int184(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(184, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int176 from int256, reverting on\n     * overflow (when the input is less than smallest int176 or\n     * greater than largest int176).\n     *\n     * Counterpart to Solidity's `int176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     */\n    function toInt176(int256 value) internal pure returns (int176 downcasted) {\n        downcasted = int176(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(176, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int168 from int256, reverting on\n     * overflow (when the input is less than smallest int168 or\n     * greater than largest int168).\n     *\n     * Counterpart to Solidity's `int168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     */\n    function toInt168(int256 value) internal pure returns (int168 downcasted) {\n        downcasted = int168(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(168, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int160 from int256, reverting on\n     * overflow (when the input is less than smallest int160 or\n     * greater than largest int160).\n     *\n     * Counterpart to Solidity's `int160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     */\n    function toInt160(int256 value) internal pure returns (int160 downcasted) {\n        downcasted = int160(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(160, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int152 from int256, reverting on\n     * overflow (when the input is less than smallest int152 or\n     * greater than largest int152).\n     *\n     * Counterpart to Solidity's `int152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     */\n    function toInt152(int256 value) internal pure returns (int152 downcasted) {\n        downcasted = int152(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(152, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int144 from int256, reverting on\n     * overflow (when the input is less than smallest int144 or\n     * greater than largest int144).\n     *\n     * Counterpart to Solidity's `int144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     */\n    function toInt144(int256 value) internal pure returns (int144 downcasted) {\n        downcasted = int144(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(144, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int136 from int256, reverting on\n     * overflow (when the input is less than smallest int136 or\n     * greater than largest int136).\n     *\n     * Counterpart to Solidity's `int136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     */\n    function toInt136(int256 value) internal pure returns (int136 downcasted) {\n        downcasted = int136(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(136, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toInt128(int256 value) internal pure returns (int128 downcasted) {\n        downcasted = int128(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(128, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int120 from int256, reverting on\n     * overflow (when the input is less than smallest int120 or\n     * greater than largest int120).\n     *\n     * Counterpart to Solidity's `int120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     */\n    function toInt120(int256 value) internal pure returns (int120 downcasted) {\n        downcasted = int120(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(120, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int112 from int256, reverting on\n     * overflow (when the input is less than smallest int112 or\n     * greater than largest int112).\n     *\n     * Counterpart to Solidity's `int112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     */\n    function toInt112(int256 value) internal pure returns (int112 downcasted) {\n        downcasted = int112(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(112, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int104 from int256, reverting on\n     * overflow (when the input is less than smallest int104 or\n     * greater than largest int104).\n     *\n     * Counterpart to Solidity's `int104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     */\n    function toInt104(int256 value) internal pure returns (int104 downcasted) {\n        downcasted = int104(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(104, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int96 from int256, reverting on\n     * overflow (when the input is less than smallest int96 or\n     * greater than largest int96).\n     *\n     * Counterpart to Solidity's `int96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toInt96(int256 value) internal pure returns (int96 downcasted) {\n        downcasted = int96(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(96, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int88 from int256, reverting on\n     * overflow (when the input is less than smallest int88 or\n     * greater than largest int88).\n     *\n     * Counterpart to Solidity's `int88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     */\n    function toInt88(int256 value) internal pure returns (int88 downcasted) {\n        downcasted = int88(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(88, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int80 from int256, reverting on\n     * overflow (when the input is less than smallest int80 or\n     * greater than largest int80).\n     *\n     * Counterpart to Solidity's `int80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     */\n    function toInt80(int256 value) internal pure returns (int80 downcasted) {\n        downcasted = int80(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(80, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int72 from int256, reverting on\n     * overflow (when the input is less than smallest int72 or\n     * greater than largest int72).\n     *\n     * Counterpart to Solidity's `int72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     */\n    function toInt72(int256 value) internal pure returns (int72 downcasted) {\n        downcasted = int72(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(72, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toInt64(int256 value) internal pure returns (int64 downcasted) {\n        downcasted = int64(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(64, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int56 from int256, reverting on\n     * overflow (when the input is less than smallest int56 or\n     * greater than largest int56).\n     *\n     * Counterpart to Solidity's `int56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     */\n    function toInt56(int256 value) internal pure returns (int56 downcasted) {\n        downcasted = int56(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(56, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int48 from int256, reverting on\n     * overflow (when the input is less than smallest int48 or\n     * greater than largest int48).\n     *\n     * Counterpart to Solidity's `int48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     */\n    function toInt48(int256 value) internal pure returns (int48 downcasted) {\n        downcasted = int48(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(48, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int40 from int256, reverting on\n     * overflow (when the input is less than smallest int40 or\n     * greater than largest int40).\n     *\n     * Counterpart to Solidity's `int40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     */\n    function toInt40(int256 value) internal pure returns (int40 downcasted) {\n        downcasted = int40(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(40, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toInt32(int256 value) internal pure returns (int32 downcasted) {\n        downcasted = int32(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(32, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int24 from int256, reverting on\n     * overflow (when the input is less than smallest int24 or\n     * greater than largest int24).\n     *\n     * Counterpart to Solidity's `int24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     */\n    function toInt24(int256 value) internal pure returns (int24 downcasted) {\n        downcasted = int24(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(24, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toInt16(int256 value) internal pure returns (int16 downcasted) {\n        downcasted = int16(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(16, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     */\n    function toInt8(int256 value) internal pure returns (int8 downcasted) {\n        downcasted = int8(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(8, value);\n        }\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        if (value > uint256(type(int256).max)) {\n            revert SafeCastOverflowedUintToInt(value);\n        }\n        return int256(value);\n    }\n\n    /**\n     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.\n     */\n    function toUint(bool b) internal pure returns (uint256 u) {\n        assembly (\"memory-safe\") {\n            u := iszero(iszero(b))\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[ERC].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},{"file_path":"contracts/lending/interfaces/IAltoLiquidationEngine.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Balance, Position} from \"@alto/lending/interfaces/IMarket.sol\";\n\n/// @notice The type of the market\nenum LiquidationEngineType {\n    DLB_DCF_PRIORITY // DlbDcfPriorityLiquidationEngine\n}\n\n/// @notice Struct for the liquidation engine result\n/// @param seizedCollateralAssets The amount of collateral assets that were seized from the borrower\n/// excluding protocol fee but including liquidator fee\n/// @param repaidBorrowShares The amount of borrow shares that were repaid on borrower's position\n/// @param repaidBorrowAmount The amount of borrow amount that was repaid on borrower's position\n/// @param protocolSeizedCollateralFee The amount of protocol fee that should be deducted from the seized collateral\n/// and transferred to the fee collector\nstruct LiquidationEngineResult {\n    uint256 seizedCollateralAssets;\n    uint256 repaidBorrowShares;\n    uint256 repaidBorrowAmount;\n    uint256 protocolSeizedCollateralFee;\n}\n\n/// @notice Struct for the liquidation engine input\n/// @param borrower The address of the borrower\n/// @param liquidator The address of the liquidator\n/// @param totalSupply The total supply struct(assets, shares) of the market\n/// @param totalBorrowed The total borrowed amount struct(assets, shares) of the market\n/// @param position The position struct(supplyShares, borrowShares, collateralAssets) of the borrower\n/// @param maxLtv The maximum LTV for the market\n/// @param collateralPrice The price of the collateral token\n/// @param liquidationData The liquidation data\nstruct LiquidationEngineInput {\n    address borrower;\n    address liquidator;\n    Balance totalSupply;\n    Balance totalBorrowed;\n    Position position;\n    uint256 maxLtv;\n    uint256 collateralPrice;\n    bytes liquidationData;\n}\n\n/// @notice Interface for the liquidation engine\n/// @dev When implementing this contract, we need to take care of the following:\n/// - data provided to `calculateLiquidation` are post interest accrual\n/// - retrieving of any additional data not provided to `calculateLiquidation` should be handled by this contract\n/// - this contract handles liquidation eligibility check by itself (insolvency checks are handled by this contract)\n/// - if potential liqudation configuration is tied to market's parameters, this should be documented and if possible\n/// validated in this contract\n/// - this contract can have its own state variables and swapping this contract should be handled with care\n/// and proper migration plan should be implemented\n/// - this contract is market aware and allows only market contract to execute calculateLiquidation\ninterface IAltoLiquidationEngine {\n    /// @notice Emitted when the market is set\n    /// @param market The address of the market\n    event SetMarketOnce(address market);\n\n    /// @notice The type of the liquidation engine\n    /// @dev This is used to identify the type of the liquidation engine during indexing\n    function LIQUIDATION_ENGINE_TYPE() external view returns (LiquidationEngineType);\n\n    /// @notice The address of the market that this liquidation engine is tied to\n    function market() external view returns (address);\n\n    /// @notice Sets the market address to which this liquidation engine is tied to\n    /// @param _market The market to set\n    /// @dev Used for the first time by the market to set itself to the liquidation engine\n    function setMarketOnce(address _market) external;\n\n    /// @notice Calculates liquidation amounts and fees\n    /// @dev This function is only callable by the market contract\n    /// @param input The input data for the liquidation calculation\n    /// @return result The liquidation calculation result\n    function prepareLiquidation(LiquidationEngineInput memory input)\n        external\n        returns (LiquidationEngineResult memory result);\n\n    /// @notice Returns the minimum LLTV\n    /// @dev LLTV is the minimum LTV that a position has to reach to be allowed for liquidation\n    /// @dev Represents the earliest hypothetical LLTV at which the position could be liquidated, assuming the liquidation conditions defined by the engine are met.\n    ///      In case of dynamic LLTV this should be the lowest possible LLTV\n    /// @return minLltv The minimum LLTV\n    function minLltv() external view returns (uint256);\n\n    /// @notice Returns the protocol fee percentage\n    /// @dev protocol fee percentage applied to the liquidator's reward fee (percentage of sum of bonus fee and base fee).\n    ///      The precision is in MATH_PRECISION\n    function protocolFeePercentage() external view returns (uint256);\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Bytes.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/Bytes.sol)\n\npragma solidity ^0.8.24;\n\nimport {Math} from \"./math/Math.sol\";\n\n/**\n * @dev Bytes operations.\n */\nlibrary Bytes {\n    /**\n     * @dev Forward search for `s` in `buffer`\n     * * If `s` is present in the buffer, returns the index of the first instance\n     * * If `s` is not present in the buffer, returns type(uint256).max\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]\n     */\n    function indexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {\n        return indexOf(buffer, s, 0);\n    }\n\n    /**\n     * @dev Forward search for `s` in `buffer` starting at position `pos`\n     * * If `s` is present in the buffer (at or after `pos`), returns the index of the next instance\n     * * If `s` is not present in the buffer (at or after `pos`), returns type(uint256).max\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]\n     */\n    function indexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {\n        uint256 length = buffer.length;\n        for (uint256 i = pos; i < length; ++i) {\n            if (bytes1(_unsafeReadBytesOffset(buffer, i)) == s) {\n                return i;\n            }\n        }\n        return type(uint256).max;\n    }\n\n    /**\n     * @dev Backward search for `s` in `buffer`\n     * * If `s` is present in the buffer, returns the index of the last instance\n     * * If `s` is not present in the buffer, returns type(uint256).max\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]\n     */\n    function lastIndexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {\n        return lastIndexOf(buffer, s, type(uint256).max);\n    }\n\n    /**\n     * @dev Backward search for `s` in `buffer` starting at position `pos`\n     * * If `s` is present in the buffer (at or before `pos`), returns the index of the previous instance\n     * * If `s` is not present in the buffer (at or before `pos`), returns type(uint256).max\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]\n     */\n    function lastIndexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {\n        unchecked {\n            uint256 length = buffer.length;\n            for (uint256 i = Math.min(Math.saturatingAdd(pos, 1), length); i > 0; --i) {\n                if (bytes1(_unsafeReadBytesOffset(buffer, i - 1)) == s) {\n                    return i - 1;\n                }\n            }\n            return type(uint256).max;\n        }\n    }\n\n    /**\n     * @dev Copies the content of `buffer`, from `start` (included) to the end of `buffer` into a new bytes object in\n     * memory.\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]\n     */\n    function slice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {\n        return slice(buffer, start, buffer.length);\n    }\n\n    /**\n     * @dev Copies the content of `buffer`, from `start` (included) to `end` (excluded) into a new bytes object in\n     * memory.\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]\n     */\n    function slice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {\n        // sanitize\n        uint256 length = buffer.length;\n        end = Math.min(end, length);\n        start = Math.min(start, end);\n\n        // allocate and copy\n        bytes memory result = new bytes(end - start);\n        assembly (\"memory-safe\") {\n            mcopy(add(result, 0x20), add(add(buffer, 0x20), start), sub(end, start))\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Reads a bytes32 from a bytes array without bounds checking.\n     *\n     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the\n     * assembly block as such would prevent some optimizations.\n     */\n    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {\n        // This is not memory safe in the general case, but all calls to this private function are within bounds.\n        assembly (\"memory-safe\") {\n            value := mload(add(add(buffer, 0x20), offset))\n        }\n    }\n}\n"},{"file_path":"contracts/lending/libraries/Uint128Converter.sol","source_code":"// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Uint128Converter\n/// @author GPM\n/// @custom:contact security@altofoundation.org\n/// @notice Library for converting uint256 to uint128.\nlibrary Uint128Converter {\n    error MathUtilsMaxUint128Overflow();\n\n    /// @dev Converts a uint256 to a uint128, reverting if the value is greater than the maximum value of uint128.\n    /// @param x The value to convert.\n    /// @return The converted value.\n    function toUint128(uint256 x) internal pure returns (uint128) {\n        if (x > type(uint128).max) {\n            revert MathUtilsMaxUint128Overflow();\n        }\n\n        return uint128(x);\n    }\n}\n"},{"file_path":"contracts/lending/interfaces/IAltoConvexCreditLineMarket.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {BaseMarketInitParams, IMarket, IMarketStaticTypes} from \"./IMarket.sol\";\n\n/// @notice Struct that represents the parameters for initializing a credit market\nstruct CreditMarketInitParams {\n    /// @notice The parameters for initializing the base market.\n    BaseMarketInitParams baseMarketInitParams;\n    /// @notice The sole account permitted to own collateral and debt.\n    address creditAccount;\n    /// @notice The maximum credit capacity; used capacity is `totalBorrowed.assets + badDebtAssets`.\n    uint256 creditLimit;\n    /// @notice The LTV above which governance may foreclose.\n    uint256 foreclosureLtv;\n    /// @notice The initial borrow opening fee.\n    uint256 initialBorrowOpeningFee;\n}\n\n/// @notice Struct that represents the parameters for initializing a Convex credit line market\nstruct ConvexCreditLineInitParams {\n    /// @notice The credit market initialization parameters.\n    CreditMarketInitParams creditMarketInitParams;\n    /// @notice The address of the Convex Booster.\n    address convexBooster;\n    /// @notice The Convex pool identifier.\n    uint256 convexPoolId;\n    /// @notice The account that receives Convex rewards.\n    address rewardRecipient;\n    /// @notice The initial list of reward tokens to forward.\n    address[] rewardTokens;\n}\n\ninterface IAltoConvexCreditLineMarketErrors {\n    /// @notice Error thrown when a required address is the zero address\n    error AltoCreditMarketZeroAddress();\n\n    /// @notice Error thrown when the input is invalid\n    error AltoCreditMarketInvalidInput();\n\n    /// @notice Error thrown when an account is unauthorized\n    error AltoCreditMarketUnauthorizedAccount();\n\n    /// @notice Error thrown when changing a credit account that still has debt or collateral\n    error AltoCreditMarketPositionNotEmpty();\n\n    /// @notice Error thrown when callback data is provided\n    error AltoCreditMarketCallbacksUnsupported();\n\n    /// @notice Error thrown when the oracle returns a zero price\n    error AltoCreditMarketInvalidOraclePrice();\n\n    /// @notice Error thrown when a position is not eligible for foreclosure\n    error AltoCreditMarketPositionNotForeclosable();\n\n    /// @notice Error thrown when a standard market operation is unsupported\n    error AltoCreditMarketUnsupportedOperation();\n\n    /// @notice Error thrown when public liquidation is attempted\n    error AltoCreditMarketNonLiquidatable();\n\n    /// @notice Error thrown when the Convex strategy is inactive\n    error AltoConvexCreditLineStrategyInactive();\n\n    /// @notice Error thrown when a Convex call reports failure\n    error AltoConvexCreditLineExternalCallFailed();\n\n    /// @notice Error thrown when an emergency exit is attempted while the market is not paused\n    error AltoConvexCreditLineMustBePaused();\n}\n\ninterface IAltoConvexCreditLineMarketEvents {\n    /// @notice Emitted when the credit account is initialized or changed\n    /// @param oldCreditAccount The previous credit account, or zero during initialization\n    /// @param newCreditAccount The new credit account\n    event SetCreditAccount(address indexed oldCreditAccount, address indexed newCreditAccount);\n\n    /// @notice Emitted when the credit limit is set\n    /// @param oldCreditLimit The old credit limit\n    /// @param newCreditLimit The new credit limit\n    event SetCreditLimit(uint256 oldCreditLimit, uint256 newCreditLimit);\n\n    /// @notice Emitted when the foreclosure LTV is set\n    /// @param oldForeclosureLtv The old foreclosure LTV\n    /// @param newForeclosureLtv The new foreclosure LTV\n    event SetForeclosureLtv(uint256 oldForeclosureLtv, uint256 newForeclosureLtv);\n\n    /// @notice Emitted when the borrow opening fee is set\n    /// @param oldBorrowOpeningFee The old borrow opening fee\n    /// @param newBorrowOpeningFee The new borrow opening fee\n    event SetBorrowOpeningFee(uint256 oldBorrowOpeningFee, uint256 newBorrowOpeningFee);\n\n    /// @notice Emitted when interest and fees are claimed\n    /// @param recipient The account that received the borrow tokens\n    /// @param amount The amount of borrow tokens minted\n    event InterestClaimed(address indexed recipient, uint256 amount);\n\n    /// @notice Emitted when debt is written off during foreclosure\n    /// @param badDebtAmount The amount of bad debt accrued\n    event BadDebtAccrued(uint256 badDebtAmount);\n\n    /// @notice Emitted when recovered borrow tokens are burned to settle bad debt\n    /// @param settledAssets The amount of bad debt settled\n    event BadDebtSettled(uint256 settledAssets);\n\n    /// @notice Emitted when the Convex pool is configured\n    /// @param booster The address of the Convex Booster\n    /// @param poolId The Convex pool identifier\n    /// @param rewardPool The address of the Convex reward pool\n    /// @param depositToken The address of the Convex deposit token\n    /// @param rewardRecipient The account that receives Convex rewards\n    event ConvexConfigured(\n        address indexed booster,\n        uint256 indexed poolId,\n        address indexed rewardPool,\n        address depositToken,\n        address rewardRecipient\n    );\n\n    /// @notice Emitted when collateral is deposited and staked in Convex\n    /// @param caller The account that deposited the collateral\n    /// @param assets The amount of collateral deposited\n    event CollateralStaked(address indexed caller, uint256 assets);\n\n    /// @notice Emitted when collateral is unstaked and transferred\n    /// @param receiver The account that received the collateral\n    /// @param assets The amount of collateral withdrawn\n    event CollateralUnstaked(address indexed receiver, uint256 assets);\n\n    /// @notice Emitted for each reward token processed during a claim\n    /// @param caller The account that claimed the rewards\n    /// @param recipient The account that received the rewards\n    /// @param token The reward token processed\n    /// @param amount The amount of reward tokens transferred\n    event RewardsClaimed(address indexed caller, address indexed recipient, address indexed token, uint256 amount);\n\n    /// @notice Emitted when the reward recipient is set\n    /// @param oldRecipient The old reward recipient\n    /// @param newRecipient The new reward recipient\n    event SetRewardRecipient(address indexed oldRecipient, address indexed newRecipient);\n\n    /// @notice Emitted when a reward token is added\n    /// @param token The reward token added\n    event RewardTokenAdded(address indexed token);\n\n    /// @notice Emitted when a reward token is removed\n    /// @param token The reward token removed\n    event RewardTokenRemoved(address indexed token);\n\n    /// @notice Emitted when governance exits the Convex strategy\n    /// @param assets The reward-pool stake balance requested for withdrawal from Convex\n    event ConvexEmergencyExit(uint256 assets);\n}\n\n/// @dev This interface is used for factorizing IAltoConvexCreditLineMarketStaticTypes and\n/// IAltoConvexCreditLineMarket.\n/// @dev Consider using the IAltoConvexCreditLineMarket interface instead of this one.\ninterface IAltoConvexCreditLineMarketBase is IAltoConvexCreditLineMarketErrors, IAltoConvexCreditLineMarketEvents {\n    /// @notice The sole account permitted to own market collateral and debt\n    /// @return The configured credit-account address\n    function creditAccount() external view returns (address);\n\n    /// @notice The LTV above which governance may foreclose\n    /// @return The foreclosure LTV in `MATH_PRECISION`\n    function foreclosureLtv() external view returns (uint256);\n\n    /// @notice The opening fees and accrued interest available to claim\n    /// @return The claimable amount in borrow-token assets\n    function claimableFeesAssets() external view returns (uint128);\n\n    /// @notice The debt written off during foreclosures that has not been settled\n    /// @return The unsettled bad debt in borrow-token assets\n    function badDebtAssets() external view returns (uint256);\n\n    /// @notice Sets the credit account when the current account has no debt or collateral\n    /// @dev Only the owner may change the account. The reward recipient and account-specific authorizations\n    /// retain their configured values; the new credit account may update its reward recipient and authorizations.\n    /// @param newCreditAccount The nonzero account permitted to own market collateral and debt\n    function setCreditAccount(address newCreditAccount) external;\n\n    /// @notice Sets the maximum credit capacity; used capacity is `totalBorrowed.assets + badDebtAssets`\n    /// @dev Zero is allowed when active debt and bad debt are both zero after any interest accrual.\n    /// @param newCreditLimit The new credit limit\n    function setCreditLimit(uint256 newCreditLimit) external;\n\n    /// @notice Sets the LTV above which governance may foreclose\n    /// @param newForeclosureLtv The new foreclosure LTV\n    function setForeclosureLtv(uint256 newForeclosureLtv) external;\n\n    /// @notice Sets the borrow opening fee\n    /// @param newBorrowOpeningFee The new borrow opening fee\n    function setBorrowOpeningFee(uint256 newBorrowOpeningFee) external;\n\n    /// @notice Claims interest and fees for the fee recipient\n    /// @param interest The amount to claim, or zero to claim all\n    /// @return claimed The amount minted to the fee recipient\n    function claimInterest(uint256 interest) external returns (uint256 claimed);\n\n    /// @notice Burns recovered borrow tokens from the owner and reduces recorded bad debt\n    /// @dev Available while paused or frozen. The amount must be positive and cannot exceed bad debt, the owner's\n    /// token balance or DUSD's minted balance for this market. Unminted fees may need to be claimed before settlement.\n    /// @param assets The amount of bad debt to settle in borrow-token assets\n    function settleBadDebt(uint256 assets) external;\n\n    /// @notice The Convex Booster used to deposit collateral\n    function convexBooster() external view returns (address);\n\n    /// @notice The Convex pool identifier used by the market\n    function convexPoolId() external view returns (uint256);\n\n    /// @notice The Convex reward pool holding the market staked position\n    function convexRewardPool() external view returns (address);\n\n    /// @notice The account that receives claimed Convex rewards\n    function rewardRecipient() external view returns (address);\n\n    /// @notice Whether the Convex strategy is active for collateral deposits and withdrawals\n    /// @dev When false, new collateral additions revert, while removals and governance foreclosure transfer LP tokens\n    /// recovered into idle market custody by the emergency exit.\n    function convexActive() external view returns (bool);\n\n    /// @notice Returns a reward token by index\n    /// @param index The index of the reward token\n    function rewardToken(uint256 index) external view returns (address);\n\n    /// @notice Returns whether a token is configured as a reward token\n    /// @param token The token to query\n    function isRewardToken(address token) external view returns (bool);\n\n    /// @notice Claims and forwards every configured Convex reward token\n    /// @dev DUSD rewards are unsupported. Any DUSD received remains in the market and is not forwarded or swept.\n    /// @return claimedAmounts The amount forwarded for each configured reward token\n    function claimRewards() external returns (uint256[] memory claimedAmounts);\n\n    /// @notice Sets the account that receives future reward claims\n    /// @param newRecipient The new reward recipient\n    function setRewardRecipient(address newRecipient) external;\n\n    /// @notice Adds a token to the reward forwarding list\n    /// @dev The borrow token, DUSD, is intentionally excluded. This integration must not use DUSD reward incentives.\n    /// @param token The token to add\n    function addRewardToken(address token) external;\n\n    /// @notice Removes a token from the reward forwarding list\n    /// @param token The token to remove\n    function removeRewardToken(address token) external;\n\n    /// @notice Withdraws the reported Convex stake and permanently deactivates the strategy\n    /// @dev Once inactive, new collateral additions revert. After unpausing, collateral removals and governance\n    /// foreclosure transfer the recovered LP tokens directly from idle market custody.\n    /// @return assets The reward-pool stake balance requested for withdrawal\n    function emergencyExitConvex() external returns (uint256 assets);\n}\n\n/// @title Alto Convex Credit Line Market\n/// @author GPM\n/// @custom:contact security@altofoundation.org\n/// @notice Interface for a Curve-LP-backed credit line market staked through Convex\ninterface IAltoConvexCreditLineMarket is IMarket, IAltoConvexCreditLineMarketBase {\n    /// @notice Repays the credit account's debt\n    /// @dev Only the exact `creditAccount` may call this function and `onBehalf` must equal `creditAccount`.\n    /// Authorized delegates and unrelated accounts cannot repay.\n    /// @param assets The exact amount of borrow tokens to repay, or zero when repaying by shares\n    /// @param shares The exact amount of borrow shares to repay, or zero when repaying by assets\n    /// @param onBehalf The configured credit account\n    /// @return assets The amount of borrow tokens repaid\n    /// @return shares The amount of borrow shares repaid\n    function repay(uint256 assets, uint256 shares, address onBehalf) external override returns (uint256, uint256);\n\n    /// @notice Adds collateral to the credit account's position and deposits it into Convex\n    /// @dev Only the exact `creditAccount` may call this function and `onBehalf` must equal `creditAccount`.\n    /// Authorized delegates and unrelated accounts cannot add collateral.\n    /// @param assets The amount of collateral to add\n    /// @param onBehalf The configured credit account\n    /// @return assets The amount of collateral added\n    function addCollateral(uint256 assets, address onBehalf) external override returns (uint256);\n\n    /// @notice Sets a nonzero IRM for the market\n    /// @param irm The address of the new IRM implementing IIrm\n    /// @param skipAccrueInterest Whether to skip accrual with the current IRM before updating it\n    function setIrm(address irm, bool skipAccrueInterest) external override;\n\n    /// @notice Accrues interest into active debt and claimable fees\n    /// @dev The IRM receives the credit limit as total supply and active debt as total borrowed, excluding bad debt.\n    /// The credit limit stored in `totalSupply.assets` remains unchanged.\n    function accrueInterest() external override;\n}\n\n/// @dev This interface is inherited by the implementation so public struct getters are type checked.\n/// @dev Consider using the IAltoConvexCreditLineMarket interface instead of this one.\ninterface IAltoConvexCreditLineMarketStaticTypes is IMarketStaticTypes, IAltoConvexCreditLineMarketBase {}\n"},{"file_path":"contracts/utils/FixedPointMath.sol","source_code":"// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity ^0.8.0;\n\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\n\nuint256 constant MATH_PRECISION = 1e18;\n\n/// @title FixedPointMath\n/// @author GPM\n/// @custom:contact security@altofoundation.org\n/// @notice Library for fixed point arithmetic.\nlibrary FixedPointMath {\n    /// @dev Multiplies two numbers and divides by MATH_PRECISION, rounding down.\n    function multiplyWithPrecision(uint256 multiplicand, uint256 multiplier) internal pure returns (uint256) {\n        return (multiplicand * multiplier) / MATH_PRECISION;\n    }\n\n    /// @dev Multiplies two numbers and divides by MATH_PRECISION, rounding up.\n    function multiplyWithPrecisionUp(uint256 multiplicand, uint256 multiplier) internal pure returns (uint256) {\n        return Math.ceilDiv(multiplicand * multiplier, MATH_PRECISION);\n    }\n\n    /// @dev Divides a number by another using MATH_PRECISION, rounding up.\n    function divideWithPrecisionUp(uint256 numerator, uint256 denominator) internal pure returns (uint256) {\n        return Math.ceilDiv(numerator * MATH_PRECISION, denominator);\n    }\n\n    /// @dev Divides a number by another using MATH_PRECISION, rounding down.\n    function divideWithPrecisionDown(uint256 numerator, uint256 denominator) internal pure returns (uint256) {\n        return (numerator * MATH_PRECISION) / denominator;\n    }\n\n    /// @dev Multiplies numerator by multiplier and divides by denominator rounding division result up or down based on roundUp parameter.\n    /// @dev numerator * multiplier / denominator rounding division result.\n    function divideWithRounding(uint256 numerator, uint256 multiplier, uint256 denominator, bool roundUp)\n        internal\n        pure\n        returns (uint256)\n    {\n        if (roundUp) {\n            return Math.ceilDiv(numerator * multiplier, denominator);\n        }\n        return (numerator * multiplier) / denominator;\n    }\n\n    /// @dev Multiplies numerator by multiplier and divides by denominator rounding division result up or down based on half up rule.\n    /// @dev numerator * multiplier / denominator rounding division result.\n    function divideWithRoundingHalfUp(uint256 numerator, uint256 multiplier, uint256 denominator)\n        internal\n        pure\n        returns (uint256)\n    {\n        return (numerator * multiplier + denominator / 2) / denominator;\n    }\n\n    /// @dev Calculates compound interest using Taylor series approximation.\n    function calculateCompoundInterest(uint256 rate, uint256 periods) internal pure returns (uint256) {\n        uint256 linearTerm = rate * periods;\n        uint256 quadraticTerm = (linearTerm * linearTerm) / (2 * MATH_PRECISION);\n        uint256 cubicTerm = (quadraticTerm * linearTerm) / (3 * MATH_PRECISION);\n\n        uint256 result = linearTerm + quadraticTerm + cubicTerm;\n\n        // Add fourth term when rate * periods exceeds 0.2e18 for improved accuracy\n        if (linearTerm > 0.2e18) {\n            uint256 quarticTerm = (cubicTerm * linearTerm) / (4 * MATH_PRECISION);\n\n            // Check for overflow before adding the fourth term\n            if (result <= type(uint256).max - quarticTerm) {\n                result += quarticTerm;\n            }\n        }\n\n        // Cap the result to prevent downstream uint128 overflows in interest calculations\n        // Max safe value is approximately 1e20 to allow for reasonable multiplication with borrower amounts\n        uint256 maxSafeResult = 1e20;\n        if (result > maxSafeResult) {\n            result = maxSafeResult;\n        }\n\n        return result;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC-1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.\n *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n *     function _getImplementation() internal view returns (address) {\n *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n *     }\n *\n *     function _setImplementation(address newImplementation) internal {\n *         require(newImplementation.code.length > 0);\n *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n *     }\n * }\n * ```\n *\n * TIP: Consider using this library along with {SlotDerivation}.\n */\nlibrary StorageSlot {\n    struct AddressSlot {\n        address value;\n    }\n\n    struct BooleanSlot {\n        bool value;\n    }\n\n    struct Bytes32Slot {\n        bytes32 value;\n    }\n\n    struct Uint256Slot {\n        uint256 value;\n    }\n\n    struct Int256Slot {\n        int256 value;\n    }\n\n    struct StringSlot {\n        string value;\n    }\n\n    struct BytesSlot {\n        bytes value;\n    }\n\n    /**\n     * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n     */\n    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.\n     */\n    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.\n     */\n    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.\n     */\n    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Int256Slot` with member `value` located at `slot`.\n     */\n    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `StringSlot` with member `value` located at `slot`.\n     */\n    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n     */\n    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := store.slot\n        }\n    }\n\n    /**\n     * @dev Returns a `BytesSlot` with member `value` located at `slot`.\n     */\n    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n     */\n    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := store.slot\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC7913.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC7913.sol)\n\npragma solidity >=0.5.0;\n\n/**\n * @dev Signature verifier interface.\n */\ninterface IERC7913SignatureVerifier {\n    /**\n     * @dev Verifies `signature` as a valid signature of `hash` by `key`.\n     *\n     * MUST return the bytes4 magic value IERC7913SignatureVerifier.verify.selector if the signature is valid.\n     * SHOULD return 0xffffffff or revert if the signature is not valid.\n     * SHOULD return 0xffffffff or revert if the key is empty\n     */\n    function verify(bytes calldata key, bytes32 hash, bytes calldata signature) external view returns (bytes4);\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Address.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\nimport {Errors} from \"./Errors.sol\";\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev There's no code at `target` (it is not a contract).\n     */\n    error AddressEmptyCode(address target);\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        if (address(this).balance < amount) {\n            revert Errors.InsufficientBalance(address(this).balance, amount);\n        }\n\n        (bool success, bytes memory returndata) = recipient.call{value: amount}(\"\");\n        if (!success) {\n            _revert(returndata);\n        }\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason or custom error, it is bubbled\n     * up by this function (like regular Solidity function calls). However, if\n     * the call reverted with no returned reason, this function reverts with a\n     * {Errors.FailedCall} error.\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        if (address(this).balance < value) {\n            revert Errors.InsufficientBalance(address(this).balance, value);\n        }\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case\n     * of an unsuccessful call.\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata\n    ) internal view returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            // only check if target is a contract if the call was successful and the return data is empty\n            // otherwise we already know that it was a contract\n            if (returndata.length == 0 && target.code.length == 0) {\n                revert AddressEmptyCode(target);\n            }\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n     * revert reason or with a default {Errors.FailedCall} error.\n     */\n    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.\n     */\n    function _revert(bytes memory returndata) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            assembly (\"memory-safe\") {\n                revert(add(returndata, 0x20), mload(returndata))\n            }\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n}\n"},{"file_path":"contracts/lending/interfaces/vendor/IConvexRewardPool.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Convex Base Reward Pool Interface\n/// @notice Minimal Ethereum Convex BaseRewardPool surface used by the credit line.\ninterface IConvexRewardPool {\n    /// @notice Returns the Convex pool identifier\n    function pid() external view returns (uint256);\n\n    /// @notice Returns the pool operator\n    function operator() external view returns (address);\n\n    /// @notice Returns the staking token\n    function stakingToken() external view returns (address);\n\n    /// @notice Returns the primary reward token\n    function rewardToken() external view returns (address);\n\n    /// @notice Returns the staked balance of an account\n    function balanceOf(address account) external view returns (uint256);\n\n    /// @notice Withdraws and unwraps staked LP tokens\n    function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool);\n\n    /// @notice Claims rewards for an account\n    function getReward(address account, bool claimExtras) external returns (bool);\n}\n"},{"file_path":"contracts/lending/interfaces/IMarketCallbacks.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IBorrowCallback {\n    /// @notice Callback function for borrowing\n    /// @param assets the amount of assets to borrow - \"in\" amount for the swap\n    /// @param onBehalf the address of the user whose position is being borrowed\n    /// @param swapParams ABI-encoded swap parameter (see `SwapParams` struct for details)\n    /// @dev Called during market's `borrow`\n    function onBorrowCallback(uint256 assets, address onBehalf, bytes calldata swapParams) external;\n}\n\ninterface IRemoveCollateralCallback {\n    /// @notice Callback function for removing collateral\n    /// @param assets the amount of assets to remove - \"in\" amount for the swap\n    /// @param onBehalf the address of the user whose collateral is being removed\n    /// @param swapParams ABI-encoded swap parameter (see `SwapParams` struct for details)\n    /// @dev Called during market's `removeCollateral`\n    function onRemoveCollateralCallback(uint256 assets, address onBehalf, bytes calldata swapParams) external;\n}\n\n/// @notice Callback interface for liquidator to call during liquidation\ninterface ILiquidateCallback {\n    /// @notice Callback function for liquidator to call during liquidation\n    /// @param assetsToRepay The amount of token to be repaid by the callback receiver, this will be amount of borrow token of market\n    /// @dev The callback receiver needs to give approval of assetsToRepay of borrow token of market to the market\n    /// @param collateralReceived The amount of collateral received by the liquidator receiving the callback\n    /// @dev The callback receiver needs to give approval of collateralReceived of collateral token of market to the market\n    /// @param data Additional data for the liquidation\n    function onLiquidateCallback(uint256 assetsToRepay, uint256 collateralReceived, bytes calldata data) external;\n}\n"},{"file_path":"contracts/utils/AltoOwnable2StepUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nimport {OwnableUpgradeable} from \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport {Initializable} from \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\n/**\n * @title Alto Ownable 2 Step\n * @author GPM\n * @custom:contact security@altofoundation.org\n * @notice This contract extends Ownable2StepUpgradeable contract from OpenZeppelin, with a way to bypass the 2 steps ownership transfer.\n */\nabstract contract AltoOwnable2StepUpgradeable is Initializable, OwnableUpgradeable {\n    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable2Step\n    struct Ownable2StepStorage {\n        address _pendingOwner;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Ownable2Step\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant Ownable2StepStorageLocation =\n        0x237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00;\n\n    function _getOwnable2StepStorage() private pure returns (Ownable2StepStorage storage $) {\n        assembly {\n            $.slot := Ownable2StepStorageLocation\n        }\n    }\n\n    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);\n\n    function __Ownable2Step_init() internal onlyInitializing {}\n\n    function __Ownable2Step_init_unchained() internal onlyInitializing {}\n\n    /**\n     * @dev Returns the address of the pending owner.\n     */\n    function pendingOwner() public view virtual returns (address) {\n        Ownable2StepStorage storage $ = _getOwnable2StepStorage();\n        return $._pendingOwner;\n    }\n\n    /**\n     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\n     * Can only be called by the current owner.\n     *\n     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.\n     */\n    function transferOwnership(address newOwner) public virtual override onlyOwner {\n        Ownable2StepStorage storage $ = _getOwnable2StepStorage();\n        $._pendingOwner = newOwner;\n        emit OwnershipTransferStarted(owner(), newOwner);\n    }\n\n    /// @notice This function is used to transfer ownership of the contract to a new account without the 2 steps ownership transfer.\n    /// @param newOwner The address of the new owner.\n    /// @dev This is useful in deployment scripts and should be used with caution.\n    function transferOwnershipSkip2Step(address newOwner) public virtual onlyOwner {\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual override {\n        Ownable2StepStorage storage $ = _getOwnable2StepStorage();\n        delete $._pendingOwner;\n        super._transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev The new owner accepts the ownership transfer.\n     */\n    function acceptOwnership() public virtual {\n        address sender = _msgSender();\n        if (pendingOwner() != sender) {\n            revert OwnableUnauthorizedAccount(sender);\n        }\n        _transferOwnership(sender);\n    }\n}\n"},{"file_path":"contracts/lending/interfaces/IMintableERC20.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.22;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/// @title IMintableERC20\n/// @author GPM\n/// @custom:contact security@altofoundation.org\n/// @notice Interface for mintable ERC20 tokens.\n/// @dev This is used as a borrow token in the AltoMintMarket contract.\ninterface IMintableERC20 is IERC20 {\n    /// @notice Mints tokens to an address.\n    /// @param to The address to mint tokens to.\n    /// @param amount The amount of tokens to mint.\n    function mint(address to, uint256 amount) external;\n\n    /// @notice Burns tokens from an address.\n    /// @param from The address to burn tokens from.\n    /// @param amount The amount of tokens to burn.\n    function burn(address from, uint256 amount) external;\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Storage of the initializable contract.\n     *\n     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions\n     * when using with upgradeable contracts.\n     *\n     * @custom:storage-location erc7201:openzeppelin.storage.Initializable\n     */\n    struct InitializableStorage {\n        /**\n         * @dev Indicates that the contract has been initialized.\n         */\n        uint64 _initialized;\n        /**\n         * @dev Indicates that the contract is in the process of being initialized.\n         */\n        bool _initializing;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Initializable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;\n\n    /**\n     * @dev The contract is already initialized.\n     */\n    error InvalidInitialization();\n\n    /**\n     * @dev The contract is not initializing.\n     */\n    error NotInitializing();\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint64 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts.\n     *\n     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any\n     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in\n     * production.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        // Cache values to avoid duplicated sloads\n        bool isTopLevelCall = !$._initializing;\n        uint64 initialized = $._initialized;\n\n        // Allowed calls:\n        // - initialSetup: the contract is not in the initializing state and no previous version was\n        //                 initialized\n        // - construction: the contract is initialized at version 1 (no reinitialization) and the\n        //                 current contract is just being deployed\n        bool initialSetup = initialized == 0 && isTopLevelCall;\n        bool construction = initialized == 1 && address(this).code.length == 0;\n\n        if (!initialSetup && !construction) {\n            revert InvalidInitialization();\n        }\n        $._initialized = 1;\n        if (isTopLevelCall) {\n            $._initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            $._initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n     * are added through upgrades and that require initialization.\n     *\n     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n     * cannot be nested. If one is invoked in the context of another, execution will revert.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     *\n     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint64 version) {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing || $._initialized >= version) {\n            revert InvalidInitialization();\n        }\n        $._initialized = version;\n        $._initializing = true;\n        _;\n        $._initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        _checkInitializing();\n        _;\n    }\n\n    /**\n     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.\n     */\n    function _checkInitializing() internal view virtual {\n        if (!_isInitializing()) {\n            revert NotInitializing();\n        }\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     *\n     * Emits an {Initialized} event the first time it is successfully executed.\n     */\n    function _disableInitializers() internal virtual {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing) {\n            revert InvalidInitialization();\n        }\n        if ($._initialized != type(uint64).max) {\n            $._initialized = type(uint64).max;\n            emit Initialized(type(uint64).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint64) {\n        return _getInitializableStorage()._initialized;\n    }\n\n    /**\n     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _getInitializableStorage()._initializing;\n    }\n\n    /**\n     * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.\n     *\n     * NOTE: Consider following the ERC-7201 formula to derive storage locations.\n     */\n    function _initializableStorageSlot() internal pure virtual returns (bytes32) {\n        return INITIALIZABLE_STORAGE;\n    }\n\n    /**\n     * @dev Returns a pointer to the storage namespace.\n     */\n    // solhint-disable-next-line var-name-mixedcase\n    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {\n        bytes32 slot = _initializableStorageSlot();\n        assembly {\n            $.slot := slot\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC5267.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC5267.sol)\n\npragma solidity >=0.4.16;\n\ninterface IERC5267 {\n    /**\n     * @dev MAY be emitted to signal that the domain could have changed.\n     */\n    event EIP712DomainChanged();\n\n    /**\n     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712\n     * signature.\n     */\n    function eip712Domain()\n        external\n        view\n        returns (\n            bytes1 fields,\n            string memory name,\n            string memory version,\n            uint256 chainId,\n            address verifyingContract,\n            bytes32 salt,\n            uint256[] memory extensions\n        );\n}\n"}],"certified":false,"conflicting_implementations":null,"abi":[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[],"name":"AltoBaseMarketBorrowingTooMuch","type":"error"},{"inputs":[],"name":"AltoBaseMarketInsufficientMarketLiquidity","type":"error"},{"inputs":[],"name":"AltoBaseMarketInsufficientUserCollateral","type":"error"},{"inputs":[],"name":"AltoBaseMarketInvalidInput","type":"error"},{"inputs":[],"name":"AltoBaseMarketUnauthorized","type":"error"},{"inputs":[],"name":"AltoConvexCreditLineExternalCallFailed","type":"error"},{"inputs":[],"name":"AltoConvexCreditLineMustBePaused","type":"error"},{"inputs":[],"name":"AltoConvexCreditLineStrategyInactive","type":"error"},{"inputs":[],"name":"AltoCreditMarketCallbacksUnsupported","type":"error"},{"inputs":[],"name":"AltoCreditMarketInvalidInput","type":"error"},{"inputs":[],"name":"AltoCreditMarketInvalidOraclePrice","type":"error"},{"inputs":[],"name":"AltoCreditMarketNonLiquidatable","type":"error"},{"inputs":[],"name":"AltoCreditMarketPositionNotEmpty","type":"error"},{"inputs":[],"name":"AltoCreditMarketPositionNotForeclosable","type":"error"},{"inputs":[],"name":"AltoCreditMarketUnauthorizedAccount","type":"error"},{"inputs":[],"name":"AltoCreditMarketUnsupportedOperation","type":"error"},{"inputs":[],"name":"AltoCreditMarketZeroAddress","type":"error"},{"inputs":[],"name":"AuthAuthorizationAlreadySet","type":"error"},{"inputs":[],"name":"AuthInvalidNonce","type":"error"},{"inputs":[],"name":"AuthInvalidSignature","type":"error"},{"inputs":[],"name":"AuthSignatureExpired","type":"error"},{"inputs":[{"internalType":"address","name":"implementation","type":"address"}],"name":"ERC1967InvalidImplementation","type":"error"},{"inputs":[],"name":"ERC1967NonPayable","type":"error"},{"inputs":[],"name":"FailedCall","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[{"internalType":"bytes32","name":"pauseType","type":"bytes32"}],"name":"IsPaused","type":"error"},{"inputs":[],"name":"MathUtilsMaxUint128Overflow","type":"error"},{"inputs":[],"name":"NotInitializing","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":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[{"internalType":"bytes32","name":"pauseType","type":"bytes32"},{"internalType":"bool","name":"currentState","type":"bool"},{"internalType":"bool","name":"newState","type":"bool"}],"name":"StateNotChanged","type":"error"},{"inputs":[],"name":"UUPSUnauthorizedCallContext","type":"error"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"UUPSUnsupportedProxiableUUID","type":"error"},{"inputs":[{"internalType":"address","name":"pauser","type":"address"},{"internalType":"bytes32","name":"pauseType","type":"bytes32"}],"name":"Unauthorized","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"borrowRate","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"interest","type":"uint256"},{"indexed":false,"internalType":"uint128","name":"totalBorrowAssets","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"totalSupplyAssets","type":"uint128"}],"name":"AccrueInterest","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"onBehalf","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"AddCollateral","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"onBehalf","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"AddSupply","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"badDebtAmount","type":"uint256"}],"name":"BadDebtAccrued","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"settledAssets","type":"uint256"}],"name":"BadDebtSettled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"onBehalf","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"feeAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"feeSupplyShares","type":"uint256"}],"name":"Borrow","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"}],"name":"CollateralStaked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"}],"name":"CollateralUnstaked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"booster","type":"address"},{"indexed":true,"internalType":"uint256","name":"poolId","type":"uint256"},{"indexed":true,"internalType":"address","name":"rewardPool","type":"address"},{"indexed":false,"internalType":"address","name":"depositToken","type":"address"},{"indexed":false,"internalType":"address","name":"rewardRecipient","type":"address"}],"name":"ConvexConfigured","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"}],"name":"ConvexEmergencyExit","type":"event"},{"anonymous":false,"inputs":[],"name":"EIP712DomainChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"address","name":"liquidator","type":"address"},{"indexed":false,"internalType":"uint256","name":"liquidatedCollateral","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"badDebtClearedAssets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"badDebtClearedShares","type":"uint256"}],"name":"GovernanceLiquidation","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"nonce","type":"uint256"}],"name":"IncrementNonce","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"InterestClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"address","name":"liquidator","type":"address"},{"indexed":false,"internalType":"uint256","name":"liquidatedCollateral","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"protocolFee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"repaidBorrow","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"repaidBorrowShares","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"badDebtClearedAssets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"badDebtClearedShares","type":"uint256"}],"name":"Liquidation","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pauser","type":"address"},{"indexed":false,"internalType":"bytes32","name":"pauseType","type":"bytes32"},{"indexed":false,"internalType":"bool","name":"paused","type":"bool"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pauser","type":"address"},{"indexed":false,"internalType":"bytes32","name":"pauseType","type":"bytes32"},{"indexed":false,"internalType":"bool","name":"status","type":"bool"}],"name":"PauserUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"onBehalf","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"RemoveCollateral","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"onBehalf","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"RemoveSupply","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"onBehalf","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Repay","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"}],"name":"RewardTokenAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"}],"name":"RewardTokenRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"RewardsClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"bool","name":"isAuthorized","type":"bool"}],"name":"SetAuthorization","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"callback","type":"address"},{"indexed":false,"internalType":"bool","name":"isAuthorized","type":"bool"}],"name":"SetAuthorizedCallback","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"periphery","type":"address"},{"indexed":false,"internalType":"bool","name":"isAuthorized","type":"bool"}],"name":"SetAuthorizedLiquidationPeriphery","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldBorrowOpeningFee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newBorrowOpeningFee","type":"uint256"}],"name":"SetBorrowOpeningFee","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldCreditAccount","type":"address"},{"indexed":true,"internalType":"address","name":"newCreditAccount","type":"address"}],"name":"SetCreditAccount","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldCreditLimit","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newCreditLimit","type":"uint256"}],"name":"SetCreditLimit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldAddr","type":"address"},{"indexed":true,"internalType":"address","name":"newAddr","type":"address"}],"name":"SetFeeRecipient","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldForeclosureLtv","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newForeclosureLtv","type":"uint256"}],"name":"SetForeclosureLtv","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldAddr","type":"address"},{"indexed":true,"internalType":"address","name":"newAddr","type":"address"}],"name":"SetIrm","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldLiquidationEngine","type":"address"},{"indexed":true,"internalType":"address","name":"newLiquidationEngine","type":"address"}],"name":"SetLiquidationEngine","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldMaxLtv","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newMaxLtv","type":"uint256"}],"name":"SetMaxLtv","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldAddr","type":"address"},{"indexed":true,"internalType":"address","name":"newAddr","type":"address"}],"name":"SetOracle","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldRecipient","type":"address"},{"indexed":true,"internalType":"address","name":"newRecipient","type":"address"}],"name":"SetRewardRecipient","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"inputs":[],"name":"MARKET_TYPE","outputs":[{"internalType":"enum MarketType","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UPGRADE_INTERFACE_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"accrueInterest","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"onBehalf","type":"address"}],"name":"addCollateral","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"addRewardToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"onBehalf","type":"address"}],"name":"addSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"authorizedCallbacks","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"authorizedLiquidationPeriphery","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"badDebtAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"onBehalf","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"bytes","name":"swapParams","type":"bytes"}],"name":"borrow","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"borrowOpeningFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"borrowToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"interest","type":"uint256"}],"name":"claimInterest","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimRewards","outputs":[{"internalType":"uint256[]","name":"claimedAmounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimableFeesAssets","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collateralToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"convexActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"convexBooster","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"convexPoolId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"convexRewardPool","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"creditAccount","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"eip712Domain","outputs":[{"internalType":"bytes1","name":"fields","type":"bytes1"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"version","type":"string"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"verifyingContract","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256[]","name":"extensions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"emergencyExitConvex","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"feeRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"foreclosureLtv","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"borrower","type":"address"},{"internalType":"bool","name":"skipAccrueInterest","type":"bool"}],"name":"governanceLiquidate","outputs":[{"internalType":"uint256","name":"collateralAmount","type":"uint256"},{"internalType":"uint256","name":"badDebtAmount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"components":[{"components":[{"internalType":"address","name":"borrowToken","type":"address"},{"internalType":"address","name":"collateralToken","type":"address"},{"internalType":"address","name":"irm","type":"address"},{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"emergencyAdmin","type":"address"},{"internalType":"address","name":"oracle","type":"address"},{"internalType":"uint256","name":"maxLtv","type":"uint256"},{"internalType":"address","name":"feeRecipient","type":"address"},{"internalType":"address","name":"liquidationEngine","type":"address"}],"internalType":"struct BaseMarketInitParams","name":"baseMarketInitParams","type":"tuple"},{"internalType":"address","name":"creditAccount","type":"address"},{"internalType":"uint256","name":"creditLimit","type":"uint256"},{"internalType":"uint256","name":"foreclosureLtv","type":"uint256"},{"internalType":"uint256","name":"initialBorrowOpeningFee","type":"uint256"}],"internalType":"struct CreditMarketInitParams","name":"creditMarketInitParams","type":"tuple"},{"internalType":"address","name":"convexBooster","type":"address"},{"internalType":"uint256","name":"convexPoolId","type":"uint256"},{"internalType":"address","name":"rewardRecipient","type":"address"},{"internalType":"address[]","name":"rewardTokens","type":"address[]"}],"internalType":"struct ConvexCreditLineInitParams","name":"_initParams","type":"tuple"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"irm","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"isAuthorized","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"isRewardToken","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"borrower","type":"address"},{"internalType":"bytes","name":"callbackData","type":"bytes"},{"internalType":"bytes","name":"liquidationData","type":"bytes"}],"name":"liquidate","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"liquidationEngine","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxLtv","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonce","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"oracle","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"pauseType","type":"bytes32"},{"internalType":"bool","name":"_paused","type":"bool"}],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"pausers","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"position","outputs":[{"internalType":"uint128","name":"supplyShares","type":"uint128"},{"internalType":"uint128","name":"borrowShares","type":"uint128"},{"internalType":"uint128","name":"collateralAssets","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"onBehalf","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"bytes","name":"swapParams","type":"bytes"}],"name":"removeCollateral","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"removeRewardToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"onBehalf","type":"address"},{"internalType":"address","name":"receiver","type":"address"}],"name":"removeSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"onBehalf","type":"address"}],"name":"repay","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rewardRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"rewardToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"bool","name":"isAuthorizedStatus","type":"bool"}],"name":"setAuthorization","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"bool","name":"isAuthorizedStatus","type":"bool"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct Authorization","name":"authData","type":"tuple"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"sigData","type":"tuple"}],"name":"setAuthorizationWithSignature","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"callback","type":"address"},{"internalType":"bool","name":"value","type":"bool"}],"name":"setAuthorizedCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"periphery","type":"address"},{"internalType":"bool","name":"value","type":"bool"}],"name":"setAuthorizedLiquidationPeriphery","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newBorrowOpeningFee","type":"uint256"}],"name":"setBorrowOpeningFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newCreditAccount","type":"address"}],"name":"setCreditAccount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newCreditLimit","type":"uint256"}],"name":"setCreditLimit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_feeRecipient","type":"address"}],"name":"setFeeRecipient","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newForeclosureLtv","type":"uint256"}],"name":"setForeclosureLtv","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_irm","type":"address"},{"internalType":"bool","name":"_skipAccrueInterest","type":"bool"}],"name":"setIrm","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_liquidationEngine","type":"address"}],"name":"setLiquidationEngine","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxLtv","type":"uint256"}],"name":"setMaxLtv","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_oracle","type":"address"}],"name":"setOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"pauser","type":"address"},{"internalType":"bytes32","name":"pauseType","type":"bytes32"},{"internalType":"bool","name":"status","type":"bool"}],"name":"setPauser","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newRecipient","type":"address"}],"name":"setRewardRecipient","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"settleBadDebt","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"totalBorrowed","outputs":[{"internalType":"uint128","name":"assets","type":"uint128"},{"internalType":"uint128","name":"shares","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint128","name":"assets","type":"uint128"},{"internalType":"uint128","name":"shares","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnershipSkip2Step","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"}],"is_changed_bytecode":false,"is_partially_verified":true,"constructor_args":null}