ETH Price: $3,802.52 (+1.76%)
Gas: 11 Gwei

Contract

0xce23E457fb01454B8C59E31F4f72E4bd3d29b5EB
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Value

There are no matching entries

Please try again later

Latest 1 internal transaction

Advanced mode:
Parent Transaction Hash Block From To Value
161981852022-12-16 15:34:59524 days ago1671204899  Contract Creation0 ETH
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
Lens

Compiler Version
v0.8.13+commit.abaa5c0e

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion
File 1 of 29 : Lens.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity 0.8.13;

import "./MarketsLens.sol";

/// @title Lens.
/// @author Morpho Labs.
/// @custom:contact [email protected]
/// @notice This contract exposes an API to query on-chain data related to the Morpho Protocol, its markets and its users.
contract Lens is MarketsLens {
    using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
    using WadRayMath for uint256;

    /// CONSTRUCTOR ///

    /// @notice Constructs the contract.
    /// @param _morpho The address of the main Morpho contract.
    constructor(address _morpho) LensStorage(_morpho) {}

    /// EXTERNAL ///

    /// @notice Computes and returns the total distribution of supply through Morpho, using virtually updated indexes.
    /// @return p2pSupplyAmount The total supplied amount matched peer-to-peer, subtracting the supply delta (in ETH).
    /// @return poolSupplyAmount The total supplied amount on the underlying pool, adding the supply delta (in ETH).
    /// @return totalSupplyAmount The total amount supplied through Morpho (in ETH).
    function getTotalSupply()
        external
        view
        returns (
            uint256 p2pSupplyAmount,
            uint256 poolSupplyAmount,
            uint256 totalSupplyAmount
        )
    {
        address[] memory markets = morpho.getMarketsCreated();
        IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());

        uint256 nbMarkets = markets.length;
        for (uint256 i; i < nbMarkets; ) {
            address _poolToken = markets[i];

            (
                address underlyingToken,
                uint256 marketP2PSupplyAmount,
                uint256 marketPoolSupplyAmount
            ) = _getTotalMarketSupply(_poolToken);

            uint256 underlyingPrice = oracle.getAssetPrice(underlyingToken);
            (, , , uint256 reserveDecimals, ) = pool
            .getConfiguration(underlyingToken)
            .getParamsMemory();

            uint256 tokenUnit = 10**reserveDecimals;
            p2pSupplyAmount += (marketP2PSupplyAmount * underlyingPrice) / tokenUnit;
            poolSupplyAmount += (marketPoolSupplyAmount * underlyingPrice) / tokenUnit;

            unchecked {
                ++i;
            }
        }

        totalSupplyAmount = p2pSupplyAmount + poolSupplyAmount;
    }

    /// @notice Computes and returns the total distribution of borrows through Morpho, using virtually updated indexes.
    /// @return p2pBorrowAmount The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in ETH).
    /// @return poolBorrowAmount The total borrowed amount on the underlying pool, adding the borrow delta (in ETH).
    /// @return totalBorrowAmount The total amount borrowed through Morpho (in ETH).
    function getTotalBorrow()
        external
        view
        returns (
            uint256 p2pBorrowAmount,
            uint256 poolBorrowAmount,
            uint256 totalBorrowAmount
        )
    {
        address[] memory markets = morpho.getMarketsCreated();
        IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());

        uint256 nbMarkets = markets.length;
        for (uint256 i; i < nbMarkets; ) {
            address _poolToken = markets[i];

            (
                address underlyingToken,
                uint256 marketP2PBorrowAmount,
                uint256 marketPoolBorrowAmount
            ) = _getTotalMarketBorrow(_poolToken);

            uint256 underlyingPrice = oracle.getAssetPrice(underlyingToken);
            (, , , uint256 reserveDecimals, ) = pool
            .getConfiguration(underlyingToken)
            .getParamsMemory();

            uint256 tokenUnit = 10**reserveDecimals;
            p2pBorrowAmount += (marketP2PBorrowAmount * underlyingPrice) / tokenUnit;
            poolBorrowAmount += (marketPoolBorrowAmount * underlyingPrice) / tokenUnit;

            unchecked {
                ++i;
            }
        }

        totalBorrowAmount = p2pBorrowAmount + poolBorrowAmount;
    }
}

File 2 of 29 : Math.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity ^0.8.0;

library Math {
    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := xor(x, mul(xor(x, y), lt(y, x)))
        }
    }

    function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := xor(x, mul(xor(x, y), gt(y, x)))
        }
    }

    /// @dev Returns max(x - y, 0).
    function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            z := mul(gt(x, y), sub(x, y))
        }
    }

    /// @dev Returns x / y rounded up (x / y + boolAsInt(x % y > 0)).
    function divUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            // Revert if y = 0
            if iszero(y) {
                revert(0, 0)
            }

            z := add(gt(mod(x, y), 0), div(x, y))
        }
    }
}

File 3 of 29 : PercentageMath.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity ^0.8.0;

/// @title PercentageMath.
/// @author Morpho Labs.
/// @custom:contact [email protected]
/// @notice Optimized version of Aave V3 math library PercentageMath to conduct percentage manipulations: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/libraries/math/PercentageMath.sol
library PercentageMath {
    ///	CONSTANTS ///

    uint256 internal constant PERCENTAGE_FACTOR = 1e4; // 100.00%
    uint256 internal constant HALF_PERCENTAGE_FACTOR = 0.5e4; // 50.00%
    uint256 internal constant MAX_UINT256 = 2**256 - 1;
    uint256 internal constant MAX_UINT256_MINUS_HALF_PERCENTAGE = 2**256 - 1 - 0.5e4;

    /// INTERNAL ///

    /// @notice Executes a percentage addition (x * (1 + p)), rounded up.
    /// @param x The value to which to add the percentage.
    /// @param percentage The percentage of the value to add.
    /// @return y The result of the addition.
    function percentAdd(uint256 x, uint256 percentage) internal pure returns (uint256 y) {
        // Must revert if
        // PERCENTAGE_FACTOR + percentage > type(uint256).max
        //     or x * (PERCENTAGE_FACTOR + percentage) + HALF_PERCENTAGE_FACTOR > type(uint256).max
        // <=> percentage > type(uint256).max - PERCENTAGE_FACTOR
        //     or x > (type(uint256).max - HALF_PERCENTAGE_FACTOR) / (PERCENTAGE_FACTOR + percentage)
        // Note: PERCENTAGE_FACTOR + percentage >= PERCENTAGE_FACTOR > 0
        assembly {
            y := add(PERCENTAGE_FACTOR, percentage) // Temporary assignment to save gas.

            if or(
                gt(percentage, sub(MAX_UINT256, PERCENTAGE_FACTOR)),
                gt(x, div(MAX_UINT256_MINUS_HALF_PERCENTAGE, y))
            ) {
                revert(0, 0)
            }

            y := div(add(mul(x, y), HALF_PERCENTAGE_FACTOR), PERCENTAGE_FACTOR)
        }
    }

    /// @notice Executes a percentage subtraction (x * (1 - p)), rounded up.
    /// @param x The value to which to subtract the percentage.
    /// @param percentage The percentage of the value to subtract.
    /// @return y The result of the subtraction.
    function percentSub(uint256 x, uint256 percentage) internal pure returns (uint256 y) {
        // Must revert if
        // percentage > PERCENTAGE_FACTOR
        //     or x * (PERCENTAGE_FACTOR - percentage) + HALF_PERCENTAGE_FACTOR > type(uint256).max
        // <=> percentage > PERCENTAGE_FACTOR
        //     or ((PERCENTAGE_FACTOR - percentage) > 0 and x > (type(uint256).max - HALF_PERCENTAGE_FACTOR) / (PERCENTAGE_FACTOR - percentage))
        assembly {
            y := sub(PERCENTAGE_FACTOR, percentage) // Temporary assignment to save gas.

            if or(gt(percentage, PERCENTAGE_FACTOR), mul(y, gt(x, div(MAX_UINT256_MINUS_HALF_PERCENTAGE, y)))) {
                revert(0, 0)
            }

            y := div(add(mul(x, y), HALF_PERCENTAGE_FACTOR), PERCENTAGE_FACTOR)
        }
    }

    /// @notice Executes a percentage multiplication (x * p), rounded up.
    /// @param x The value to multiply by the percentage.
    /// @param percentage The percentage of the value to multiply.
    /// @return y The result of the multiplication.
    function percentMul(uint256 x, uint256 percentage) internal pure returns (uint256 y) {
        // Must revert if
        // x * percentage + HALF_PERCENTAGE_FACTOR > type(uint256).max
        // <=> percentage > 0 and x > (type(uint256).max - HALF_PERCENTAGE_FACTOR) / percentage
        assembly {
            if mul(percentage, gt(x, div(MAX_UINT256_MINUS_HALF_PERCENTAGE, percentage))) {
                revert(0, 0)
            }

            y := div(add(mul(x, percentage), HALF_PERCENTAGE_FACTOR), PERCENTAGE_FACTOR)
        }
    }

    /// @notice Executes a percentage division (x / p), rounded up.
    /// @param x The value to divide by the percentage.
    /// @param percentage The percentage of the value to divide.
    /// @return y The result of the division.
    function percentDiv(uint256 x, uint256 percentage) internal pure returns (uint256 y) {
        // Must revert if
        // percentage == 0
        //     or x * PERCENTAGE_FACTOR + percentage / 2 > type(uint256).max
        // <=> percentage == 0
        //     or x > (type(uint256).max - percentage / 2) / PERCENTAGE_FACTOR
        assembly {
            y := div(percentage, 2) // Temporary assignment to save gas.

            if iszero(mul(percentage, iszero(gt(x, div(sub(MAX_UINT256, y), PERCENTAGE_FACTOR))))) {
                revert(0, 0)
            }

            y := div(add(mul(PERCENTAGE_FACTOR, x), y), percentage)
        }
    }

    /// @notice Executes a weighted average (x * (1 - p) + y * p), rounded up.
    /// @param x The first value, with a weight of 1 - percentage.
    /// @param y The second value, with a weight of percentage.
    /// @param percentage The weight of y, and complement of the weight of x.
    /// @return z The result of the weighted average.
    function weightedAvg(
        uint256 x,
        uint256 y,
        uint256 percentage
    ) internal pure returns (uint256 z) {
        // Must revert if
        //     percentage > PERCENTAGE_FACTOR
        // or if
        //     y * percentage + HALF_PERCENTAGE_FACTOR > type(uint256).max
        //     <=> percentage > 0 and y > (type(uint256).max - HALF_PERCENTAGE_FACTOR) / percentage
        // or if
        //     x * (PERCENTAGE_FACTOR - percentage) + y * percentage + HALF_PERCENTAGE_FACTOR > type(uint256).max
        //     <=> (PERCENTAGE_FACTOR - percentage) > 0 and x > (type(uint256).max - HALF_PERCENTAGE_FACTOR - y * percentage) / (PERCENTAGE_FACTOR - percentage)
        assembly {
            z := sub(PERCENTAGE_FACTOR, percentage) // Temporary assignment to save gas.
            if or(
                gt(percentage, PERCENTAGE_FACTOR),
                or(
                    mul(percentage, gt(y, div(MAX_UINT256_MINUS_HALF_PERCENTAGE, percentage))),
                    mul(z, gt(x, div(sub(MAX_UINT256_MINUS_HALF_PERCENTAGE, mul(y, percentage)), z)))
                )
            ) {
                revert(0, 0)
            }
            z := div(add(add(mul(x, z), mul(y, percentage)), HALF_PERCENTAGE_FACTOR), PERCENTAGE_FACTOR)
        }
    }
}

File 4 of 29 : WadRayMath.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity ^0.8.0;

/// @title WadRayMath.
/// @author Morpho Labs.
/// @custom:contact [email protected]
/// @notice Optimized version of Aave V3 math library WadRayMath to conduct wad and ray manipulations: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/libraries/math/WadRayMath.sol
library WadRayMath {
    /// CONSTANTS ///

    uint256 internal constant WAD = 1e18;
    uint256 internal constant HALF_WAD = 0.5e18;
    uint256 internal constant RAY = 1e27;
    uint256 internal constant HALF_RAY = 0.5e27;
    uint256 internal constant WAD_RAY_RATIO = 1e9;
    uint256 internal constant HALF_WAD_RAY_RATIO = 0.5e9;
    uint256 internal constant MAX_UINT256 = 2**256 - 1; // Not possible to use type(uint256).max in yul.
    uint256 internal constant MAX_UINT256_MINUS_HALF_WAD = 2**256 - 1 - 0.5e18;
    uint256 internal constant MAX_UINT256_MINUS_HALF_RAY = 2**256 - 1 - 0.5e27;

    /// INTERNAL ///

    /// @dev Multiplies two wad, rounding half up to the nearest wad.
    /// @param x Wad.
    /// @param y Wad.
    /// @return z The result of x * y, in wad.
    function wadMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        // Let y > 0
        // Overflow if (x * y + HALF_WAD) > type(uint256).max
        // <=> x * y > type(uint256).max - HALF_WAD
        // <=> x > (type(uint256).max - HALF_WAD) / y
        assembly {
            if mul(y, gt(x, div(MAX_UINT256_MINUS_HALF_WAD, y))) {
                revert(0, 0)
            }

            z := div(add(mul(x, y), HALF_WAD), WAD)
        }
    }

    /// @dev Divides two wad, rounding half up to the nearest wad.
    /// @param x Wad.
    /// @param y Wad.
    /// @return z The result of x / y, in wad.
    function wadDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
        // Overflow if y == 0
        // Overflow if (x * WAD + y / 2) > type(uint256).max
        // <=> x * WAD > type(uint256).max - y / 2
        // <=> x > (type(uint256).max - y / 2) / WAD
        assembly {
            z := div(y, 2)
            if iszero(mul(y, iszero(gt(x, div(sub(MAX_UINT256, z), WAD))))) {
                revert(0, 0)
            }

            z := div(add(mul(WAD, x), z), y)
        }
    }

    /// @dev Multiplies two ray, rounding half up to the nearest ray.
    /// @param x Ray.
    /// @param y Ray.
    /// @return z The result of x * y, in ray.
    function rayMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        // Let y > 0
        // Overflow if (x * y + HALF_RAY) > type(uint256).max
        // <=> x * y > type(uint256).max - HALF_RAY
        // <=> x > (type(uint256).max - HALF_RAY) / y
        assembly {
            if mul(y, gt(x, div(MAX_UINT256_MINUS_HALF_RAY, y))) {
                revert(0, 0)
            }

            z := div(add(mul(x, y), HALF_RAY), RAY)
        }
    }

    /// @dev Divides two ray, rounding half up to the nearest ray.
    /// @param x Ray.
    /// @param y Ray.
    /// @return z The result of x / y, in ray.
    function rayDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
        // Overflow if y == 0
        // Overflow if (x * RAY + y / 2) > type(uint256).max
        // <=> x * RAY > type(uint256).max - y / 2
        // <=> x > (type(uint256).max - y / 2) / RAY
        assembly {
            z := div(y, 2)
            if iszero(mul(y, iszero(gt(x, div(sub(MAX_UINT256, z), RAY))))) {
                revert(0, 0)
            }

            z := div(add(mul(RAY, x), z), y)
        }
    }

    /// @dev Casts ray down to wad.
    /// @param x Ray.
    /// @return y = x converted to wad, rounded half up to the nearest wad.
    function rayToWad(uint256 x) internal pure returns (uint256 y) {
        assembly {
            // If x % WAD_RAY_RATIO >= HALF_WAD_RAY_RATIO, round up.
            y := add(div(x, WAD_RAY_RATIO), iszero(lt(mod(x, WAD_RAY_RATIO), HALF_WAD_RAY_RATIO)))
        }
    }

    /// @dev Converts wad up to ray.
    /// @param x Wad.
    /// @return y = x converted in ray.
    function wadToRay(uint256 x) internal pure returns (uint256 y) {
        assembly {
            y := mul(WAD_RAY_RATIO, x)
            // Revert if y / WAD_RAY_RATIO != x
            if iszero(eq(div(y, WAD_RAY_RATIO), x)) {
                revert(0, 0)
            }
        }
    }
}

File 5 of 29 : ERC20.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event Transfer(address indexed from, address indexed to, uint256 amount);

    event Approval(address indexed owner, address indexed spender, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                            METADATA STORAGE
    //////////////////////////////////////////////////////////////*/

    string public name;

    string public symbol;

    uint8 public immutable decimals;

    /*//////////////////////////////////////////////////////////////
                              ERC20 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 public totalSupply;

    mapping(address => uint256) public balanceOf;

    mapping(address => mapping(address => uint256)) public allowance;

    /*//////////////////////////////////////////////////////////////
                            EIP-2612 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 internal immutable INITIAL_CHAIN_ID;

    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;

    mapping(address => uint256) public nonces;

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(
        string memory _name,
        string memory _symbol,
        uint8 _decimals
    ) {
        name = _name;
        symbol = _symbol;
        decimals = _decimals;

        INITIAL_CHAIN_ID = block.chainid;
        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
    }

    /*//////////////////////////////////////////////////////////////
                               ERC20 LOGIC
    //////////////////////////////////////////////////////////////*/

    function approve(address spender, uint256 amount) public virtual returns (bool) {
        allowance[msg.sender][spender] = amount;

        emit Approval(msg.sender, spender, amount);

        return true;
    }

    function transfer(address to, uint256 amount) public virtual returns (bool) {
        balanceOf[msg.sender] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(msg.sender, to, amount);

        return true;
    }

    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual returns (bool) {
        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.

        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;

        balanceOf[from] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(from, to, amount);

        return true;
    }

    /*//////////////////////////////////////////////////////////////
                             EIP-2612 LOGIC
    //////////////////////////////////////////////////////////////*/

    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");

        // Unchecked because the only math done is incrementing
        // the owner's nonce which cannot realistically overflow.
        unchecked {
            address recoveredAddress = ecrecover(
                keccak256(
                    abi.encodePacked(
                        "\x19\x01",
                        DOMAIN_SEPARATOR(),
                        keccak256(
                            abi.encode(
                                keccak256(
                                    "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                ),
                                owner,
                                spender,
                                value,
                                nonces[owner]++,
                                deadline
                            )
                        )
                    )
                ),
                v,
                r,
                s
            );

            require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");

            allowance[recoveredAddress][spender] = value;
        }

        emit Approval(owner, spender, value);
    }

    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
    }

    function computeDomainSeparator() internal view virtual returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                    keccak256(bytes(name)),
                    keccak256("1"),
                    block.chainid,
                    address(this)
                )
            );
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL MINT/BURN LOGIC
    //////////////////////////////////////////////////////////////*/

    function _mint(address to, uint256 amount) internal virtual {
        totalSupply += amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(address(0), to, amount);
    }

    function _burn(address from, uint256 amount) internal virtual {
        balanceOf[from] -= amount;

        // Cannot underflow because a user's balance
        // will never be larger than the total supply.
        unchecked {
            totalSupply -= amount;
        }

        emit Transfer(from, address(0), amount);
    }
}

File 6 of 29 : SafeTransferLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

import {ERC20} from "../tokens/ERC20.sol";

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
    /*//////////////////////////////////////////////////////////////
                             ETH OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferETH(address to, uint256 amount) internal {
        bool success;

        assembly {
            // Transfer the ETH and store if it succeeded or not.
            success := call(gas(), to, amount, 0, 0, 0, 0)
        }

        require(success, "ETH_TRANSFER_FAILED");
    }

    /*//////////////////////////////////////////////////////////////
                            ERC20 OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferFrom(
        ERC20 token,
        address from,
        address to,
        uint256 amount
    ) internal {
        bool success;

        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
            mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
            )
        }

        require(success, "TRANSFER_FROM_FAILED");
    }

    function safeTransfer(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        require(success, "TRANSFER_FAILED");
    }

    function safeApprove(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        require(success, "APPROVE_FAILED");
    }
}

File 7 of 29 : IEntryPositionsManager.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity >=0.5.0;

interface IEntryPositionsManager {
    function supplyLogic(
        address _poolToken,
        address _supplier,
        address _onBehalf,
        uint256 _amount,
        uint256 _maxGasForMatching
    ) external;

    function borrowLogic(
        address _poolToken,
        uint256 _amount,
        uint256 _maxGasForMatching
    ) external;
}

File 8 of 29 : IExitPositionsManager.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity >=0.5.0;

interface IExitPositionsManager {
    function withdrawLogic(
        address _poolToken,
        uint256 _amount,
        address _supplier,
        address _receiver,
        uint256 _maxGasForMatching
    ) external;

    function repayLogic(
        address _poolToken,
        address _repayer,
        address _onBehalf,
        uint256 _amount,
        uint256 _maxGasForMatching
    ) external;

    function liquidateLogic(
        address _poolTokenBorrowed,
        address _poolTokenCollateral,
        address _borrower,
        uint256 _amount
    ) external;

    function increaseP2PDeltasLogic(address _poolToken, uint256 _amount) external;
}

File 9 of 29 : IInterestRatesManager.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity >=0.5.0;

interface IInterestRatesManager {
    function updateIndexes(address _marketAddress) external;
}

File 10 of 29 : IMorpho.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity >=0.5.0;

import "./aave/ILendingPoolAddressesProvider.sol";
import "./aave/ILendingPool.sol";
import "./IEntryPositionsManager.sol";
import "./IExitPositionsManager.sol";
import "./IInterestRatesManager.sol";

import "../libraries/Types.sol";

// prettier-ignore
interface IMorpho {

    /// STORAGE ///

    function NO_REFERRAL_CODE() external view returns(uint8);
    function VARIABLE_INTEREST_MODE() external view returns(uint8);
    function MAX_BASIS_POINTS() external view returns (uint16);
    function DEFAULT_LIQUIDATION_CLOSE_FACTOR() external view returns (uint256);
    function HEALTH_FACTOR_LIQUIDATION_THRESHOLD() external view returns(uint256);
    function MAX_NB_OF_MARKETS() external view returns(uint256);
    function BORROWING_MASK() external view returns(bytes32);
    function ONE() external view returns(bytes32);

    function ST_ETH() external view returns (address);
    function ST_ETH_BASE_REBASE_INDEX() external view returns (uint256);

    function isClaimRewardsPaused() external view returns (bool);
    function defaultMaxGasForMatching() external view returns (Types.MaxGasForMatching memory);
    function maxSortedUsers() external view returns (uint256);
    function supplyBalanceInOf(address, address) external view returns (Types.SupplyBalance memory);
    function borrowBalanceInOf(address, address) external view returns (Types.BorrowBalance memory);
    function deltas(address) external view returns (Types.Delta memory);
    function market(address) external view returns (Types.Market memory);
    function marketPauseStatus(address) external view returns (Types.MarketPauseStatus memory);
    function p2pSupplyIndex(address) external view returns (uint256);
    function p2pBorrowIndex(address) external view returns (uint256);
    function poolIndexes(address) external view returns (Types.PoolIndexes memory);
    function interestRatesManager() external view returns (IInterestRatesManager);
    function entryPositionsManager() external view returns (IEntryPositionsManager);
    function exitPositionsManager() external view returns (IExitPositionsManager);
    function addressesProvider() external view returns (ILendingPoolAddressesProvider);
    function pool() external view returns (ILendingPool);
    function treasuryVault() external view returns (address);
    function borrowMask(address) external view returns (bytes32);
    function userMarkets(address) external view returns (bytes32);

    /// UTILS ///

    function updateIndexes(address _poolToken) external;

    /// GETTERS ///

    function getMarketsCreated() external view returns (address[] memory marketsCreated_);
    function getHead(address _poolToken, Types.PositionType _positionType) external view returns (address head);
    function getNext(address _poolToken, Types.PositionType _positionType, address _user) external view returns (address next);

    /// GOVERNANCE ///

    function setMaxSortedUsers(uint256 _newMaxSortedUsers) external;
    function setDefaultMaxGasForMatching(Types.MaxGasForMatching memory _maxGasForMatching) external;
    function setExitPositionsManager(IExitPositionsManager _exitPositionsManager) external;
    function setEntryPositionsManager(IEntryPositionsManager _entryPositionsManager) external;
    function setInterestRatesManager(IInterestRatesManager _interestRatesManager) external;
    function setTreasuryVault(address _newTreasuryVaultAddress) external;
    function setIsP2PDisabled(address _poolToken, bool _isP2PDisabled) external;
    function setReserveFactor(address _poolToken, uint256 _newReserveFactor) external;
    function setP2PIndexCursor(address _poolToken, uint16 _p2pIndexCursor) external;
    function setIsPausedForAllMarkets(bool _isPaused) external;
    function setIsSupplyPaused(address _poolToken, bool _isPaused) external;
    function setIsBorrowPaused(address _poolToken, bool _isPaused) external;
    function setIsWithdrawPaused(address _poolToken, bool _isPaused) external;
    function setIsRepayPaused(address _poolToken, bool _isPaused) external;
    function setIsLiquidateCollateralPaused(address _poolToken, bool _isPaused) external;
    function setIsLiquidateBorrowPaused(address _poolToken, bool _isPaused) external;
    function claimToTreasury(address[] calldata _poolTokens, uint256[] calldata _amounts) external;
    function createMarket(address _underlyingToken, uint16 _reserveFactor, uint16 _p2pIndexCursor) external;
    function increaseP2PDeltas(address _poolToken, uint256 _amount) external;

    /// USERS ///

    function supply(address _poolToken, uint256 _amount) external;
    function supply(address _poolToken, address _onBehalf, uint256 _amount) external;
    function supply(address _poolToken, address _onBehalf, uint256 _amount, uint256 _maxGasForMatching) external;
    function borrow(address _poolToken, uint256 _amount) external;
    function borrow(address _poolToken, uint256 _amount, uint256 _maxGasForMatching) external;
    function withdraw(address _poolToken, uint256 _amount) external;
    function withdraw(address _poolToken, uint256 _amount, address _receiver) external;
    function repay(address _poolToken, uint256 _amount) external;
    function repay(address _poolToken, address _onBehalf, uint256 _amount) external;
    function liquidate(address _poolTokenBorrowed, address _poolTokenCollateral, address _borrower, uint256 _amount) external;
}

File 11 of 29 : IAToken.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity >=0.5.0;

import {IERC20} from "./IERC20.sol";
import {IScaledBalanceToken} from "./IScaledBalanceToken.sol";

interface IAToken is IERC20, IScaledBalanceToken {
    /**
     * @dev Emitted after the mint action
     * @param from The address performing the mint
     * @param value The amount being
     * @param index The new liquidity index of the reserve
     **/
    event Mint(address indexed from, uint256 value, uint256 index);

    /**
     * @dev Mints `amount` aTokens to `user`
     * @param user The address receiving the minted tokens
     * @param amount The amount of tokens getting minted
     * @param index The new liquidity index of the reserve
     * @return `true` if the the previous balance of the user was 0
     */
    function mint(
        address user,
        uint256 amount,
        uint256 index
    ) external returns (bool);

    /**
     * @dev Emitted after aTokens are burned
     * @param from The owner of the aTokens, getting them burned
     * @param target The address that will receive the underlying
     * @param value The amount being burned
     * @param index The new liquidity index of the reserve
     **/
    event Burn(address indexed from, address indexed target, uint256 value, uint256 index);

    /**
     * @dev Emitted during the transfer action
     * @param from The user whose tokens are being transferred
     * @param to The recipient
     * @param value The amount being transferred
     * @param index The new liquidity index of the reserve
     **/
    event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);

    /**
     * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`
     * @param user The owner of the aTokens, getting them burned
     * @param receiverOfUnderlying The address that will receive the underlying
     * @param amount The amount being burned
     * @param index The new liquidity index of the reserve
     **/
    function burn(
        address user,
        address receiverOfUnderlying,
        uint256 amount,
        uint256 index
    ) external;

    /**
     * @dev Mints aTokens to the reserve treasury
     * @param amount The amount of tokens getting minted
     * @param index The new liquidity index of the reserve
     */
    function mintToTreasury(uint256 amount, uint256 index) external;

    /**
     * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken
     * @param from The address getting liquidated, current owner of the aTokens
     * @param to The recipient
     * @param value The amount of tokens getting transferred
     **/
    function transferOnLiquidation(
        address from,
        address to,
        uint256 value
    ) external;

    /**
     * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer
     * assets in borrow(), withdraw() and flashLoan()
     * @param user The recipient of the aTokens
     * @param amount The amount getting transferred
     * @return The amount transferred
     **/
    function transferUnderlyingTo(address user, uint256 amount) external returns (uint256);

    function UNDERLYING_ASSET_ADDRESS() external view returns (address);
}

File 12 of 29 : IERC20.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity >=0.5.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

File 13 of 29 : ILendingPool.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;

import {ILendingPoolAddressesProvider} from "./ILendingPoolAddressesProvider.sol";
import {DataTypes} from "../../libraries/aave/DataTypes.sol";

interface ILendingPool {
    /**
     * @dev Emitted on deposit()
     * @param reserve The address of the underlying asset of the reserve
     * @param user The address initiating the deposit
     * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens
     * @param amount The amount deposited
     * @param referral The referral code used
     **/
    event Deposit(
        address indexed reserve,
        address user,
        address indexed onBehalfOf,
        uint256 amount,
        uint16 indexed referral
    );

    /**
     * @dev Emitted on withdraw()
     * @param reserve The address of the underlyng asset being withdrawn
     * @param user The address initiating the withdrawal, owner of aTokens
     * @param to Address that will receive the underlying
     * @param amount The amount to be withdrawn
     **/
    event Withdraw(
        address indexed reserve,
        address indexed user,
        address indexed to,
        uint256 amount
    );

    /**
     * @dev Emitted on borrow() and flashLoan() when debt needs to be opened
     * @param reserve The address of the underlying asset being borrowed
     * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
     * initiator of the transaction on flashLoan()
     * @param onBehalfOf The address that will be getting the debt
     * @param amount The amount borrowed out
     * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable
     * @param borrowRate The numeric rate at which the user has borrowed
     * @param referral The referral code used
     **/
    event Borrow(
        address indexed reserve,
        address user,
        address indexed onBehalfOf,
        uint256 amount,
        uint256 borrowRateMode,
        uint256 borrowRate,
        uint16 indexed referral
    );

    /**
     * @dev Emitted on repay()
     * @param reserve The address of the underlying asset of the reserve
     * @param user The beneficiary of the repayment, getting his debt reduced
     * @param repayer The address of the user initiating the repay(), providing the funds
     * @param amount The amount repaid
     **/
    event Repay(
        address indexed reserve,
        address indexed user,
        address indexed repayer,
        uint256 amount
    );

    /**
     * @dev Emitted on swapBorrowRateMode()
     * @param reserve The address of the underlying asset of the reserve
     * @param user The address of the user swapping his rate mode
     * @param rateMode The rate mode that the user wants to swap to
     **/
    event Swap(address indexed reserve, address indexed user, uint256 rateMode);

    /**
     * @dev Emitted on setUserUseReserveAsCollateral()
     * @param reserve The address of the underlying asset of the reserve
     * @param user The address of the user enabling the usage as collateral
     **/
    event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);

    /**
     * @dev Emitted on setUserUseReserveAsCollateral()
     * @param reserve The address of the underlying asset of the reserve
     * @param user The address of the user enabling the usage as collateral
     **/
    event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);

    /**
     * @dev Emitted on rebalanceStableBorrowRate()
     * @param reserve The address of the underlying asset of the reserve
     * @param user The address of the user for which the rebalance has been executed
     **/
    event RebalanceStableBorrowRate(address indexed reserve, address indexed user);

    /**
     * @dev Emitted on flashLoan()
     * @param target The address of the flash loan receiver contract
     * @param initiator The address initiating the flash loan
     * @param asset The address of the asset being flash borrowed
     * @param amount The amount flash borrowed
     * @param premium The fee flash borrowed
     * @param referralCode The referral code used
     **/
    event FlashLoan(
        address indexed target,
        address indexed initiator,
        address indexed asset,
        uint256 amount,
        uint256 premium,
        uint16 referralCode
    );

    /**
     * @dev Emitted when the pause is triggered.
     */
    event Paused();

    /**
     * @dev Emitted when the pause is lifted.
     */
    event Unpaused();

    /**
     * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via
     * LendingPoolCollateral manager using a DELEGATECALL
     * This allows to have the events in the generated ABI for LendingPool.
     * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
     * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
     * @param user The address of the borrower getting liquidated
     * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
     * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator
     * @param liquidator The address of the liquidator
     * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
     * to receive the underlying collateral asset directly
     **/
    event LiquidationCall(
        address indexed collateralAsset,
        address indexed debtAsset,
        address indexed user,
        uint256 debtToCover,
        uint256 liquidatedCollateralAmount,
        address liquidator,
        bool receiveAToken
    );

    /**
     * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
     * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
     * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
     * gets added to the LendingPool ABI
     * @param reserve The address of the underlying asset of the reserve
     * @param liquidityRate The new liquidity rate
     * @param stableBorrowRate The new stable borrow rate
     * @param variableBorrowRate The new variable borrow rate
     * @param liquidityIndex The new liquidity index
     * @param variableBorrowIndex The new variable borrow index
     **/
    event ReserveDataUpdated(
        address indexed reserve,
        uint256 liquidityRate,
        uint256 stableBorrowRate,
        uint256 variableBorrowRate,
        uint256 liquidityIndex,
        uint256 variableBorrowIndex
    );

    /**
     * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
     * - E.g. User deposits 100 USDC and gets in return 100 aUSDC
     * @param asset The address of the underlying asset to deposit
     * @param amount The amount to be deposited
     * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
     *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
     *   is a different wallet
     * @param referralCode Code used to register the integrator originating the operation, for potential rewards.
     *   0 if the action is executed directly by the user, without any middle-man
     **/
    function deposit(
        address asset,
        uint256 amount,
        address onBehalfOf,
        uint16 referralCode
    ) external;

    /**
     * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
     * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
     * @param asset The address of the underlying asset to withdraw
     * @param amount The underlying amount to be withdrawn
     *   - Send the value type(uint256).max in order to withdraw the whole aToken balance
     * @param to Address that will receive the underlying, same as msg.sender if the user
     *   wants to receive it on his own wallet, or a different address if the beneficiary is a
     *   different wallet
     * @return The final amount withdrawn
     **/
    function withdraw(
        address asset,
        uint256 amount,
        address to
    ) external returns (uint256);

    /**
     * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
     * already deposited enough collateral, or he was given enough allowance by a credit delegator on the
     * corresponding debt token (StableDebtToken or VariableDebtToken)
     * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
     *   and 100 stable/variable debt tokens, depending on the `interestRateMode`
     * @param asset The address of the underlying asset to borrow
     * @param amount The amount to be borrowed
     * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
     * @param referralCode Code used to register the integrator originating the operation, for potential rewards.
     *   0 if the action is executed directly by the user, without any middle-man
     * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
     * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
     * if he has been given credit delegation allowance
     **/
    function borrow(
        address asset,
        uint256 amount,
        uint256 interestRateMode,
        uint16 referralCode,
        address onBehalfOf
    ) external;

    /**
     * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
     * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
     * @param asset The address of the borrowed underlying asset previously borrowed
     * @param amount The amount to repay
     * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
     * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
     * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
     * user calling the function if he wants to reduce/remove his own debt, or the address of any other
     * other borrower whose debt should be removed
     * @return The final amount repaid
     **/
    function repay(
        address asset,
        uint256 amount,
        uint256 rateMode,
        address onBehalfOf
    ) external returns (uint256);

    /**
     * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
     * @param asset The address of the underlying asset borrowed
     * @param rateMode The rate mode that the user wants to swap to
     **/
    function swapBorrowRateMode(address asset, uint256 rateMode) external;

    /**
     * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
     * - Users can be rebalanced if the following conditions are satisfied:
     *     1. Usage ratio is above 95%
     *     2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
     *        borrowed at a stable rate and depositors are not earning enough
     * @param asset The address of the underlying asset borrowed
     * @param user The address of the user to be rebalanced
     **/
    function rebalanceStableBorrowRate(address asset, address user) external;

    /**
     * @dev Allows depositors to enable/disable a specific deposited asset as collateral
     * @param asset The address of the underlying asset deposited
     * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
     **/
    function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;

    /**
     * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
     * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
     *   a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
     * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
     * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
     * @param user The address of the borrower getting liquidated
     * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
     * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
     * to receive the underlying collateral asset directly
     **/
    function liquidationCall(
        address collateralAsset,
        address debtAsset,
        address user,
        uint256 debtToCover,
        bool receiveAToken
    ) external;

    /**
     * @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
     * as long as the amount taken plus a fee is returned.
     * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
     * For further details please visit https://developers.aave.com
     * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
     * @param assets The addresses of the assets being flash-borrowed
     * @param amounts The amounts amounts being flash-borrowed
     * @param modes Types of the debt to open if the flash loan is not returned:
     *   0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
     *   1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
     *   2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
     * @param onBehalfOf The address  that will receive the debt in the case of using on `modes` 1 or 2
     * @param params Variadic packed params to pass to the receiver as extra information
     * @param referralCode Code used to register the integrator originating the operation, for potential rewards.
     *   0 if the action is executed directly by the user, without any middle-man
     **/
    function flashLoan(
        address receiverAddress,
        address[] calldata assets,
        uint256[] calldata amounts,
        uint256[] calldata modes,
        address onBehalfOf,
        bytes calldata params,
        uint16 referralCode
    ) external;

    /**
     * @dev Returns the user account data across all the reserves
     * @param user The address of the user
     * @return totalCollateralETH the total collateral in ETH of the user
     * @return totalDebtETH the total debt in ETH of the user
     * @return availableBorrowsETH the borrowing power left of the user
     * @return currentLiquidationThreshold the liquidation threshold of the user
     * @return ltv the loan to value of the user
     * @return healthFactor the current health factor of the user
     **/
    function getUserAccountData(address user)
        external
        view
        returns (
            uint256 totalCollateralETH,
            uint256 totalDebtETH,
            uint256 availableBorrowsETH,
            uint256 currentLiquidationThreshold,
            uint256 ltv,
            uint256 healthFactor
        );

    function initReserve(
        address reserve,
        address aTokenAddress,
        address stableDebtAddress,
        address variableDebtAddress,
        address interestRateStrategyAddress
    ) external;

    function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress)
        external;

    function setConfiguration(address reserve, uint256 configuration) external;

    /**
     * @dev Returns the configuration of the reserve
     * @param asset The address of the underlying asset of the reserve
     * @return The configuration of the reserve
     **/
    function getConfiguration(address asset)
        external
        view
        returns (DataTypes.ReserveConfigurationMap memory);

    /**
     * @dev Returns the configuration of the user across all the reserves
     * @param user The user address
     * @return The configuration of the user
     **/
    function getUserConfiguration(address user)
        external
        view
        returns (DataTypes.UserConfigurationMap memory);

    /**
     * @dev Returns the normalized income normalized income of the reserve
     * @param asset The address of the underlying asset of the reserve
     * @return The reserve's normalized income
     */
    function getReserveNormalizedIncome(address asset) external view returns (uint256);

    /**
     * @dev Returns the normalized variable debt per unit of asset
     * @param asset The address of the underlying asset of the reserve
     * @return The reserve normalized variable debt
     */
    function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);

    /**
     * @dev Returns the state and configuration of the reserve
     * @param asset The address of the underlying asset of the reserve
     * @return The state of the reserve
     **/
    function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);

    function finalizeTransfer(
        address asset,
        address from,
        address to,
        uint256 amount,
        uint256 balanceFromAfter,
        uint256 balanceToBefore
    ) external;

    function getReservesList() external view returns (address[] memory);

    function getAddressesProvider() external view returns (ILendingPoolAddressesProvider);

    function setPause(bool val) external;

    function paused() external view returns (bool);

    function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint256);
}

File 14 of 29 : ILendingPoolAddressesProvider.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity >=0.5.0;

/**
 * @title LendingPoolAddressesProvider contract
 * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles
 * - Acting also as factory of proxies and admin of those, so with right to change its implementations
 * - Owned by the Aave Governance
 * @author Aave
 **/
interface ILendingPoolAddressesProvider {
    event MarketIdSet(string newMarketId);
    event LendingPoolUpdated(address indexed newAddress);
    event ConfigurationAdminUpdated(address indexed newAddress);
    event EmergencyAdminUpdated(address indexed newAddress);
    event LendingPoolConfiguratorUpdated(address indexed newAddress);
    event LendingPoolCollateralManagerUpdated(address indexed newAddress);
    event PriceOracleUpdated(address indexed newAddress);
    event LendingRateOracleUpdated(address indexed newAddress);
    event ProxyCreated(bytes32 id, address indexed newAddress);
    event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);

    function getMarketId() external view returns (string memory);

    function setMarketId(string calldata marketId) external;

    function setAddress(bytes32 id, address newAddress) external;

    function setAddressAsProxy(bytes32 id, address impl) external;

    function getAddress(bytes32 id) external view returns (address);

    function getLendingPool() external view returns (address);

    function setLendingPoolImpl(address pool) external;

    function getLendingPoolConfigurator() external view returns (address);

    function setLendingPoolConfiguratorImpl(address configurator) external;

    function getLendingPoolCollateralManager() external view returns (address);

    function setLendingPoolCollateralManager(address manager) external;

    function getPoolAdmin() external view returns (address);

    function setPoolAdmin(address admin) external;

    function getEmergencyAdmin() external view returns (address);

    function setEmergencyAdmin(address admin) external;

    function getPriceOracle() external view returns (address);

    function setPriceOracle(address priceOracle) external;

    function getLendingRateOracle() external view returns (address);

    function setLendingRateOracle(address lendingRateOracle) external;
}

File 15 of 29 : IPriceOracleGetter.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity >=0.5.0;

/************
@title IPriceOracleGetter interface
@notice Interface for the Aave price oracle.*/
interface IPriceOracleGetter {
    /***********
    @dev returns the asset price in ETH
     */
    function getAssetPrice(address _asset) external view returns (uint256);
}

File 16 of 29 : IScaledBalanceToken.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity >=0.5.0;

interface IScaledBalanceToken {
    /**
     * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
     * updated stored balance divided by the reserve's liquidity index at the moment of the update
     * @param user The user whose balance is calculated
     * @return The scaled balance of the user
     **/
    function scaledBalanceOf(address user) external view returns (uint256);

    /**
     * @dev Returns the scaled balance of the user and the scaled total supply.
     * @param user The address of the user
     * @return The scaled balance of the user
     * @return The scaled balance and the scaled total supply
     **/
    function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);

    /**
     * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
     * @return The scaled total supply
     **/
    function scaledTotalSupply() external view returns (uint256);
}

File 17 of 29 : IVariableDebtToken.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity >=0.5.0;

import {IScaledBalanceToken} from "./IScaledBalanceToken.sol";

/**
 * @title IVariableDebtToken
 * @author Aave
 * @notice Defines the basic interface for a variable debt token.
 **/
interface IVariableDebtToken is IScaledBalanceToken {
    /**
     * @dev Emitted after the mint action
     * @param from The address performing the mint
     * @param onBehalfOf The address of the user on which behalf minting has been performed
     * @param value The amount to be minted
     * @param index The last index of the reserve
     **/
    event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index);

    /**
     * @dev delegates borrowing power to a user on the specific debt token
     * @param delegatee the address receiving the delegated borrowing power
     * @param amount the maximum amount being delegated. Delegation will still
     * respect the liquidation constraints (even if delegated, a delegatee cannot
     * force a delegator HF to go below 1)
     **/
    function approveDelegation(address delegatee, uint256 amount) external;

    /**
     * @dev returns the borrow allowance of the user
     * @param fromUser The user to giving allowance
     * @param toUser The user to give allowance to
     * @return the current allowance of toUser
     **/
    function borrowAllowance(address fromUser, address toUser) external view returns (uint256);

    /**
     * @dev Mints debt token to the `onBehalfOf` address
     * @param user The address receiving the borrowed underlying, being the delegatee in case
     * of credit delegate, or same as `onBehalfOf` otherwise
     * @param onBehalfOf The address receiving the debt tokens
     * @param amount The amount of debt being minted
     * @param index The variable debt index of the reserve
     * @return `true` if the the previous balance of the user is 0
     **/
    function mint(
        address user,
        address onBehalfOf,
        uint256 amount,
        uint256 index
    ) external returns (bool);

    /**
     * @dev Emitted when variable debt is burnt
     * @param user The user which debt has been burned
     * @param amount The amount of debt being burned
     * @param index The index of the user
     **/
    event Burn(address indexed user, uint256 amount, uint256 index);

    /**
     * @dev Burns user variable debt
     * @param user The user which debt is burnt
     * @param index The variable debt index of the reserve
     **/
    function burn(
        address user,
        uint256 amount,
        uint256 index
    ) external;

    /**
     * @dev Returns the debt balance of the user
     * @return The debt balance of the user.
     **/
    function balanceOf(address user) external view returns (uint256);
}

File 18 of 29 : ILido.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity >=0.5.0;

interface ILido {
    function getPooledEthByShares(uint256 _sharesAmount) external view returns (uint256);

    function submit(address _referral) external payable returns (uint256);
}

File 19 of 29 : IndexesLens.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity 0.8.13;

import "../interfaces/IInterestRatesManager.sol";
import "../interfaces/lido/ILido.sol";

import "./LensStorage.sol";

/// @title IndexesLens.
/// @author Morpho Labs.
/// @custom:contact [email protected]
/// @notice Intermediary layer exposing endpoints to query live data related to the Morpho Protocol market indexes & rates.
abstract contract IndexesLens is LensStorage {
    using WadRayMath for uint256;

    /// EXTERNAL ///

    /// @notice Returns the updated peer-to-peer supply index.
    /// @param _poolToken The address of the market.
    /// @return p2pSupplyIndex The updated peer-to-peer supply index.
    function getCurrentP2PSupplyIndex(address _poolToken)
        external
        view
        returns (uint256 p2pSupplyIndex)
    {
        (, , Types.Indexes memory indexes) = _getIndexes(_poolToken);

        p2pSupplyIndex = indexes.p2pSupplyIndex;
    }

    /// @notice Returns the updated peer-to-peer borrow index.
    /// @param _poolToken The address of the market.
    /// @return p2pBorrowIndex The updated peer-to-peer borrow index.
    function getCurrentP2PBorrowIndex(address _poolToken)
        external
        view
        returns (uint256 p2pBorrowIndex)
    {
        (, , Types.Indexes memory indexes) = _getIndexes(_poolToken);

        p2pBorrowIndex = indexes.p2pBorrowIndex;
    }

    /// @notice Returns the updated peer-to-peer and pool indexes.
    /// @param _poolToken The address of the market.
    /// @return indexes The given market's updated indexes.
    function getIndexes(address _poolToken) external view returns (Types.Indexes memory indexes) {
        (, , indexes) = _getIndexes(_poolToken);
    }

    /// INTERNAL ///

    /// @notice Returns the updated peer-to-peer and pool indexes.
    /// @param _poolToken The address of the market.
    /// @return market The given market's market data.
    /// @return delta The given market's deltas.
    /// @return indexes The given market's updated indexes.
    function _getIndexes(address _poolToken)
        internal
        view
        returns (
            Types.Market memory market,
            Types.Delta memory delta,
            Types.Indexes memory indexes
        )
    {
        market = morpho.market(_poolToken);
        delta = morpho.deltas(_poolToken);
        Types.PoolIndexes memory lastPoolIndexes = morpho.poolIndexes(_poolToken);

        (indexes.poolSupplyIndex, indexes.poolBorrowIndex) = _getPoolIndexes(
            market.underlyingToken
        );

        InterestRatesModel.GrowthFactors memory growthFactors = InterestRatesModel
        .computeGrowthFactors(
            indexes.poolSupplyIndex,
            indexes.poolBorrowIndex,
            lastPoolIndexes,
            market.p2pIndexCursor,
            market.reserveFactor
        );

        indexes.p2pSupplyIndex = InterestRatesModel.computeP2PSupplyIndex(
            InterestRatesModel.P2PIndexComputeParams({
                poolGrowthFactor: growthFactors.poolSupplyGrowthFactor,
                p2pGrowthFactor: growthFactors.p2pSupplyGrowthFactor,
                lastPoolIndex: lastPoolIndexes.poolSupplyIndex,
                lastP2PIndex: morpho.p2pSupplyIndex(_poolToken),
                p2pDelta: delta.p2pSupplyDelta,
                p2pAmount: delta.p2pSupplyAmount
            })
        );
        indexes.p2pBorrowIndex = InterestRatesModel.computeP2PBorrowIndex(
            InterestRatesModel.P2PIndexComputeParams({
                poolGrowthFactor: growthFactors.poolBorrowGrowthFactor,
                p2pGrowthFactor: growthFactors.p2pBorrowGrowthFactor,
                lastPoolIndex: lastPoolIndexes.poolBorrowIndex,
                lastP2PIndex: morpho.p2pBorrowIndex(_poolToken),
                p2pDelta: delta.p2pBorrowDelta,
                p2pAmount: delta.p2pBorrowAmount
            })
        );
    }

    /// @notice Returns the current pool indexes.
    /// @param _underlyingToken The address of the underlying token.
    /// @return poolSupplyIndex The pool supply index.
    /// @return poolBorrowIndex The pool borrow index.
    function _getPoolIndexes(address _underlyingToken)
        internal
        view
        returns (uint256 poolSupplyIndex, uint256 poolBorrowIndex)
    {
        poolSupplyIndex = pool.getReserveNormalizedIncome(_underlyingToken);
        poolBorrowIndex = pool.getReserveNormalizedVariableDebt(_underlyingToken);

        if (_underlyingToken == ST_ETH) {
            uint256 rebaseIndex = ILido(ST_ETH).getPooledEthByShares(WadRayMath.RAY);

            poolSupplyIndex = poolSupplyIndex.rayMul(rebaseIndex).rayDiv(ST_ETH_BASE_REBASE_INDEX);
            poolBorrowIndex = poolBorrowIndex.rayMul(rebaseIndex).rayDiv(ST_ETH_BASE_REBASE_INDEX);
        }
    }
}

File 21 of 29 : LensStorage.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity 0.8.13;

import "../interfaces/aave/IPriceOracleGetter.sol";
import "../interfaces/aave/ILendingPool.sol";
import "../interfaces/aave/IAToken.sol";
import "../interfaces/IMorpho.sol";
import "./interfaces/ILens.sol";

import "../libraries/aave/ReserveConfiguration.sol";
import "@morpho-dao/morpho-utils/math/PercentageMath.sol";
import "@morpho-dao/morpho-utils/math/WadRayMath.sol";
import "@morpho-dao/morpho-utils/math/Math.sol";
import "../libraries/aave/DataTypes.sol";
import "../libraries/InterestRatesModel.sol";

/// @title LensStorage.
/// @author Morpho Labs.
/// @custom:contact [email protected]
/// @notice Base layer to the Morpho Protocol Lens, managing the upgradeable storage layout.
abstract contract LensStorage is ILens {
    /// CONSTANTS ///

    uint16 public constant DEFAULT_LIQUIDATION_CLOSE_FACTOR = 50_00; // 50% in basis points.
    uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; // Health factor below which the positions can be liquidated.

    address public constant ST_ETH = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;

    /// IMMUTABLES ///

    // stETH is a rebasing token, so the rebase index's value when the astEth market was created is stored
    // and used for internal calculations to convert `stEth.balanceOf` into an amount in scaled units.
    uint256 public immutable ST_ETH_BASE_REBASE_INDEX;

    IMorpho public immutable morpho;
    ILendingPoolAddressesProvider public immutable addressesProvider;
    ILendingPool public immutable pool;

    /// CONSTRUCTOR ///

    /// @notice Constructs the contract.
    /// @param _morpho The address of the main Morpho contract.
    constructor(address _morpho) {
        morpho = IMorpho(_morpho);
        pool = ILendingPool(morpho.pool());
        addressesProvider = ILendingPoolAddressesProvider(morpho.addressesProvider());
        ST_ETH_BASE_REBASE_INDEX = morpho.ST_ETH_BASE_REBASE_INDEX();
    }
}

File 22 of 29 : MarketsLens.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity 0.8.13;

import "./RatesLens.sol";

/// @title MarketsLens.
/// @author Morpho Labs.
/// @custom:contact [email protected]
/// @notice Intermediary layer exposing endpoints to query live data related to the Morpho Protocol markets.
abstract contract MarketsLens is RatesLens {
    using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
    using WadRayMath for uint256;

    /// EXTERNAL ///

    /// @notice Checks if a market is created.
    /// @param _poolToken The address of the market to check.
    /// @return true if the market is created and not paused, otherwise false.
    function isMarketCreated(address _poolToken) external view returns (bool) {
        return morpho.market(_poolToken).isCreated;
    }

    /// @dev Deprecated.
    function isMarketCreatedAndNotPaused(address) external pure returns (bool) {
        return false;
    }

    /// @dev Deprecated.
    function isMarketCreatedAndNotPausedNorPartiallyPaused(address) external pure returns (bool) {
        return false;
    }

    /// @notice Returns all created markets.
    /// @return marketsCreated The list of market addresses.
    function getAllMarkets() external view returns (address[] memory marketsCreated) {
        return morpho.getMarketsCreated();
    }

    /// @notice For a given market, returns the average supply/borrow rates and amounts of underlying asset supplied and borrowed through Morpho, on the underlying pool and matched peer-to-peer.
    /// @dev The returned values are not updated.
    /// @param _poolToken The address of the market of which to get main data.
    /// @return avgSupplyRatePerYear The average supply rate experienced on the given market.
    /// @return avgBorrowRatePerYear The average borrow rate experienced on the given market.
    /// @return p2pSupplyAmount The total supplied amount matched peer-to-peer, subtracting the supply delta (in underlying).
    /// @return p2pBorrowAmount The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in underlying).
    /// @return poolSupplyAmount The total supplied amount on the underlying pool, adding the supply delta (in underlying).
    /// @return poolBorrowAmount The total borrowed amount on the underlying pool, adding the borrow delta (in underlying).
    function getMainMarketData(address _poolToken)
        external
        view
        returns (
            uint256 avgSupplyRatePerYear,
            uint256 avgBorrowRatePerYear,
            uint256 p2pSupplyAmount,
            uint256 p2pBorrowAmount,
            uint256 poolSupplyAmount,
            uint256 poolBorrowAmount
        )
    {
        (avgSupplyRatePerYear, p2pSupplyAmount, poolSupplyAmount) = getAverageSupplyRatePerYear(
            _poolToken
        );
        (avgBorrowRatePerYear, p2pBorrowAmount, poolBorrowAmount) = getAverageBorrowRatePerYear(
            _poolToken
        );
    }

    /// @notice Returns non-updated indexes, the block at which they were last updated and the total deltas of a given market.
    /// @param _poolToken The address of the market of which to get advanced data.
    /// @return indexes The given market's updated indexes.
    /// @return lastUpdateTimestamp The timestamp of the block at which pool indexes were last updated.
    /// @return p2pSupplyDelta The total supply delta (in underlying).
    /// @return p2pBorrowDelta The total borrow delta (in underlying).
    function getAdvancedMarketData(address _poolToken)
        external
        view
        returns (
            Types.Indexes memory indexes,
            uint32 lastUpdateTimestamp,
            uint256 p2pSupplyDelta,
            uint256 p2pBorrowDelta
        )
    {
        Types.Delta memory delta;
        (, delta, indexes) = _getIndexes(_poolToken);

        p2pSupplyDelta = delta.p2pSupplyDelta.rayMul(indexes.poolSupplyIndex);
        p2pBorrowDelta = delta.p2pBorrowDelta.rayMul(indexes.poolBorrowIndex);

        lastUpdateTimestamp = morpho.poolIndexes(_poolToken).lastUpdateTimestamp;
    }

    /// @notice Returns the given market's configuration.
    /// @param _poolToken The address of the market of which to get the configuration.
    /// @return underlying The underlying token address.
    /// @return isCreated Whether the market is created or not.
    /// @return isP2PDisabled Whether the peer-to-peer market is enabled or not.
    /// @return isPaused Deprecated.
    /// @return isPartiallyPaused Deprecated.
    /// @return reserveFactor The reserve factor applied to this market.
    /// @return p2pIndexCursor The p2p index cursor applied to this market.
    /// @return loanToValue The ltv of the given market, set by AAVE.
    /// @return liquidationThreshold The liquidation threshold of the given market, set by AAVE.
    /// @return liquidationBonus The liquidation bonus of the given market, set by AAVE.
    /// @return decimals The number of decimals of the underlying token.
    function getMarketConfiguration(address _poolToken)
        external
        view
        returns (
            address underlying,
            bool isCreated,
            bool isP2PDisabled,
            bool isPaused,
            bool isPartiallyPaused,
            uint16 reserveFactor,
            uint16 p2pIndexCursor,
            uint256 loanToValue,
            uint256 liquidationThreshold,
            uint256 liquidationBonus,
            uint256 decimals
        )
    {
        Types.Market memory market = morpho.market(_poolToken);

        underlying = market.underlyingToken;
        isCreated = market.isCreated;
        isP2PDisabled = market.isP2PDisabled;
        isPaused = false;
        isPartiallyPaused = false;
        reserveFactor = market.reserveFactor;
        p2pIndexCursor = market.p2pIndexCursor;

        (loanToValue, liquidationThreshold, liquidationBonus, decimals, ) = pool
        .getConfiguration(underlying)
        .getParamsMemory();
    }

    /// @notice Returns the given market's pause statuses.
    /// @param _poolToken The address of the market of which to get pause statuses.
    /// @return The market status struct.
    function getMarketPauseStatus(address _poolToken)
        external
        view
        returns (Types.MarketPauseStatus memory)
    {
        return morpho.marketPauseStatus(_poolToken);
    }

    /// @notice Computes and returns the total distribution of supply for a given market, using virtually updated indexes.
    /// @param _poolToken The address of the market to check.
    /// @return p2pSupplyAmount The total supplied amount matched peer-to-peer, subtracting the supply delta (in underlying).
    /// @return poolSupplyAmount The total supplied amount on the underlying pool, adding the supply delta (in underlying).
    function getTotalMarketSupply(address _poolToken)
        external
        view
        returns (uint256 p2pSupplyAmount, uint256 poolSupplyAmount)
    {
        (, p2pSupplyAmount, poolSupplyAmount) = _getTotalMarketSupply(_poolToken);
    }

    /// @notice Computes and returns the total distribution of borrows for a given market, using virtually updated indexes.
    /// @param _poolToken The address of the market to check.
    /// @return p2pBorrowAmount The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in underlying).
    /// @return poolBorrowAmount The total borrowed amount on the underlying pool, adding the borrow delta (in underlying).
    function getTotalMarketBorrow(address _poolToken)
        external
        view
        returns (uint256 p2pBorrowAmount, uint256 poolBorrowAmount)
    {
        (, p2pBorrowAmount, poolBorrowAmount) = _getTotalMarketBorrow(_poolToken);
    }

    /// INTERNAL ///

    /// @notice Computes and returns the total distribution of supply for a given market, using virtually updated indexes.
    /// @param _poolToken The address of the market to check.
    /// @return underlyingToken The address of the underlying ERC20 token of the given market.
    /// @return p2pSupplyAmount The total supplied amount matched peer-to-peer, subtracting the supply delta (in underlying).
    /// @return poolSupplyAmount The total supplied amount on the underlying pool, adding the supply delta (in underlying).
    function _getTotalMarketSupply(address _poolToken)
        internal
        view
        returns (
            address underlyingToken,
            uint256 p2pSupplyAmount,
            uint256 poolSupplyAmount
        )
    {
        (
            Types.Market memory market,
            Types.Delta memory delta,
            Types.Indexes memory indexes
        ) = _getIndexes(_poolToken);

        underlyingToken = market.underlyingToken;
        (p2pSupplyAmount, poolSupplyAmount) = _getMarketSupply(
            _poolToken,
            indexes.p2pSupplyIndex,
            indexes.poolSupplyIndex,
            delta
        );
    }

    /// @notice Computes and returns the total distribution of borrows for a given market, using virtually updated indexes.
    /// @param _poolToken The address of the market to check.
    /// @return underlyingToken The address of the underlying ERC20 token of the given market.
    /// @return p2pBorrowAmount The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in underlying).
    /// @return poolBorrowAmount The total borrowed amount on the underlying pool, adding the borrow delta (in underlying).
    function _getTotalMarketBorrow(address _poolToken)
        internal
        view
        returns (
            address underlyingToken,
            uint256 p2pBorrowAmount,
            uint256 poolBorrowAmount
        )
    {
        (
            Types.Market memory market,
            Types.Delta memory delta,
            Types.Indexes memory indexes
        ) = _getIndexes(_poolToken);

        underlyingToken = market.underlyingToken;
        DataTypes.ReserveData memory reserve = pool.getReserveData(underlyingToken);

        (p2pBorrowAmount, poolBorrowAmount) = _getMarketBorrow(
            reserve,
            indexes.p2pBorrowIndex,
            indexes.poolBorrowIndex,
            delta
        );
    }
}

File 23 of 29 : RatesLens.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity 0.8.13;

import "../interfaces/aave/IVariableDebtToken.sol";

import "./UsersLens.sol";

/// @title RatesLens.
/// @author Morpho Labs.
/// @custom:contact [email protected]
/// @notice Intermediary layer exposing endpoints to query live data related to the Morpho Protocol users and their positions.
abstract contract RatesLens is UsersLens {
    using WadRayMath for uint256;
    using Math for uint256;

    /// EXTERNAL ///

    /// @notice Returns the supply rate per year experienced on a market after having supplied the given amount on behalf of the given user.
    /// @dev Note: the returned supply rate is a low estimate: when supplying through Morpho-Aave,
    /// a supplier could be matched more than once instantly or later and thus benefit from a higher supply rate.
    /// @param _poolToken The address of the market.
    /// @param _user The address of the user on behalf of whom to supply.
    /// @param _amount The amount to supply.
    /// @return nextSupplyRatePerYear An approximation of the next supply rate per year experienced after having supplied (in ray).
    /// @return balanceInP2P The total balance matched peer-to-peer after having supplied (in underlying).
    /// @return balanceOnPool The total balance supplied on pool after having supplied (in underlying).
    /// @return totalBalance The total balance supplied through Morpho (in underlying).
    function getNextUserSupplyRatePerYear(
        address _poolToken,
        address _user,
        uint256 _amount
    )
        external
        view
        returns (
            uint256 nextSupplyRatePerYear,
            uint256 balanceInP2P,
            uint256 balanceOnPool,
            uint256 totalBalance
        )
    {
        (
            Types.Market memory market,
            Types.Delta memory delta,
            Types.Indexes memory indexes
        ) = _getIndexes(_poolToken);

        Types.SupplyBalance memory supplyBalance = morpho.supplyBalanceInOf(_poolToken, _user);
        if (_amount > 0 && delta.p2pBorrowDelta > 0) {
            uint256 matchedDelta = Math.min(
                delta.p2pBorrowDelta.rayMul(indexes.poolBorrowIndex),
                _amount
            );

            supplyBalance.inP2P += matchedDelta.rayDiv(indexes.p2pSupplyIndex);
            _amount -= matchedDelta;
        }

        if (_amount > 0 && !market.isP2PDisabled) {
            address firstPoolBorrower = morpho.getHead(
                _poolToken,
                Types.PositionType.BORROWERS_ON_POOL
            );
            uint256 firstPoolBorrowerBalance = morpho
            .borrowBalanceInOf(_poolToken, firstPoolBorrower)
            .onPool;

            if (firstPoolBorrowerBalance > 0) {
                uint256 matchedP2P = Math.min(
                    firstPoolBorrowerBalance.rayMul(indexes.poolBorrowIndex),
                    _amount
                );

                supplyBalance.inP2P += matchedP2P.rayDiv(indexes.p2pSupplyIndex);
                _amount -= matchedP2P;
            }
        }

        if (_amount > 0) supplyBalance.onPool += _amount.rayDiv(indexes.poolSupplyIndex);

        balanceOnPool = supplyBalance.onPool.rayMul(indexes.poolSupplyIndex);
        balanceInP2P = supplyBalance.inP2P.rayMul(indexes.p2pSupplyIndex);

        (nextSupplyRatePerYear, totalBalance) = _getUserSupplyRatePerYear(
            _poolToken,
            balanceInP2P,
            balanceOnPool
        );
    }

    /// @notice Returns the borrow rate per year experienced on a market after having supplied the given amount on behalf of the given user.
    /// @dev Note: the returned borrow rate is a high estimate: when borrowing through Morpho-Aave,
    /// a borrower could be matched more than once instantly or later and thus benefit from a lower borrow rate.
    /// @param _poolToken The address of the market.
    /// @param _user The address of the user on behalf of whom to borrow.
    /// @param _amount The amount to borrow.
    /// @return nextBorrowRatePerYear An approximation of the next borrow rate per year experienced after having supplied (in ray).
    /// @return balanceInP2P The total balance matched peer-to-peer after having supplied (in underlying).
    /// @return balanceOnPool The total balance supplied on pool after having supplied (in underlying).
    /// @return totalBalance The total balance supplied through Morpho (in underlying).
    function getNextUserBorrowRatePerYear(
        address _poolToken,
        address _user,
        uint256 _amount
    )
        external
        view
        returns (
            uint256 nextBorrowRatePerYear,
            uint256 balanceInP2P,
            uint256 balanceOnPool,
            uint256 totalBalance
        )
    {
        (
            Types.Market memory market,
            Types.Delta memory delta,
            Types.Indexes memory indexes
        ) = _getIndexes(_poolToken);

        Types.BorrowBalance memory borrowBalance = morpho.borrowBalanceInOf(_poolToken, _user);
        if (_amount > 0 && delta.p2pSupplyDelta > 0) {
            uint256 matchedDelta = Math.min(
                delta.p2pSupplyDelta.rayMul(indexes.poolSupplyIndex),
                _amount
            );

            borrowBalance.inP2P += matchedDelta.rayDiv(indexes.p2pBorrowIndex);
            _amount -= matchedDelta;
        }

        if (_amount > 0 && !market.isP2PDisabled) {
            address firstPoolSupplier = morpho.getHead(
                _poolToken,
                Types.PositionType.SUPPLIERS_ON_POOL
            );
            uint256 firstPoolSupplierBalance = morpho
            .supplyBalanceInOf(_poolToken, firstPoolSupplier)
            .onPool;

            if (firstPoolSupplierBalance > 0) {
                uint256 matchedP2P = Math.min(
                    firstPoolSupplierBalance.rayMul(indexes.poolSupplyIndex),
                    _amount
                );

                borrowBalance.inP2P += matchedP2P.rayDiv(indexes.p2pBorrowIndex);
                _amount -= matchedP2P;
            }
        }

        if (_amount > 0) borrowBalance.onPool += _amount.rayDiv(indexes.poolBorrowIndex);

        balanceOnPool = borrowBalance.onPool.rayMul(indexes.poolBorrowIndex);
        balanceInP2P = borrowBalance.inP2P.rayMul(indexes.p2pBorrowIndex);

        (nextBorrowRatePerYear, totalBalance) = _getUserBorrowRatePerYear(
            _poolToken,
            balanceInP2P,
            balanceOnPool
        );
    }

    /// @notice Returns the supply rate per year a given user is currently experiencing on a given market.
    /// @param _poolToken The address of the market.
    /// @param _user The user to compute the supply rate per year for.
    /// @return supplyRatePerYear The supply rate per year the user is currently experiencing (in wad).
    function getCurrentUserSupplyRatePerYear(address _poolToken, address _user)
        external
        view
        returns (uint256 supplyRatePerYear)
    {
        (, uint256 balanceInP2P, uint256 balanceOnPool, ) = _getCurrentSupplyBalanceInOf(
            _poolToken,
            _user
        );

        (supplyRatePerYear, ) = _getUserSupplyRatePerYear(_poolToken, balanceInP2P, balanceOnPool);
    }

    /// @notice Returns the borrow rate per year a given user is currently experiencing on a given market.
    /// @param _poolToken The address of the market.
    /// @param _user The user to compute the borrow rate per year for.
    /// @return borrowRatePerYear The borrow rate per year the user is currently experiencing (in wad).
    function getCurrentUserBorrowRatePerYear(address _poolToken, address _user)
        external
        view
        returns (uint256 borrowRatePerYear)
    {
        (, uint256 balanceInP2P, uint256 balanceOnPool, ) = _getCurrentBorrowBalanceInOf(
            _poolToken,
            _user
        );

        (borrowRatePerYear, ) = _getUserBorrowRatePerYear(_poolToken, balanceInP2P, balanceOnPool);
    }

    /// PUBLIC ///

    /// @notice Computes and returns the current supply rate per year experienced on average on a given market.
    /// @param _poolToken The market address.
    /// @return avgSupplyRatePerYear The market's average supply rate per year (in ray).
    /// @return p2pSupplyAmount The total supplied amount matched peer-to-peer, subtracting the supply delta (in underlying).
    /// @return poolSupplyAmount The total supplied amount on the underlying pool, adding the supply delta (in underlying).
    function getAverageSupplyRatePerYear(address _poolToken)
        public
        view
        returns (
            uint256 avgSupplyRatePerYear,
            uint256 p2pSupplyAmount,
            uint256 poolSupplyAmount
        )
    {
        (
            Types.Market memory market,
            Types.Delta memory delta,
            Types.Indexes memory indexes
        ) = _getIndexes(_poolToken);

        DataTypes.ReserveData memory reserve = pool.getReserveData(market.underlyingToken);
        uint256 poolSupplyRatePerYear = reserve.currentLiquidityRate;

        // Do not take delta into account as it's already taken into account in p2pSupplyAmount & poolSupplyAmount
        uint256 p2pSupplyRatePerYear = InterestRatesModel.computeP2PSupplyRatePerYear(
            InterestRatesModel.P2PRateComputeParams({
                poolSupplyRatePerYear: poolSupplyRatePerYear,
                poolBorrowRatePerYear: reserve.currentVariableBorrowRate,
                poolIndex: indexes.poolSupplyIndex,
                p2pIndex: indexes.p2pSupplyIndex,
                p2pDelta: 0,
                p2pAmount: 0,
                p2pIndexCursor: market.p2pIndexCursor,
                reserveFactor: market.reserveFactor
            })
        );

        (p2pSupplyAmount, poolSupplyAmount) = _getMarketSupply(
            _poolToken,
            indexes.p2pSupplyIndex,
            indexes.poolSupplyIndex,
            delta
        );

        (avgSupplyRatePerYear, ) = _getWeightedRate(
            p2pSupplyRatePerYear,
            poolSupplyRatePerYear,
            p2pSupplyAmount,
            poolSupplyAmount
        );
    }

    /// @notice Computes and returns the current average borrow rate per year experienced on a given market.
    /// @param _poolToken The market address.
    /// @return avgBorrowRatePerYear The market's average borrow rate per year (in ray).
    /// @return p2pBorrowAmount The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in underlying).
    /// @return poolBorrowAmount The total borrowed amount on the underlying pool, adding the borrow delta (in underlying).
    function getAverageBorrowRatePerYear(address _poolToken)
        public
        view
        returns (
            uint256 avgBorrowRatePerYear,
            uint256 p2pBorrowAmount,
            uint256 poolBorrowAmount
        )
    {
        (
            Types.Market memory market,
            Types.Delta memory delta,
            Types.Indexes memory indexes
        ) = _getIndexes(_poolToken);

        DataTypes.ReserveData memory reserve = pool.getReserveData(market.underlyingToken);
        uint256 poolBorrowRatePerYear = reserve.currentVariableBorrowRate;

        // Do not take delta into account as it's already taken into account in p2pBorrowAmount & poolBorrowAmount
        uint256 p2pBorrowRatePerYear = InterestRatesModel.computeP2PBorrowRatePerYear(
            InterestRatesModel.P2PRateComputeParams({
                poolSupplyRatePerYear: reserve.currentLiquidityRate,
                poolBorrowRatePerYear: poolBorrowRatePerYear,
                poolIndex: indexes.poolBorrowIndex,
                p2pIndex: indexes.p2pBorrowIndex,
                p2pDelta: 0,
                p2pAmount: 0,
                p2pIndexCursor: market.p2pIndexCursor,
                reserveFactor: market.reserveFactor
            })
        );

        (p2pBorrowAmount, poolBorrowAmount) = _getMarketBorrow(
            reserve,
            indexes.p2pBorrowIndex,
            indexes.poolBorrowIndex,
            delta
        );

        (avgBorrowRatePerYear, ) = _getWeightedRate(
            p2pBorrowRatePerYear,
            poolBorrowRatePerYear,
            p2pBorrowAmount,
            poolBorrowAmount
        );
    }

    /// @notice Computes and returns peer-to-peer and pool rates for a specific market.
    /// @dev Note: prefer using getAverageSupplyRatePerYear & getAverageBorrowRatePerYear to get the actual experienced supply/borrow rate.
    /// @param _poolToken The market address.
    /// @return p2pSupplyRate The market's peer-to-peer supply rate per year (in ray).
    /// @return p2pBorrowRate The market's peer-to-peer borrow rate per year (in ray).
    /// @return poolSupplyRate The market's pool supply rate per year (in ray).
    /// @return poolBorrowRate The market's pool borrow rate per year (in ray).
    function getRatesPerYear(address _poolToken)
        public
        view
        returns (
            uint256 p2pSupplyRate,
            uint256 p2pBorrowRate,
            uint256 poolSupplyRate,
            uint256 poolBorrowRate
        )
    {
        (
            Types.Market memory market,
            Types.Delta memory delta,
            Types.Indexes memory indexes
        ) = _getIndexes(_poolToken);

        DataTypes.ReserveData memory reserve = pool.getReserveData(market.underlyingToken);
        poolSupplyRate = reserve.currentLiquidityRate;
        poolBorrowRate = reserve.currentVariableBorrowRate;

        p2pSupplyRate = InterestRatesModel.computeP2PSupplyRatePerYear(
            InterestRatesModel.P2PRateComputeParams({
                poolSupplyRatePerYear: poolSupplyRate,
                poolBorrowRatePerYear: poolBorrowRate,
                poolIndex: indexes.poolSupplyIndex,
                p2pIndex: indexes.p2pSupplyIndex,
                p2pDelta: delta.p2pSupplyDelta,
                p2pAmount: delta.p2pSupplyAmount,
                p2pIndexCursor: market.p2pIndexCursor,
                reserveFactor: market.reserveFactor
            })
        );

        p2pBorrowRate = InterestRatesModel.computeP2PBorrowRatePerYear(
            InterestRatesModel.P2PRateComputeParams({
                poolSupplyRatePerYear: poolSupplyRate,
                poolBorrowRatePerYear: poolBorrowRate,
                poolIndex: indexes.poolBorrowIndex,
                p2pIndex: indexes.p2pBorrowIndex,
                p2pDelta: delta.p2pBorrowDelta,
                p2pAmount: delta.p2pBorrowAmount,
                p2pIndexCursor: market.p2pIndexCursor,
                reserveFactor: market.reserveFactor
            })
        );
    }

    /// INTERNAL ///

    /// @notice Computes and returns the total distribution of supply for a given market, using virtually updated indexes.
    /// @param _poolToken The address of the market to check.
    /// @param _p2pSupplyIndex The given market's peer-to-peer supply index.
    /// @param _poolSupplyIndex The given market's pool supply index.
    /// @param _delta The given market's deltas.
    /// @return p2pSupplyAmount The total supplied amount matched peer-to-peer, subtracting the supply delta (in underlying).
    /// @return poolSupplyAmount The total supplied amount on the underlying pool, adding the supply delta (in underlying).
    function _getMarketSupply(
        address _poolToken,
        uint256 _p2pSupplyIndex,
        uint256 _poolSupplyIndex,
        Types.Delta memory _delta
    ) internal view returns (uint256 p2pSupplyAmount, uint256 poolSupplyAmount) {
        p2pSupplyAmount = _delta.p2pSupplyAmount.rayMul(_p2pSupplyIndex).zeroFloorSub(
            _delta.p2pSupplyDelta.rayMul(_poolSupplyIndex)
        );
        poolSupplyAmount = IAToken(_poolToken).balanceOf(address(morpho));
    }

    /// @notice Computes and returns the total distribution of borrows for a given market, using virtually updated indexes.
    /// @param reserve The reserve data of the underlying pool.
    /// @param _p2pBorrowIndex The given market's peer-to-peer borrow index.
    /// @param _poolBorrowIndex The given market's pool borrow index.
    /// @param _delta The given market's deltas.
    /// @return p2pBorrowAmount The total borrowed amount matched peer-to-peer, subtracting the borrow delta (in underlying).
    /// @return poolBorrowAmount The total borrowed amount on the underlying pool, adding the borrow delta (in underlying).
    function _getMarketBorrow(
        DataTypes.ReserveData memory reserve,
        uint256 _p2pBorrowIndex,
        uint256 _poolBorrowIndex,
        Types.Delta memory _delta
    ) internal view returns (uint256 p2pBorrowAmount, uint256 poolBorrowAmount) {
        p2pBorrowAmount = _delta.p2pBorrowAmount.rayMul(_p2pBorrowIndex).zeroFloorSub(
            _delta.p2pBorrowDelta.rayMul(_poolBorrowIndex)
        );
        poolBorrowAmount = IVariableDebtToken(reserve.variableDebtTokenAddress)
        .scaledBalanceOf(address(morpho))
        .rayMul(_poolBorrowIndex);
    }

    /// @dev Returns the supply rate per year experienced on a market based on a given position distribution.
    /// @param _poolToken The address of the market.
    /// @param _balanceOnPool The amount of balance supplied on pool (in a unit common to `_balanceInP2P`).
    /// @param _balanceInP2P The amount of balance matched peer-to-peer (in a unit common to `_balanceOnPool`).
    /// @return The supply rate per year experienced by the given position (in ray).
    /// @return The sum of peer-to-peer & pool balances.
    function _getUserSupplyRatePerYear(
        address _poolToken,
        uint256 _balanceInP2P,
        uint256 _balanceOnPool
    ) internal view returns (uint256, uint256) {
        (uint256 p2pSupplyRatePerYear, , uint256 poolSupplyRatePerYear, ) = getRatesPerYear(
            _poolToken
        );

        return
            _getWeightedRate(
                p2pSupplyRatePerYear,
                poolSupplyRatePerYear,
                _balanceInP2P,
                _balanceOnPool
            );
    }

    /// @dev Returns the borrow rate per year experienced on a market based on a given position distribution.
    /// @param _poolToken The address of the market.
    /// @param _balanceOnPool The amount of balance supplied on pool (in a unit common to `_balanceInP2P`).
    /// @param _balanceInP2P The amount of balance matched peer-to-peer (in a unit common to `_balanceOnPool`).
    /// @return The borrow rate per year experienced by the given position (in ray).
    /// @return The sum of peer-to-peer & pool balances.
    function _getUserBorrowRatePerYear(
        address _poolToken,
        uint256 _balanceInP2P,
        uint256 _balanceOnPool
    ) internal view returns (uint256, uint256) {
        (, uint256 p2pBorrowRatePerYear, , uint256 poolBorrowRatePerYear) = getRatesPerYear(
            _poolToken
        );

        return
            _getWeightedRate(
                p2pBorrowRatePerYear,
                poolBorrowRatePerYear,
                _balanceInP2P,
                _balanceOnPool
            );
    }

    /// @dev Returns the rate experienced based on a given pool & peer-to-peer distribution.
    /// @param _p2pRate The peer-to-peer rate (in a unit common to `_poolRate` & `weightedRate`).
    /// @param _poolRate The pool rate (in a unit common to `_p2pRate` & `weightedRate`).
    /// @param _balanceInP2P The amount of balance matched peer-to-peer (in a unit common to `_balanceOnPool`).
    /// @param _balanceOnPool The amount of balance supplied on pool (in a unit common to `_balanceInP2P`).
    /// @return weightedRate The rate experienced by the given distribution (in a unit common to `_p2pRate` & `_poolRate`).
    /// @return totalBalance The sum of peer-to-peer & pool balances.
    function _getWeightedRate(
        uint256 _p2pRate,
        uint256 _poolRate,
        uint256 _balanceInP2P,
        uint256 _balanceOnPool
    ) internal pure returns (uint256 weightedRate, uint256 totalBalance) {
        totalBalance = _balanceInP2P + _balanceOnPool;
        if (totalBalance == 0) return (weightedRate, totalBalance);

        if (_balanceInP2P > 0) weightedRate += _p2pRate.rayMul(_balanceInP2P.rayDiv(totalBalance));
        if (_balanceOnPool > 0)
            weightedRate += _poolRate.rayMul(_balanceOnPool.rayDiv(totalBalance));
    }
}

File 24 of 29 : UsersLens.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity 0.8.13;

import {ERC20} from "@rari-capital/solmate/src/utils/SafeTransferLib.sol";

import "./IndexesLens.sol";

/// @title UsersLens.
/// @author Morpho Labs.
/// @custom:contact [email protected]
/// @notice Intermediary layer exposing endpoints to query live data related to the Morpho Protocol users and their positions.
abstract contract UsersLens is IndexesLens {
    using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
    using PercentageMath for uint256;
    using WadRayMath for uint256;
    using Math for uint256;

    /// EXTERNAL ///

    /// @notice Returns all markets entered by a given user.
    /// @param _user The address of the user.
    /// @return enteredMarkets The list of markets entered by this user.
    function getEnteredMarkets(address _user)
        external
        view
        returns (address[] memory enteredMarkets)
    {
        address[] memory createdMarkets = morpho.getMarketsCreated();
        uint256 nbCreatedMarkets = createdMarkets.length;

        uint256 nbEnteredMarkets;
        enteredMarkets = new address[](nbCreatedMarkets);

        bytes32 userMarkets = morpho.userMarkets(_user);
        for (uint256 i; i < nbCreatedMarkets; ++i) {
            if (_isSupplyingOrBorrowing(userMarkets, createdMarkets[i])) {
                enteredMarkets[nbEnteredMarkets] = createdMarkets[i];
                ++nbEnteredMarkets;
            }
        }

        // Resize the array for return
        assembly {
            mstore(enteredMarkets, nbEnteredMarkets)
        }
    }

    /// @notice Returns the maximum amount available to withdraw & borrow for a given user, on a given market.
    /// @param _user The user to determine the capacities for.
    /// @param _poolToken The address of the market.
    /// @return withdrawable The maximum withdrawable amount of underlying token allowed (in underlying).
    /// @return borrowable The maximum borrowable amount of underlying token allowed (in underlying).
    function getUserMaxCapacitiesForAsset(address _user, address _poolToken)
        external
        view
        returns (uint256 withdrawable, uint256 borrowable)
    {
        IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());

        Types.LiquidityData memory liquidityData = getUserBalanceStates(_user);
        Types.AssetLiquidityData memory assetData = getUserLiquidityDataForAsset(
            _user,
            _poolToken,
            oracle
        );

        if (
            liquidityData.debtEth > 0 &&
            liquidityData.maxDebtEth.wadDiv(liquidityData.debtEth) <=
            HEALTH_FACTOR_LIQUIDATION_THRESHOLD
        ) return (0, 0);

        uint256 poolTokenBalance = ERC20(IAToken(_poolToken).UNDERLYING_ASSET_ADDRESS()).balanceOf(
            _poolToken
        );

        if (liquidityData.debtEth < liquidityData.borrowableEth)
            borrowable = Math.min(
                poolTokenBalance,
                ((liquidityData.borrowableEth - liquidityData.debtEth) * assetData.tokenUnit) /
                    assetData.underlyingPrice
            );

        withdrawable = Math.min(
            poolTokenBalance,
            (assetData.collateralEth * assetData.tokenUnit) / assetData.underlyingPrice
        );

        if (assetData.liquidationThreshold > 0)
            withdrawable = Math.min(
                withdrawable,
                ((liquidityData.maxDebtEth - liquidityData.debtEth).percentDiv(
                    assetData.liquidationThreshold
                ) * assetData.tokenUnit) / assetData.underlyingPrice
            );
    }

    /// @dev Computes the maximum repayable amount for a potential liquidation.
    /// @param _user The potential liquidatee.
    /// @param _poolTokenBorrowed The address of the market to repay.
    /// @param _poolTokenCollateral The address of the market to seize.
    /// @return The maximum repayable amount (in underlying).
    function computeLiquidationRepayAmount(
        address _user,
        address _poolTokenBorrowed,
        address _poolTokenCollateral
    ) external view returns (uint256) {
        if (!isLiquidatable(_user, _poolTokenBorrowed)) return 0;

        (
            address collateralToken,
            ,
            ,
            uint256 totalCollateralBalance
        ) = _getCurrentSupplyBalanceInOf(_poolTokenCollateral, _user);
        (address borrowedToken, , , uint256 totalBorrowBalance) = _getCurrentBorrowBalanceInOf(
            _poolTokenBorrowed,
            _user
        );

        (, , uint256 liquidationBonus, uint256 collateralReserveDecimals, ) = pool
        .getConfiguration(collateralToken)
        .getParamsMemory();

        IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());
        uint256 borrowedPrice = oracle.getAssetPrice(borrowedToken);
        uint256 collateralPrice = oracle.getAssetPrice(collateralToken);

        return
            Math.min(
                ((totalCollateralBalance * collateralPrice * 10**ERC20(borrowedToken).decimals()) /
                    (borrowedPrice * 10**collateralReserveDecimals))
                    .percentDiv(liquidationBonus),
                totalBorrowBalance.percentMul(DEFAULT_LIQUIDATION_CLOSE_FACTOR)
            );
    }

    /// @notice Returns the balance in underlying of a given user in a given market.
    /// @param _poolToken The address of the market.
    /// @param _user The user to determine balances of.
    /// @return balanceInP2P The balance in peer-to-peer of the user (in underlying).
    /// @return balanceOnPool The balance on pool of the user (in underlying).
    /// @return totalBalance The total balance of the user (in underlying).
    function getCurrentSupplyBalanceInOf(address _poolToken, address _user)
        external
        view
        returns (
            uint256 balanceInP2P,
            uint256 balanceOnPool,
            uint256 totalBalance
        )
    {
        (, balanceInP2P, balanceOnPool, totalBalance) = _getCurrentSupplyBalanceInOf(
            _poolToken,
            _user
        );
    }

    /// @notice Returns the borrow balance in underlying of a given user in a given market.
    /// @param _poolToken The address of the market.
    /// @param _user The user to determine balances of.
    /// @return balanceInP2P The balance in peer-to-peer of the user (in underlying).
    /// @return balanceOnPool The balance on pool of the user (in underlying).
    /// @return totalBalance The total balance of the user (in underlying).
    function getCurrentBorrowBalanceInOf(address _poolToken, address _user)
        external
        view
        returns (
            uint256 balanceInP2P,
            uint256 balanceOnPool,
            uint256 totalBalance
        )
    {
        (, balanceInP2P, balanceOnPool, totalBalance) = _getCurrentBorrowBalanceInOf(
            _poolToken,
            _user
        );
    }

    /// PUBLIC ///

    /// @notice Returns the collateral value, debt value and max debt value of a given user.
    /// @param _user The user to determine liquidity for.
    /// @return The liquidity data of the user.
    function getUserBalanceStates(address _user) public view returns (Types.LiquidityData memory) {
        return getUserHypotheticalBalanceStates(_user, address(0), 0, 0);
    }

    /// @notice Returns the aggregated position of a given user, following an hypothetical borrow/withdraw on a given market,
    ///         using virtually updated pool & peer-to-peer indexes for all markets.
    /// @param _user The user to determine liquidity for.
    /// @param _poolToken The market to hypothetically withdraw/borrow in.
    /// @param _withdrawnAmount The number of tokens to hypothetically withdraw from the given market (in underlying).
    /// @param _borrowedAmount The amount of tokens to hypothetically borrow from the given market (in underlying).
    /// @return liquidityData The liquidity data of the user.
    function getUserHypotheticalBalanceStates(
        address _user,
        address _poolToken,
        uint256 _withdrawnAmount,
        uint256 _borrowedAmount
    ) public view returns (Types.LiquidityData memory liquidityData) {
        IPriceOracleGetter oracle = IPriceOracleGetter(addressesProvider.getPriceOracle());
        address[] memory createdMarkets = morpho.getMarketsCreated();
        bytes32 userMarkets = morpho.userMarkets(_user);

        uint256 nbCreatedMarkets = createdMarkets.length;
        for (uint256 i; i < nbCreatedMarkets; ++i) {
            address poolToken = createdMarkets[i];

            if (!_isSupplyingOrBorrowing(userMarkets, poolToken) && _poolToken != poolToken)
                continue;

            Types.AssetLiquidityData memory assetData = _poolToken == poolToken
                ? _getUserHypotheticalLiquidityDataForAsset(
                    _user,
                    poolToken,
                    oracle,
                    _withdrawnAmount,
                    _borrowedAmount
                )
                : _getUserHypotheticalLiquidityDataForAsset(_user, poolToken, oracle, 0, 0);

            liquidityData.collateralEth += assetData.collateralEth;
            liquidityData.borrowableEth += assetData.collateralEth.percentMul(assetData.ltv);
            liquidityData.maxDebtEth += assetData.collateralEth.percentMul(
                assetData.liquidationThreshold
            );
            liquidityData.debtEth += assetData.debtEth;
        }
    }

    /// @notice Returns the data related to `_poolToken` for the `_user`.
    /// @param _user The user to determine data for.
    /// @param _poolToken The address of the market.
    /// @param _oracle The oracle used.
    /// @return assetData The data related to this asset.
    function getUserLiquidityDataForAsset(
        address _user,
        address _poolToken,
        IPriceOracleGetter _oracle
    ) public view returns (Types.AssetLiquidityData memory) {
        return _getUserHypotheticalLiquidityDataForAsset(_user, _poolToken, _oracle, 0, 0);
    }

    /// @notice Returns the health factor of a given user, using virtually updated pool & peer-to-peer indexes for all markets.
    /// @param _user The user of whom to get the health factor.
    /// @return The health factor of the given user (in wad).
    function getUserHealthFactor(address _user) public view returns (uint256) {
        return getUserHypotheticalHealthFactor(_user, address(0), 0, 0);
    }

    /// @notice Returns the hypothetical health factor of a user, following an hypothetical borrow/withdraw on a given market,
    ///         using virtually updated pool & peer-to-peer indexes for all markets.
    /// @param _user The user to determine liquidity for.
    /// @param _poolToken The market to hypothetically withdraw/borrow from.
    /// @param _withdrawnAmount The number of tokens to hypothetically withdraw (in underlying).
    /// @param _borrowedAmount The amount of tokens to hypothetically borrow (in underlying).
    /// @return healthFactor The health factor of the user.
    function getUserHypotheticalHealthFactor(
        address _user,
        address _poolToken,
        uint256 _withdrawnAmount,
        uint256 _borrowedAmount
    ) public view returns (uint256 healthFactor) {
        Types.LiquidityData memory liquidityData = getUserHypotheticalBalanceStates(
            _user,
            _poolToken,
            _withdrawnAmount,
            _borrowedAmount
        );
        if (liquidityData.debtEth == 0) return type(uint256).max;

        return liquidityData.maxDebtEth.wadDiv(liquidityData.debtEth);
    }

    /// @notice Returns whether a liquidation can be performed on a given user, based on their health factor.
    /// @dev This function checks for the user's health factor, without treating borrow positions from deprecated market as instantly liquidatable.
    /// @param _user The address of the user to check.
    /// @return whether or not the user is liquidatable.
    function isLiquidatable(address _user) public view returns (bool) {
        return getUserHealthFactor(_user) < HEALTH_FACTOR_LIQUIDATION_THRESHOLD;
    }

    /// @notice Returns whether a liquidation can be performed on a given user borrowing from a given market.
    /// @dev This function checks for the user's health factor as well as whether the given market is deprecated & the user is borrowing from it.
    /// @param _user The address of the user to check.
    /// @param _poolToken The address of the borrowed market to check.
    /// @return whether or not the user is liquidatable.
    function isLiquidatable(address _user, address _poolToken) public view returns (bool) {
        if (morpho.marketPauseStatus(_poolToken).isDeprecated && _isBorrowing(_user, _poolToken))
            return true;

        return isLiquidatable(_user);
    }

    /// INTERNAL ///

    /// @dev Returns wheter the given user is borrowing from the given market.
    /// @param _user The address of the user to check.
    /// @param _market The address of the market to check.
    /// @return True if the user has been supplying or borrowing on this market, false otherwise.
    function _isBorrowing(address _user, address _market) internal view returns (bool) {
        return morpho.userMarkets(_user) & morpho.borrowMask(_market) != 0;
    }

    /// @dev Returns whether the given user is borrowing or supplying on the given market.
    /// @param _userMarkets The bytes representation of entered markets of the user to check for.
    /// @param _market The address of the market to check.
    /// @return True if the user has been supplying or borrowing on this market, false otherwise.
    function _isSupplyingOrBorrowing(bytes32 _userMarkets, address _market)
        internal
        view
        returns (bool)
    {
        bytes32 marketBorrowMask = morpho.borrowMask(_market);

        return _userMarkets & (marketBorrowMask | (marketBorrowMask << 1)) != 0;
    }

    /// @notice Returns the balance in underlying of a given user in a given market.
    /// @param _poolToken The address of the market.
    /// @param _user The user to determine balances of.
    /// @return underlyingToken The address of the underlying ERC20 token of the given market.
    /// @return balanceInP2P The balance in peer-to-peer of the user (in underlying).
    /// @return balanceOnPool The balance on pool of the user (in underlying).
    /// @return totalBalance The total balance of the user (in underlying).
    function _getCurrentSupplyBalanceInOf(address _poolToken, address _user)
        internal
        view
        returns (
            address underlyingToken,
            uint256 balanceInP2P,
            uint256 balanceOnPool,
            uint256 totalBalance
        )
    {
        (Types.Market memory market, , Types.Indexes memory indexes) = _getIndexes(_poolToken);

        underlyingToken = market.underlyingToken;
        (balanceInP2P, balanceOnPool, totalBalance) = _getSupplyBalanceInOf(
            _poolToken,
            _user,
            indexes.p2pSupplyIndex,
            indexes.poolSupplyIndex
        );
    }

    /// @notice Returns the borrow balance in underlying of a given user in a given market.
    /// @param _poolToken The address of the market.
    /// @param _user The user to determine balances of.
    /// @return underlyingToken The address of the underlying ERC20 token of the given market.
    /// @return balanceInP2P The balance in peer-to-peer of the user (in underlying).
    /// @return balanceOnPool The balance on pool of the user (in underlying).
    /// @return totalBalance The total balance of the user (in underlying).
    function _getCurrentBorrowBalanceInOf(address _poolToken, address _user)
        internal
        view
        returns (
            address underlyingToken,
            uint256 balanceInP2P,
            uint256 balanceOnPool,
            uint256 totalBalance
        )
    {
        (Types.Market memory market, , Types.Indexes memory indexes) = _getIndexes(_poolToken);

        underlyingToken = market.underlyingToken;
        (balanceInP2P, balanceOnPool, totalBalance) = _getBorrowBalanceInOf(
            _poolToken,
            _user,
            indexes.p2pBorrowIndex,
            indexes.poolBorrowIndex
        );
    }

    /// @dev Returns the supply balance of `_user` in the `_poolToken` market.
    /// @dev Note: Computes the result with the stored indexes, which are not always the most up to date ones.
    /// @param _poolToken The market where to get the supply amount.
    /// @param _user The address of the user.
    /// @param _p2pSupplyIndex The peer-to-peer supply index of the given market (in ray).
    /// @param _poolSupplyIndex The pool supply index of the given market (in ray).
    /// @return balanceInP2P The balance in peer-to-peer of the user (in underlying).
    /// @return balanceOnPool The balance on pool of the user (in underlying).
    /// @return totalBalance The total balance of the user (in underlying).
    function _getSupplyBalanceInOf(
        address _poolToken,
        address _user,
        uint256 _p2pSupplyIndex,
        uint256 _poolSupplyIndex
    )
        internal
        view
        returns (
            uint256 balanceInP2P,
            uint256 balanceOnPool,
            uint256 totalBalance
        )
    {
        Types.SupplyBalance memory supplyBalance = morpho.supplyBalanceInOf(_poolToken, _user);

        balanceInP2P = supplyBalance.inP2P.rayMul(_p2pSupplyIndex);
        balanceOnPool = supplyBalance.onPool.rayMul(_poolSupplyIndex);

        totalBalance = balanceOnPool + balanceInP2P;
    }

    /// @dev Returns the borrow balance of `_user` in the `_poolToken` market.
    /// @param _poolToken The market where to get the borrow amount.
    /// @param _user The address of the user.
    /// @param _p2pBorrowIndex The peer-to-peer borrow index of the given market (in ray).
    /// @param _poolBorrowIndex The pool borrow index of the given market (in ray).
    /// @return balanceInP2P The balance in peer-to-peer of the user (in underlying).
    /// @return balanceOnPool The balance on pool of the user (in underlying).
    /// @return totalBalance The total balance of the user (in underlying).
    function _getBorrowBalanceInOf(
        address _poolToken,
        address _user,
        uint256 _p2pBorrowIndex,
        uint256 _poolBorrowIndex
    )
        internal
        view
        returns (
            uint256 balanceInP2P,
            uint256 balanceOnPool,
            uint256 totalBalance
        )
    {
        Types.BorrowBalance memory borrowBalance = morpho.borrowBalanceInOf(_poolToken, _user);

        balanceInP2P = borrowBalance.inP2P.rayMul(_p2pBorrowIndex);
        balanceOnPool = borrowBalance.onPool.rayMul(_poolBorrowIndex);

        totalBalance = balanceOnPool + balanceInP2P;
    }

    /// @notice Returns the data related to `_poolToken` for the `_user`.
    /// @param _user The user to determine data for.
    /// @param _poolToken The address of the market.
    /// @param _oracle The oracle used.
    /// @param _withdrawnAmount The amount to hypothetically withdraw from the given market (in underlying).
    /// @param _borrowedAmount The amount to hypothetically borrow from the given market (in underlying).
    /// @return assetData The data related to this asset.
    function _getUserHypotheticalLiquidityDataForAsset(
        address _user,
        address _poolToken,
        IPriceOracleGetter _oracle,
        uint256 _withdrawnAmount,
        uint256 _borrowedAmount
    ) internal view returns (Types.AssetLiquidityData memory assetData) {
        (Types.Market memory market, , Types.Indexes memory indexes) = _getIndexes(_poolToken);

        assetData.underlyingPrice = _oracle.getAssetPrice(market.underlyingToken); // In ETH.
        (assetData.ltv, assetData.liquidationThreshold, , assetData.decimals, ) = pool
        .getConfiguration(market.underlyingToken)
        .getParamsMemory();

        unchecked {
            assetData.tokenUnit = 10**assetData.decimals;
        }

        (, , uint256 totalCollateralBalance) = _getSupplyBalanceInOf(
            _poolToken,
            _user,
            indexes.p2pSupplyIndex,
            indexes.poolSupplyIndex
        );
        (, , uint256 totalDebtBalance) = _getBorrowBalanceInOf(
            _poolToken,
            _user,
            indexes.p2pBorrowIndex,
            indexes.poolBorrowIndex
        );

        assetData.debtEth = ((totalDebtBalance + _borrowedAmount) * assetData.underlyingPrice)
        .divUp(assetData.tokenUnit);
        assetData.collateralEth =
            ((totalCollateralBalance.zeroFloorSub(_withdrawnAmount)) * assetData.underlyingPrice) /
            assetData.tokenUnit;
    }
}

File 25 of 29 : ILens.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity >=0.5.0;

import "../../interfaces/aave/IPriceOracleGetter.sol";
import "../../interfaces/aave/ILendingPool.sol";
import "../../interfaces/IMorpho.sol";

interface ILens {
    /// STORAGE ///

    function DEFAULT_LIQUIDATION_CLOSE_FACTOR() external view returns (uint16);

    function HEALTH_FACTOR_LIQUIDATION_THRESHOLD() external view returns (uint256);

    function ST_ETH() external view returns (address);

    function ST_ETH_BASE_REBASE_INDEX() external view returns (uint256);

    function morpho() external view returns (IMorpho);

    function addressesProvider() external view returns (ILendingPoolAddressesProvider);

    function pool() external view returns (ILendingPool);

    /// GENERAL ///

    function getTotalSupply()
        external
        view
        returns (
            uint256 p2pSupplyAmount,
            uint256 poolSupplyAmount,
            uint256 totalSupplyAmount
        );

    function getTotalBorrow()
        external
        view
        returns (
            uint256 p2pBorrowAmount,
            uint256 poolBorrowAmount,
            uint256 totalBorrowAmount
        );

    /// MARKETS ///

    function isMarketCreated(address _poolToken) external view returns (bool);

    /// @dev Deprecated.
    function isMarketCreatedAndNotPaused(address _poolToken) external view returns (bool);

    /// @dev Deprecated.
    function isMarketCreatedAndNotPausedNorPartiallyPaused(address _poolToken)
        external
        view
        returns (bool);

    function getAllMarkets() external view returns (address[] memory marketsCreated_);

    function getMainMarketData(address _poolToken)
        external
        view
        returns (
            uint256 avgSupplyRatePerYear,
            uint256 avgBorrowRatePerYear,
            uint256 p2pSupplyAmount,
            uint256 p2pBorrowAmount,
            uint256 poolSupplyAmount,
            uint256 poolBorrowAmount
        );

    function getAdvancedMarketData(address _poolToken)
        external
        view
        returns (
            Types.Indexes memory indexes,
            uint32 lastUpdateTimestamp,
            uint256 p2pSupplyDelta,
            uint256 p2pBorrowDelta
        );

    function getMarketConfiguration(address _poolToken)
        external
        view
        returns (
            address underlying,
            bool isCreated,
            bool isP2PDisabled,
            bool isPaused,
            bool isPartiallyPaused,
            uint16 reserveFactor,
            uint16 p2pIndexCursor,
            uint256 loanToValue,
            uint256 liquidationThreshold,
            uint256 liquidationBonus,
            uint256 decimals
        );

    function getMarketPauseStatus(address _poolToken)
        external
        view
        returns (Types.MarketPauseStatus memory);

    function getTotalMarketSupply(address _poolToken)
        external
        view
        returns (uint256 p2pSupplyAmount, uint256 poolSupplyAmount);

    function getTotalMarketBorrow(address _poolToken)
        external
        view
        returns (uint256 p2pBorrowAmount, uint256 poolBorrowAmount);

    /// INDEXES ///

    function getCurrentP2PSupplyIndex(address _poolToken) external view returns (uint256);

    function getCurrentP2PBorrowIndex(address _poolToken) external view returns (uint256);

    function getIndexes(address _poolToken) external view returns (Types.Indexes memory indexes);

    /// USERS ///

    function getEnteredMarkets(address _user)
        external
        view
        returns (address[] memory enteredMarkets);

    function getUserHealthFactor(address _user) external view returns (uint256 healthFactor);

    function getUserBalanceStates(address _user)
        external
        view
        returns (Types.LiquidityData memory assetData);

    function getCurrentSupplyBalanceInOf(address _poolToken, address _user)
        external
        view
        returns (
            uint256 balanceInP2P,
            uint256 balanceOnPool,
            uint256 totalBalance
        );

    function getCurrentBorrowBalanceInOf(address _poolToken, address _user)
        external
        view
        returns (
            uint256 balanceInP2P,
            uint256 balanceOnPool,
            uint256 totalBalance
        );

    function getUserMaxCapacitiesForAsset(address _user, address _poolToken)
        external
        view
        returns (uint256 withdrawable, uint256 borrowable);

    function getUserHypotheticalBalanceStates(
        address _user,
        address _poolToken,
        uint256 _withdrawnAmount,
        uint256 _borrowedAmount
    ) external view returns (Types.LiquidityData memory assetData);

    function getUserHypotheticalHealthFactor(
        address _user,
        address _poolToken,
        uint256 _withdrawnAmount,
        uint256 _borrowedAmount
    ) external view returns (uint256 healthFactor);

    function getUserLiquidityDataForAsset(
        address _user,
        address _poolToken,
        IPriceOracleGetter _oracle
    ) external view returns (Types.AssetLiquidityData memory assetData);

    function isLiquidatable(address _user) external view returns (bool);

    function isLiquidatable(address _user, address _poolToken) external view returns (bool);

    function computeLiquidationRepayAmount(
        address _user,
        address _poolTokenBorrowed,
        address _poolTokenCollateral
    ) external view returns (uint256 toRepay);

    /// RATES ///

    function getNextUserSupplyRatePerYear(
        address _poolToken,
        address _user,
        uint256 _amount
    )
        external
        view
        returns (
            uint256 nextSupplyRatePerYear,
            uint256 balanceInP2P,
            uint256 balanceOnPool,
            uint256 totalBalance
        );

    function getNextUserBorrowRatePerYear(
        address _poolToken,
        address _user,
        uint256 _amount
    )
        external
        view
        returns (
            uint256 nextBorrowRatePerYear,
            uint256 balanceInP2P,
            uint256 balanceOnPool,
            uint256 totalBalance
        );

    function getCurrentUserSupplyRatePerYear(address _poolToken, address _user)
        external
        view
        returns (uint256);

    function getCurrentUserBorrowRatePerYear(address _poolToken, address _user)
        external
        view
        returns (uint256);

    function getAverageSupplyRatePerYear(address _poolToken)
        external
        view
        returns (
            uint256 avgSupplyRatePerYear,
            uint256 p2pSupplyAmount,
            uint256 poolSupplyAmount
        );

    function getAverageBorrowRatePerYear(address _poolToken)
        external
        view
        returns (
            uint256 avgBorrowRatePerYear,
            uint256 p2pBorrowAmount,
            uint256 poolBorrowAmount
        );

    function getRatesPerYear(address _poolToken)
        external
        view
        returns (
            uint256 p2pSupplyRate,
            uint256 p2pBorrowRate,
            uint256 poolSupplyRate,
            uint256 poolBorrowRate
        );
}

File 26 of 29 : InterestRatesModel.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity ^0.8.0;

import "@morpho-dao/morpho-utils/math/PercentageMath.sol";
import "@morpho-dao/morpho-utils/math/WadRayMath.sol";
import "@morpho-dao/morpho-utils/math/Math.sol";

import "./Types.sol";

library InterestRatesModel {
    using PercentageMath for uint256;
    using WadRayMath for uint256;

    /// STRUCTS ///

    struct GrowthFactors {
        uint256 poolSupplyGrowthFactor; // The pool supply index growth factor (in ray).
        uint256 poolBorrowGrowthFactor; // The pool borrow index growth factor (in ray).
        uint256 p2pSupplyGrowthFactor; // Peer-to-peer supply index growth factor (in ray).
        uint256 p2pBorrowGrowthFactor; // Peer-to-peer borrow index growth factor (in ray).
    }

    struct P2PIndexComputeParams {
        uint256 poolGrowthFactor; // The pool index growth factor (in ray).
        uint256 p2pGrowthFactor; // Morpho's peer-to-peer median index growth factor (in ray).
        uint256 lastPoolIndex; // The last stored pool index (in ray).
        uint256 lastP2PIndex; // The last stored peer-to-peer index (in ray).
        uint256 p2pDelta; // The peer-to-peer delta for the given market (in pool unit).
        uint256 p2pAmount; // The peer-to-peer amount for the given market (in peer-to-peer unit).
    }

    struct P2PRateComputeParams {
        uint256 poolSupplyRatePerYear; // The pool supply rate per year (in ray).
        uint256 poolBorrowRatePerYear; // The pool borrow rate per year (in ray).
        uint256 poolIndex; // The last stored pool index (in ray).
        uint256 p2pIndex; // The last stored peer-to-peer index (in ray).
        uint256 p2pDelta; // The peer-to-peer delta for the given market (in pool unit).
        uint256 p2pAmount; // The peer-to-peer amount for the given market (in peer-to-peer unit).
        uint256 p2pIndexCursor; // The index cursor of the given market (in bps).
        uint256 reserveFactor; // The reserve factor of the given market (in bps).
    }

    /// @notice Computes and returns the new supply/borrow growth factors associated to the given market's pool & peer-to-peer indexes.
    /// @param _newPoolSupplyIndex The current pool supply index.
    /// @param _newPoolBorrowIndex The current pool borrow index.
    /// @param _lastPoolIndexes The last stored pool indexes.
    /// @param _p2pIndexCursor The peer-to-peer index cursor for the given market.
    /// @param _reserveFactor The reserve factor of the given market.
    /// @return growthFactors The market's indexes growth factors (in ray).
    function computeGrowthFactors(
        uint256 _newPoolSupplyIndex,
        uint256 _newPoolBorrowIndex,
        Types.PoolIndexes memory _lastPoolIndexes,
        uint256 _p2pIndexCursor,
        uint256 _reserveFactor
    ) internal pure returns (GrowthFactors memory growthFactors) {
        growthFactors.poolSupplyGrowthFactor = _newPoolSupplyIndex.rayDiv(
            _lastPoolIndexes.poolSupplyIndex
        );
        growthFactors.poolBorrowGrowthFactor = _newPoolBorrowIndex.rayDiv(
            _lastPoolIndexes.poolBorrowIndex
        );

        if (growthFactors.poolSupplyGrowthFactor <= growthFactors.poolBorrowGrowthFactor) {
            uint256 p2pGrowthFactor = PercentageMath.weightedAvg(
                growthFactors.poolSupplyGrowthFactor,
                growthFactors.poolBorrowGrowthFactor,
                _p2pIndexCursor
            );

            growthFactors.p2pSupplyGrowthFactor =
                p2pGrowthFactor -
                (p2pGrowthFactor - growthFactors.poolSupplyGrowthFactor).percentMul(_reserveFactor);
            growthFactors.p2pBorrowGrowthFactor =
                p2pGrowthFactor +
                (growthFactors.poolBorrowGrowthFactor - p2pGrowthFactor).percentMul(_reserveFactor);
        } else {
            // The case poolSupplyGrowthFactor > poolBorrowGrowthFactor happens because someone has done a flashloan on Aave:
            // the peer-to-peer growth factors are set to the pool borrow growth factor.
            growthFactors.p2pSupplyGrowthFactor = growthFactors.poolBorrowGrowthFactor;
            growthFactors.p2pBorrowGrowthFactor = growthFactors.poolBorrowGrowthFactor;
        }
    }

    /// @notice Computes and returns the new peer-to-peer supply index of a market given its parameters.
    /// @param _params The computation parameters.
    /// @return newP2PSupplyIndex The updated peer-to-peer index (in ray).
    function computeP2PSupplyIndex(P2PIndexComputeParams memory _params)
        internal
        pure
        returns (uint256 newP2PSupplyIndex)
    {
        if (_params.p2pAmount == 0 || _params.p2pDelta == 0) {
            newP2PSupplyIndex = _params.lastP2PIndex.rayMul(_params.p2pGrowthFactor);
        } else {
            uint256 shareOfTheDelta = Math.min(
                _params.p2pDelta.rayMul(_params.lastPoolIndex).rayDiv(
                    _params.p2pAmount.rayMul(_params.lastP2PIndex)
                ), // Using ray division of an amount in underlying decimals by an amount in underlying decimals yields a value in ray.
                WadRayMath.RAY // To avoid shareOfTheDelta > 1 with rounding errors.
            ); // In ray.

            newP2PSupplyIndex = _params.lastP2PIndex.rayMul(
                (WadRayMath.RAY - shareOfTheDelta).rayMul(_params.p2pGrowthFactor) +
                    shareOfTheDelta.rayMul(_params.poolGrowthFactor)
            );
        }
    }

    /// @notice Computes and returns the new peer-to-peer borrow index of a market given its parameters.
    /// @param _params The computation parameters.
    /// @return newP2PBorrowIndex The updated peer-to-peer index (in ray).
    function computeP2PBorrowIndex(P2PIndexComputeParams memory _params)
        internal
        pure
        returns (uint256 newP2PBorrowIndex)
    {
        if (_params.p2pAmount == 0 || _params.p2pDelta == 0) {
            newP2PBorrowIndex = _params.lastP2PIndex.rayMul(_params.p2pGrowthFactor);
        } else {
            uint256 shareOfTheDelta = Math.min(
                _params.p2pDelta.rayMul(_params.lastPoolIndex).rayDiv(
                    _params.p2pAmount.rayMul(_params.lastP2PIndex)
                ), // Using ray division of an amount in underlying decimals by an amount in underlying decimals yields a value in ray.
                WadRayMath.RAY // To avoid shareOfTheDelta > 1 with rounding errors.
            ); // In ray.

            newP2PBorrowIndex = _params.lastP2PIndex.rayMul(
                (WadRayMath.RAY - shareOfTheDelta).rayMul(_params.p2pGrowthFactor) +
                    shareOfTheDelta.rayMul(_params.poolGrowthFactor)
            );
        }
    }

    /// @notice Computes and returns the peer-to-peer supply rate per year of a market given its parameters.
    /// @param _params The computation parameters.
    /// @return p2pSupplyRate The peer-to-peer supply rate per year (in ray).
    function computeP2PSupplyRatePerYear(P2PRateComputeParams memory _params)
        internal
        pure
        returns (uint256 p2pSupplyRate)
    {
        if (_params.poolSupplyRatePerYear > _params.poolBorrowRatePerYear) {
            p2pSupplyRate = _params.poolBorrowRatePerYear; // The p2pSupplyRate is set to the poolBorrowRatePerYear because there is no rate spread.
        } else {
            uint256 p2pRate = PercentageMath.weightedAvg(
                _params.poolSupplyRatePerYear,
                _params.poolBorrowRatePerYear,
                _params.p2pIndexCursor
            );

            p2pSupplyRate =
                p2pRate -
                (p2pRate - _params.poolSupplyRatePerYear).percentMul(_params.reserveFactor);
        }

        if (_params.p2pDelta > 0 && _params.p2pAmount > 0) {
            uint256 shareOfTheDelta = Math.min(
                _params.p2pDelta.rayMul(_params.poolIndex).rayDiv(
                    _params.p2pAmount.rayMul(_params.p2pIndex)
                ), // Using ray division of an amount in underlying decimals by an amount in underlying decimals yields a value in ray.
                WadRayMath.RAY // To avoid shareOfTheDelta > 1 with rounding errors.
            ); // In ray.

            p2pSupplyRate =
                p2pSupplyRate.rayMul(WadRayMath.RAY - shareOfTheDelta) +
                _params.poolSupplyRatePerYear.rayMul(shareOfTheDelta);
        }
    }

    /// @notice Computes and returns the peer-to-peer borrow rate per year of a market given its parameters.
    /// @param _params The computation parameters.
    /// @return p2pBorrowRate The peer-to-peer borrow rate per year (in ray).
    function computeP2PBorrowRatePerYear(P2PRateComputeParams memory _params)
        internal
        pure
        returns (uint256 p2pBorrowRate)
    {
        if (_params.poolSupplyRatePerYear > _params.poolBorrowRatePerYear) {
            p2pBorrowRate = _params.poolBorrowRatePerYear; // The p2pBorrowRate is set to the poolBorrowRatePerYear because there is no rate spread.
        } else {
            uint256 p2pRate = PercentageMath.weightedAvg(
                _params.poolSupplyRatePerYear,
                _params.poolBorrowRatePerYear,
                _params.p2pIndexCursor
            );

            p2pBorrowRate =
                p2pRate +
                (_params.poolBorrowRatePerYear - p2pRate).percentMul(_params.reserveFactor);
        }

        if (_params.p2pDelta > 0 && _params.p2pAmount > 0) {
            uint256 shareOfTheDelta = Math.min(
                _params.p2pDelta.rayMul(_params.poolIndex).rayDiv(
                    _params.p2pAmount.rayMul(_params.p2pIndex)
                ), // Using ray division of an amount in underlying decimals by an amount in underlying decimals yields a value in ray.
                WadRayMath.RAY // To avoid shareOfTheDelta > 1 with rounding errors.
            ); // In ray.

            p2pBorrowRate =
                p2pBorrowRate.rayMul(WadRayMath.RAY - shareOfTheDelta) +
                _params.poolBorrowRatePerYear.rayMul(shareOfTheDelta);
        }
    }
}

File 27 of 29 : Types.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity ^0.8.0;

/// @title Types.
/// @author Morpho Labs.
/// @custom:contact [email protected]
/// @dev Common types and structs used in Morpho contracts.
library Types {
    /// ENUMS ///

    enum PositionType {
        SUPPLIERS_IN_P2P,
        SUPPLIERS_ON_POOL,
        BORROWERS_IN_P2P,
        BORROWERS_ON_POOL
    }

    /// STRUCTS ///

    struct SupplyBalance {
        uint256 inP2P; // In peer-to-peer supply scaled unit, a unit that grows in underlying value, to keep track of the interests earned by suppliers in peer-to-peer. Multiply by the peer-to-peer supply index to get the underlying amount.
        uint256 onPool; // In pool supply scaled unit. Multiply by the pool supply index to get the underlying amount.
    }

    struct BorrowBalance {
        uint256 inP2P; // In peer-to-peer borrow scaled unit, a unit that grows in underlying value, to keep track of the interests paid by borrowers in peer-to-peer. Multiply by the peer-to-peer borrow index to get the underlying amount.
        uint256 onPool; // In pool borrow scaled unit, a unit that grows in value, to keep track of the debt increase when borrowers are on Aave. Multiply by the pool borrow index to get the underlying amount.
    }

    struct Indexes {
        uint256 p2pSupplyIndex; // The peer-to-peer supply index (in ray), used to multiply the scaled peer-to-peer supply balance and get the peer-to-peer supply balance (in underlying).
        uint256 p2pBorrowIndex; // The peer-to-peer borrow index (in ray), used to multiply the scaled peer-to-peer borrow balance and get the peer-to-peer borrow balance (in underlying).
        uint256 poolSupplyIndex; // The pool supply index (in ray), used to multiply the scaled pool supply balance and get the pool supply balance (in underlying).
        uint256 poolBorrowIndex; // The pool borrow index (in ray), used to multiply the scaled pool borrow balance and get the pool borrow balance (in underlying).
    }

    // Max gas to consume during the matching process for supply, borrow, withdraw and repay functions.
    struct MaxGasForMatching {
        uint64 supply;
        uint64 borrow;
        uint64 withdraw;
        uint64 repay;
    }

    struct Delta {
        uint256 p2pSupplyDelta; // Difference between the stored peer-to-peer supply amount and the real peer-to-peer supply amount (in pool supply unit).
        uint256 p2pBorrowDelta; // Difference between the stored peer-to-peer borrow amount and the real peer-to-peer borrow amount (in pool borrow unit).
        uint256 p2pSupplyAmount; // Sum of all stored peer-to-peer supply (in peer-to-peer supply unit).
        uint256 p2pBorrowAmount; // Sum of all stored peer-to-peer borrow (in peer-to-peer borrow unit).
    }

    struct AssetLiquidityData {
        uint256 decimals; // The number of decimals of the underlying token.
        uint256 tokenUnit; // The token unit considering its decimals.
        uint256 liquidationThreshold; // The liquidation threshold applied on this token (in basis point).
        uint256 ltv; // The LTV applied on this token (in basis point).
        uint256 underlyingPrice; // The price of the token (in ETH).
        uint256 collateralEth; // The collateral value of the asset (in ETH).
        uint256 debtEth; // The debt value of the asset (in ETH).
    }

    struct LiquidityData {
        uint256 collateralEth; // The collateral value (in ETH).
        uint256 borrowableEth; // The maximum debt value allowed to borrow (in ETH).
        uint256 maxDebtEth; // The maximum debt value allowed before being liquidatable (in ETH).
        uint256 debtEth; // The debt value (in ETH).
    }

    // Variables are packed together to save gas (will not exceed their limit during Morpho's lifetime).
    struct PoolIndexes {
        uint32 lastUpdateTimestamp; // The last time the local pool and peer-to-peer indexes were updated.
        uint112 poolSupplyIndex; // Last pool supply index. Note that for the stEth market, the pool supply index is tweaked to take into account the staking rewards.
        uint112 poolBorrowIndex; // Last pool borrow index. Note that for the stEth market, the pool borrow index is tweaked to take into account the staking rewards.
    }

    struct Market {
        address underlyingToken; // The address of the market's underlying token.
        uint16 reserveFactor; // Proportion of the additional interest earned being matched peer-to-peer on Morpho compared to being on the pool. It is sent to the DAO for each market. The default value is 0. In basis point (100% = 10 000).
        uint16 p2pIndexCursor; // Position of the peer-to-peer rate in the pool's spread. Determine the weights of the weighted arithmetic average in the indexes computations ((1 - p2pIndexCursor) * r^S + p2pIndexCursor * r^B) (in basis point).
        bool isCreated; // Whether or not this market is created.
        bool isPaused; // Deprecated.
        bool isPartiallyPaused; // Deprecated.
        bool isP2PDisabled; // Whether the peer-to-peer market is open or not.
    }

    struct MarketPauseStatus {
        bool isSupplyPaused; // Whether the supply is paused or not.
        bool isBorrowPaused; // Whether the borrow is paused or not
        bool isWithdrawPaused; // Whether the withdraw is paused or not. Note that a "withdraw" is still possible using a liquidation (if not paused).
        bool isRepayPaused; // Whether the repay is paused or not. Note that a "repay" is still possible using a liquidation (if not paused).
        bool isLiquidateCollateralPaused; // Whether the liquidation on this market as collateral is paused or not.
        bool isLiquidateBorrowPaused; // Whether the liquidatation on this market as borrow is paused or not.
        bool isDeprecated; // Whether a market is deprecated or not.
    }
}

File 28 of 29 : DataTypes.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity ^0.8.0;

library DataTypes {
    // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
    struct ReserveData {
        //stores the reserve configuration
        ReserveConfigurationMap configuration;
        //the liquidity index. Expressed in ray
        uint128 liquidityIndex;
        //variable borrow index. Expressed in ray
        uint128 variableBorrowIndex;
        //the current supply rate. Expressed in ray
        uint128 currentLiquidityRate;
        //the current variable borrow rate. Expressed in ray
        uint128 currentVariableBorrowRate;
        //the current stable borrow rate. Expressed in ray
        uint128 currentStableBorrowRate;
        uint40 lastUpdateTimestamp;
        //tokens addresses
        address aTokenAddress;
        address stableDebtTokenAddress;
        address variableDebtTokenAddress;
        //address of the interest rate strategy
        address interestRateStrategyAddress;
        //the id of the reserve. Represents the position in the list of the active reserves
        uint8 id;
    }

    struct ReserveConfigurationMap {
        //bit 0-15: LTV
        //bit 16-31: Liq. threshold
        //bit 32-47: Liq. bonus
        //bit 48-55: Decimals
        //bit 56: Reserve is active
        //bit 57: reserve is frozen
        //bit 58: borrowing is enabled
        //bit 59: stable rate borrowing enabled
        //bit 60-63: reserved
        //bit 64-79: reserve factor
        uint256 data;
    }

    struct UserConfigurationMap {
        uint256 data;
    }

    enum InterestRateMode {
        NONE,
        STABLE,
        VARIABLE
    }
}

File 29 of 29 : Errors.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity ^0.8.0;

/**
 * @title Errors library
 * @author Aave
 * @notice Defines the error messages emitted by the different contracts of the Aave protocol
 * @dev Error messages prefix glossary:
 *  - VL = ValidationLogic
 *  - MATH = Math libraries
 *  - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken)
 *  - AT = AToken
 *  - SDT = StableDebtToken
 *  - VDT = VariableDebtToken
 *  - LP = LendingPool
 *  - LPAPR = LendingPoolAddressesProviderRegistry
 *  - LPC = LendingPoolConfiguration
 *  - RL = ReserveLogic
 *  - LPCM = LendingPoolCollateralManager
 *  - P = Pausable
 */
library Errors {
    //common errors
    string public constant CALLER_NOT_POOL_ADMIN = "33"; // 'The caller must be the pool admin'
    string public constant BORROW_ALLOWANCE_NOT_ENOUGH = "59"; // User borrows on behalf, but allowance are too small

    //contract specific errors
    string public constant VL_INVALID_AMOUNT = "1"; // 'Amount must be greater than 0'
    string public constant VL_NO_ACTIVE_RESERVE = "2"; // 'Action requires an active reserve'
    string public constant VL_RESERVE_FROZEN = "3"; // 'Action cannot be performed because the reserve is frozen'
    string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = "4"; // 'The current liquidity is not enough'
    string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = "5"; // 'User cannot withdraw more than the available balance'
    string public constant VL_TRANSFER_NOT_ALLOWED = "6"; // 'Transfer cannot be allowed.'
    string public constant VL_BORROWING_NOT_ENABLED = "7"; // 'Borrowing is not enabled'
    string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = "8"; // 'Invalid interest rate mode selected'
    string public constant VL_COLLATERAL_BALANCE_IS_0 = "9"; // 'The collateral balance is 0'
    string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = "10"; // 'Health factor is lesser than the liquidation threshold'
    string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = "11"; // 'There is not enough collateral to cover a new borrow'
    string public constant VL_STABLE_BORROWING_NOT_ENABLED = "12"; // stable borrowing not enabled
    string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = "13"; // collateral is (mostly) the same currency that is being borrowed
    string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = "14"; // 'The requested amount is greater than the max loan size in stable rate mode
    string public constant VL_NO_DEBT_OF_SELECTED_TYPE = "15"; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt'
    string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = "16"; // 'To repay on behalf of an user an explicit amount to repay is needed'
    string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = "17"; // 'User does not have a stable rate loan in progress on this reserve'
    string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = "18"; // 'User does not have a variable rate loan in progress on this reserve'
    string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = "19"; // 'The underlying balance needs to be greater than 0'
    string public constant VL_DEPOSIT_ALREADY_IN_USE = "20"; // 'User deposit is already being used as collateral'
    string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = "21"; // 'User does not have any stable rate loan for this reserve'
    string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = "22"; // 'Interest rate rebalance conditions were not met'
    string public constant LP_LIQUIDATION_CALL_FAILED = "23"; // 'Liquidation call failed'
    string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = "24"; // 'There is not enough liquidity available to borrow'
    string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = "25"; // 'The requested amount is too small for a FlashLoan.'
    string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = "26"; // 'The actual balance of the protocol is inconsistent'
    string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = "27"; // 'The caller of the function is not the lending pool configurator'
    string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = "28";
    string public constant CT_CALLER_MUST_BE_LENDING_POOL = "29"; // 'The caller of this function must be a lending pool'
    string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = "30"; // 'User cannot give allowance to himself'
    string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = "31"; // 'Transferred amount needs to be greater than zero'
    string public constant RL_RESERVE_ALREADY_INITIALIZED = "32"; // 'Reserve has already been initialized'
    string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = "34"; // 'The liquidity of the reserve needs to be 0'
    string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = "35"; // 'The liquidity of the reserve needs to be 0'
    string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = "36"; // 'The liquidity of the reserve needs to be 0'
    string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = "37"; // 'The liquidity of the reserve needs to be 0'
    string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = "38"; // 'The liquidity of the reserve needs to be 0'
    string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = "39"; // 'The liquidity of the reserve needs to be 0'
    string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = "40"; // 'The liquidity of the reserve needs to be 0'
    string public constant LPC_INVALID_CONFIGURATION = "75"; // 'Invalid risk parameters for the reserve'
    string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = "76"; // 'The caller must be the emergency admin'
    string public constant LPAPR_PROVIDER_NOT_REGISTERED = "41"; // 'Provider is not registered'
    string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = "42"; // 'Health factor is not below the threshold'
    string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = "43"; // 'The collateral chosen cannot be liquidated'
    string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = "44"; // 'User did not borrow the specified currency'
    string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = "45"; // "There isn't enough liquidity available to liquidate"
    string public constant LPCM_NO_ERRORS = "46"; // 'No errors'
    string public constant LP_INVALID_FLASHLOAN_MODE = "47"; //Invalid flashloan mode selected
    string public constant MATH_MULTIPLICATION_OVERFLOW = "48";
    string public constant MATH_ADDITION_OVERFLOW = "49";
    string public constant MATH_DIVISION_BY_ZERO = "50";
    string public constant RL_LIQUIDITY_INDEX_OVERFLOW = "51"; //  Liquidity index overflows uint128
    string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = "52"; //  Variable borrow index overflows uint128
    string public constant RL_LIQUIDITY_RATE_OVERFLOW = "53"; //  Liquidity rate overflows uint128
    string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = "54"; //  Variable borrow rate overflows uint128
    string public constant RL_STABLE_BORROW_RATE_OVERFLOW = "55"; //  Stable borrow rate overflows uint128
    string public constant CT_INVALID_MINT_AMOUNT = "56"; //invalid amount to mint
    string public constant LP_FAILED_REPAY_WITH_COLLATERAL = "57";
    string public constant CT_INVALID_BURN_AMOUNT = "58"; //invalid amount to burn
    string public constant LP_FAILED_COLLATERAL_SWAP = "60";
    string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = "61";
    string public constant LP_REENTRANCY_NOT_ALLOWED = "62";
    string public constant LP_CALLER_MUST_BE_AN_ATOKEN = "63";
    string public constant LP_IS_PAUSED = "64"; // 'Pool is paused'
    string public constant LP_NO_MORE_RESERVES_ALLOWED = "65";
    string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = "66";
    string public constant RC_INVALID_LTV = "67";
    string public constant RC_INVALID_LIQ_THRESHOLD = "68";
    string public constant RC_INVALID_LIQ_BONUS = "69";
    string public constant RC_INVALID_DECIMALS = "70";
    string public constant RC_INVALID_RESERVE_FACTOR = "71";
    string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = "72";
    string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = "73";
    string public constant LP_INCONSISTENT_PARAMS_LENGTH = "74";
    string public constant UL_INVALID_INDEX = "77";
    string public constant LP_NOT_CONTRACT = "78";
    string public constant SDT_STABLE_DEBT_OVERFLOW = "79";
    string public constant SDT_BURN_EXCEEDS_BALANCE = "80";

    enum CollateralManagerErrors {
        NO_ERROR,
        NO_COLLATERAL_AVAILABLE,
        COLLATERAL_CANNOT_BE_LIQUIDATED,
        CURRRENCY_NOT_BORROWED,
        HEALTH_FACTOR_ABOVE_THRESHOLD,
        NOT_ENOUGH_LIQUIDITY,
        NO_ACTIVE_RESERVE,
        HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD,
        INVALID_EQUAL_ASSETS_TO_SWAP,
        FROZEN_RESERVE
    }
}

File 30 of 29 : ReserveConfiguration.sol
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity ^0.8.0;

import {Errors} from "./Errors.sol";
import {DataTypes} from "./DataTypes.sol";

/**
 * @title ReserveConfiguration library
 * @author Aave
 * @notice Implements the bitmap logic to handle the reserve configuration
 */
library ReserveConfiguration {
    uint256 constant LTV_MASK =                   0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore
    uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore
    uint256 constant LIQUIDATION_BONUS_MASK =     0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore
    uint256 constant DECIMALS_MASK =              0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore
    uint256 constant ACTIVE_MASK =                0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore
    uint256 constant FROZEN_MASK =                0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore
    uint256 constant BORROWING_MASK =             0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore
    uint256 constant STABLE_BORROWING_MASK =      0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore
    uint256 constant RESERVE_FACTOR_MASK =        0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore

    /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed
    uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;
    uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;
    uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48;
    uint256 constant IS_ACTIVE_START_BIT_POSITION = 56;
    uint256 constant IS_FROZEN_START_BIT_POSITION = 57;
    uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58;
    uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59;
    uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64;

    uint256 constant MAX_VALID_LTV = 65535;
    uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;
    uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535;
    uint256 constant MAX_VALID_DECIMALS = 255;
    uint256 constant MAX_VALID_RESERVE_FACTOR = 65535;

    /**
     * @dev Sets the Loan to Value of the reserve
     * @param self The reserve configuration
     * @param ltv the new ltv
     **/
    function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure {
        require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV);

        self.data = (self.data & LTV_MASK) | ltv;
    }

    /**
     * @dev Gets the Loan to Value of the reserve
     * @param self The reserve configuration
     * @return The loan to value
     **/
    function getLtv(DataTypes.ReserveConfigurationMap storage self)
        internal
        view
        returns (uint256)
    {
        return self.data & ~LTV_MASK;
    }

    /**
     * @dev Sets the liquidation threshold of the reserve
     * @param self The reserve configuration
     * @param threshold The new liquidation threshold
     **/
    function setLiquidationThreshold(
        DataTypes.ReserveConfigurationMap memory self,
        uint256 threshold
    ) internal pure {
        require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD);

        self.data =
            (self.data & LIQUIDATION_THRESHOLD_MASK) |
            (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);
    }

    /**
     * @dev Gets the liquidation threshold of the reserve
     * @param self The reserve configuration
     * @return The liquidation threshold
     **/
    function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self)
        internal
        view
        returns (uint256)
    {
        return
            (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;
    }

    /**
     * @dev Sets the liquidation bonus of the reserve
     * @param self The reserve configuration
     * @param bonus The new liquidation bonus
     **/
    function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus)
        internal
        pure
    {
        require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS);

        self.data =
            (self.data & LIQUIDATION_BONUS_MASK) |
            (bonus << LIQUIDATION_BONUS_START_BIT_POSITION);
    }

    /**
     * @dev Gets the liquidation bonus of the reserve
     * @param self The reserve configuration
     * @return The liquidation bonus
     **/
    function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self)
        internal
        view
        returns (uint256)
    {
        return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;
    }

    /**
     * @dev Sets the decimals of the underlying asset of the reserve
     * @param self The reserve configuration
     * @param decimals The decimals
     **/
    function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals)
        internal
        pure
    {
        require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS);

        self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION);
    }

    /**
     * @dev Gets the decimals of the underlying asset of the reserve
     * @param self The reserve configuration
     * @return The decimals of the asset
     **/
    function getDecimals(DataTypes.ReserveConfigurationMap storage self)
        internal
        view
        returns (uint256)
    {
        return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION;
    }

    /**
     * @dev Sets the active state of the reserve
     * @param self The reserve configuration
     * @param active The active state
     **/
    function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure {
        self.data =
            (self.data & ACTIVE_MASK) |
            (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);
    }

    /**
     * @dev Gets the active state of the reserve
     * @param self The reserve configuration
     * @return The active state
     **/
    function getActive(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {
        return (self.data & ~ACTIVE_MASK) != 0;
    }

    /**
     * @dev Sets the frozen state of the reserve
     * @param self The reserve configuration
     * @param frozen The frozen state
     **/
    function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure {
        self.data =
            (self.data & FROZEN_MASK) |
            (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);
    }

    /**
     * @dev Gets the frozen state of the reserve
     * @param self The reserve configuration
     * @return The frozen state
     **/
    function getFrozen(DataTypes.ReserveConfigurationMap storage self)
        internal
        view
        returns (bool)
    {
        return (self.data & ~FROZEN_MASK) != 0;
    }

    /**
     * @dev Enables or disables borrowing on the reserve
     * @param self The reserve configuration
     * @param enabled True if the borrowing needs to be enabled, false otherwise
     **/
    function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled)
        internal
        pure
    {
        self.data =
            (self.data & BORROWING_MASK) |
            (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION);
    }

    /**
     * @dev Gets the borrowing state of the reserve
     * @param self The reserve configuration
     * @return The borrowing state
     **/
    function getBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self)
        internal
        pure
        returns (bool)
    {
        return (self.data & ~BORROWING_MASK) != 0;
    }

    /**
     * @dev Enables or disables stable rate borrowing on the reserve
     * @param self The reserve configuration
     * @param enabled True if the stable rate borrowing needs to be enabled, false otherwise
     **/
    function setStableRateBorrowingEnabled(
        DataTypes.ReserveConfigurationMap memory self,
        bool enabled
    ) internal pure {
        self.data =
            (self.data & STABLE_BORROWING_MASK) |
            (uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION);
    }

    /**
     * @dev Gets the stable rate borrowing state of the reserve
     * @param self The reserve configuration
     * @return The stable rate borrowing state
     **/
    function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self)
        internal
        view
        returns (bool)
    {
        return (self.data & ~STABLE_BORROWING_MASK) != 0;
    }

    /**
     * @dev Sets the reserve factor of the reserve
     * @param self The reserve configuration
     * @param reserveFactor The reserve factor
     **/
    function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor)
        internal
        pure
    {
        require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR);

        self.data =
            (self.data & RESERVE_FACTOR_MASK) |
            (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION);
    }

    /**
     * @dev Gets the reserve factor of the reserve
     * @param self The reserve configuration
     * @return The reserve factor
     **/
    function getReserveFactor(DataTypes.ReserveConfigurationMap storage self)
        internal
        view
        returns (uint256)
    {
        return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION;
    }

    /**
     * @dev Gets the configuration flags of the reserve
     * @param self The reserve configuration
     * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled
     **/
    function getFlags(DataTypes.ReserveConfigurationMap storage self)
        internal
        view
        returns (
            bool,
            bool,
            bool,
            bool
        )
    {
        uint256 dataLocal = self.data;

        return (
            (dataLocal & ~ACTIVE_MASK) != 0,
            (dataLocal & ~FROZEN_MASK) != 0,
            (dataLocal & ~BORROWING_MASK) != 0,
            (dataLocal & ~STABLE_BORROWING_MASK) != 0
        );
    }

    /**
     * @dev Gets the configuration paramters of the reserve
     * @param self The reserve configuration
     * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals
     **/
    function getParams(DataTypes.ReserveConfigurationMap storage self)
        internal
        view
        returns (
            uint256,
            uint256,
            uint256,
            uint256,
            uint256
        )
    {
        uint256 dataLocal = self.data;

        return (
            dataLocal & ~LTV_MASK,
            (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,
            (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,
            (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,
            (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION
        );
    }

    /**
     * @dev Gets the configuration paramters of the reserve from a memory object
     * @param self The reserve configuration
     * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals
     **/
    function getParamsMemory(DataTypes.ReserveConfigurationMap memory self)
        internal
        pure
        returns (
            uint256,
            uint256,
            uint256,
            uint256,
            uint256
        )
    {
        return (
            self.data & ~LTV_MASK,
            (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,
            (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,
            (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,
            (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION
        );
    }

    /**
     * @dev Gets the configuration flags of the reserve from a memory object
     * @param self The reserve configuration
     * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled
     **/
    function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self)
        internal
        pure
        returns (
            bool,
            bool,
            bool,
            bool
        )
    {
        return (
            (self.data & ~ACTIVE_MASK) != 0,
            (self.data & ~FROZEN_MASK) != 0,
            (self.data & ~BORROWING_MASK) != 0,
            (self.data & ~STABLE_BORROWING_MASK) != 0
        );
    }
}

Settings
{
  "remappings": [
    "@aave/core-v3/=lib/morpho-utils/lib/aave-v3-core/",
    "@forge-std/=lib/forge-std/src/",
    "@morpho-dao/morpho-data-structures/=lib/morpho-data-structures/contracts/",
    "@morpho-dao/morpho-utils/=lib/morpho-utils/src/",
    "@openzeppelin/=node_modules/@openzeppelin/",
    "@rari-capital/solmate/=lib/solmate/",
    "aave-v3-core/=lib/morpho-utils/lib/aave-v3-core/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "forge-std/=lib/forge-std/src/",
    "hardhat-deploy/=node_modules/hardhat-deploy/",
    "hardhat/=node_modules/hardhat/",
    "morpho-utils/=lib/morpho-utils/src/",
    "openzeppelin-contracts/=lib/morpho-utils/lib/openzeppelin-contracts/",
    "solmate/=lib/solmate/src/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "london",
  "debug": {
    "revertStrings": "default"
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"address","name":"_morpho","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"DEFAULT_LIQUIDATION_CLOSE_FACTOR","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"HEALTH_FACTOR_LIQUIDATION_THRESHOLD","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ST_ETH","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ST_ETH_BASE_REBASE_INDEX","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"addressesProvider","outputs":[{"internalType":"contract ILendingPoolAddressesProvider","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"},{"internalType":"address","name":"_poolTokenBorrowed","type":"address"},{"internalType":"address","name":"_poolTokenCollateral","type":"address"}],"name":"computeLiquidationRepayAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"}],"name":"getAdvancedMarketData","outputs":[{"components":[{"internalType":"uint256","name":"p2pSupplyIndex","type":"uint256"},{"internalType":"uint256","name":"p2pBorrowIndex","type":"uint256"},{"internalType":"uint256","name":"poolSupplyIndex","type":"uint256"},{"internalType":"uint256","name":"poolBorrowIndex","type":"uint256"}],"internalType":"struct Types.Indexes","name":"indexes","type":"tuple"},{"internalType":"uint32","name":"lastUpdateTimestamp","type":"uint32"},{"internalType":"uint256","name":"p2pSupplyDelta","type":"uint256"},{"internalType":"uint256","name":"p2pBorrowDelta","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getAllMarkets","outputs":[{"internalType":"address[]","name":"marketsCreated","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"}],"name":"getAverageBorrowRatePerYear","outputs":[{"internalType":"uint256","name":"avgBorrowRatePerYear","type":"uint256"},{"internalType":"uint256","name":"p2pBorrowAmount","type":"uint256"},{"internalType":"uint256","name":"poolBorrowAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"}],"name":"getAverageSupplyRatePerYear","outputs":[{"internalType":"uint256","name":"avgSupplyRatePerYear","type":"uint256"},{"internalType":"uint256","name":"p2pSupplyAmount","type":"uint256"},{"internalType":"uint256","name":"poolSupplyAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"},{"internalType":"address","name":"_user","type":"address"}],"name":"getCurrentBorrowBalanceInOf","outputs":[{"internalType":"uint256","name":"balanceInP2P","type":"uint256"},{"internalType":"uint256","name":"balanceOnPool","type":"uint256"},{"internalType":"uint256","name":"totalBalance","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"}],"name":"getCurrentP2PBorrowIndex","outputs":[{"internalType":"uint256","name":"p2pBorrowIndex","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"}],"name":"getCurrentP2PSupplyIndex","outputs":[{"internalType":"uint256","name":"p2pSupplyIndex","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"},{"internalType":"address","name":"_user","type":"address"}],"name":"getCurrentSupplyBalanceInOf","outputs":[{"internalType":"uint256","name":"balanceInP2P","type":"uint256"},{"internalType":"uint256","name":"balanceOnPool","type":"uint256"},{"internalType":"uint256","name":"totalBalance","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"},{"internalType":"address","name":"_user","type":"address"}],"name":"getCurrentUserBorrowRatePerYear","outputs":[{"internalType":"uint256","name":"borrowRatePerYear","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"},{"internalType":"address","name":"_user","type":"address"}],"name":"getCurrentUserSupplyRatePerYear","outputs":[{"internalType":"uint256","name":"supplyRatePerYear","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"}],"name":"getEnteredMarkets","outputs":[{"internalType":"address[]","name":"enteredMarkets","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"}],"name":"getIndexes","outputs":[{"components":[{"internalType":"uint256","name":"p2pSupplyIndex","type":"uint256"},{"internalType":"uint256","name":"p2pBorrowIndex","type":"uint256"},{"internalType":"uint256","name":"poolSupplyIndex","type":"uint256"},{"internalType":"uint256","name":"poolBorrowIndex","type":"uint256"}],"internalType":"struct Types.Indexes","name":"indexes","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"}],"name":"getMainMarketData","outputs":[{"internalType":"uint256","name":"avgSupplyRatePerYear","type":"uint256"},{"internalType":"uint256","name":"avgBorrowRatePerYear","type":"uint256"},{"internalType":"uint256","name":"p2pSupplyAmount","type":"uint256"},{"internalType":"uint256","name":"p2pBorrowAmount","type":"uint256"},{"internalType":"uint256","name":"poolSupplyAmount","type":"uint256"},{"internalType":"uint256","name":"poolBorrowAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"}],"name":"getMarketConfiguration","outputs":[{"internalType":"address","name":"underlying","type":"address"},{"internalType":"bool","name":"isCreated","type":"bool"},{"internalType":"bool","name":"isP2PDisabled","type":"bool"},{"internalType":"bool","name":"isPaused","type":"bool"},{"internalType":"bool","name":"isPartiallyPaused","type":"bool"},{"internalType":"uint16","name":"reserveFactor","type":"uint16"},{"internalType":"uint16","name":"p2pIndexCursor","type":"uint16"},{"internalType":"uint256","name":"loanToValue","type":"uint256"},{"internalType":"uint256","name":"liquidationThreshold","type":"uint256"},{"internalType":"uint256","name":"liquidationBonus","type":"uint256"},{"internalType":"uint256","name":"decimals","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"}],"name":"getMarketPauseStatus","outputs":[{"components":[{"internalType":"bool","name":"isSupplyPaused","type":"bool"},{"internalType":"bool","name":"isBorrowPaused","type":"bool"},{"internalType":"bool","name":"isWithdrawPaused","type":"bool"},{"internalType":"bool","name":"isRepayPaused","type":"bool"},{"internalType":"bool","name":"isLiquidateCollateralPaused","type":"bool"},{"internalType":"bool","name":"isLiquidateBorrowPaused","type":"bool"},{"internalType":"bool","name":"isDeprecated","type":"bool"}],"internalType":"struct Types.MarketPauseStatus","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"},{"internalType":"address","name":"_user","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"getNextUserBorrowRatePerYear","outputs":[{"internalType":"uint256","name":"nextBorrowRatePerYear","type":"uint256"},{"internalType":"uint256","name":"balanceInP2P","type":"uint256"},{"internalType":"uint256","name":"balanceOnPool","type":"uint256"},{"internalType":"uint256","name":"totalBalance","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"},{"internalType":"address","name":"_user","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"getNextUserSupplyRatePerYear","outputs":[{"internalType":"uint256","name":"nextSupplyRatePerYear","type":"uint256"},{"internalType":"uint256","name":"balanceInP2P","type":"uint256"},{"internalType":"uint256","name":"balanceOnPool","type":"uint256"},{"internalType":"uint256","name":"totalBalance","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"}],"name":"getRatesPerYear","outputs":[{"internalType":"uint256","name":"p2pSupplyRate","type":"uint256"},{"internalType":"uint256","name":"p2pBorrowRate","type":"uint256"},{"internalType":"uint256","name":"poolSupplyRate","type":"uint256"},{"internalType":"uint256","name":"poolBorrowRate","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTotalBorrow","outputs":[{"internalType":"uint256","name":"p2pBorrowAmount","type":"uint256"},{"internalType":"uint256","name":"poolBorrowAmount","type":"uint256"},{"internalType":"uint256","name":"totalBorrowAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"}],"name":"getTotalMarketBorrow","outputs":[{"internalType":"uint256","name":"p2pBorrowAmount","type":"uint256"},{"internalType":"uint256","name":"poolBorrowAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"}],"name":"getTotalMarketSupply","outputs":[{"internalType":"uint256","name":"p2pSupplyAmount","type":"uint256"},{"internalType":"uint256","name":"poolSupplyAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTotalSupply","outputs":[{"internalType":"uint256","name":"p2pSupplyAmount","type":"uint256"},{"internalType":"uint256","name":"poolSupplyAmount","type":"uint256"},{"internalType":"uint256","name":"totalSupplyAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"}],"name":"getUserBalanceStates","outputs":[{"components":[{"internalType":"uint256","name":"collateralEth","type":"uint256"},{"internalType":"uint256","name":"borrowableEth","type":"uint256"},{"internalType":"uint256","name":"maxDebtEth","type":"uint256"},{"internalType":"uint256","name":"debtEth","type":"uint256"}],"internalType":"struct Types.LiquidityData","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"}],"name":"getUserHealthFactor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"},{"internalType":"address","name":"_poolToken","type":"address"},{"internalType":"uint256","name":"_withdrawnAmount","type":"uint256"},{"internalType":"uint256","name":"_borrowedAmount","type":"uint256"}],"name":"getUserHypotheticalBalanceStates","outputs":[{"components":[{"internalType":"uint256","name":"collateralEth","type":"uint256"},{"internalType":"uint256","name":"borrowableEth","type":"uint256"},{"internalType":"uint256","name":"maxDebtEth","type":"uint256"},{"internalType":"uint256","name":"debtEth","type":"uint256"}],"internalType":"struct Types.LiquidityData","name":"liquidityData","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"},{"internalType":"address","name":"_poolToken","type":"address"},{"internalType":"uint256","name":"_withdrawnAmount","type":"uint256"},{"internalType":"uint256","name":"_borrowedAmount","type":"uint256"}],"name":"getUserHypotheticalHealthFactor","outputs":[{"internalType":"uint256","name":"healthFactor","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"},{"internalType":"address","name":"_poolToken","type":"address"},{"internalType":"contract IPriceOracleGetter","name":"_oracle","type":"address"}],"name":"getUserLiquidityDataForAsset","outputs":[{"components":[{"internalType":"uint256","name":"decimals","type":"uint256"},{"internalType":"uint256","name":"tokenUnit","type":"uint256"},{"internalType":"uint256","name":"liquidationThreshold","type":"uint256"},{"internalType":"uint256","name":"ltv","type":"uint256"},{"internalType":"uint256","name":"underlyingPrice","type":"uint256"},{"internalType":"uint256","name":"collateralEth","type":"uint256"},{"internalType":"uint256","name":"debtEth","type":"uint256"}],"internalType":"struct Types.AssetLiquidityData","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"},{"internalType":"address","name":"_poolToken","type":"address"}],"name":"getUserMaxCapacitiesForAsset","outputs":[{"internalType":"uint256","name":"withdrawable","type":"uint256"},{"internalType":"uint256","name":"borrowable","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"}],"name":"isLiquidatable","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"},{"internalType":"address","name":"_poolToken","type":"address"}],"name":"isLiquidatable","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolToken","type":"address"}],"name":"isMarketCreated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"isMarketCreatedAndNotPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"isMarketCreatedAndNotPausedNorPartiallyPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"morpho","outputs":[{"internalType":"contract IMorpho","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pool","outputs":[{"internalType":"contract ILendingPool","name":"","type":"address"}],"stateMutability":"view","type":"function"}]

6101006040523480156200001257600080fd5b5060405162004a6338038062004a638339810160408190526200003591620001cd565b6001600160a01b03811660a0819052604080516316f0115b60e01b815290518392916316f0115b9160048083019260209291908290030181865afa15801562000082573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620000a89190620001cd565b6001600160a01b031660e0816001600160a01b03168152505060a0516001600160a01b031663c72c4d106040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000102573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620001289190620001cd565b6001600160a01b031660c0816001600160a01b03168152505060a0516001600160a01b031663a74e472b6040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000182573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620001a89190620001f4565b608052506200020e9050565b6001600160a01b0381168114620001ca57600080fd5b50565b600060208284031215620001e057600080fd5b8151620001ed81620001b4565b9392505050565b6000602082840312156200020757600080fd5b5051919050565b60805160a05160c05160e0516146cb62000398600039600081816102c001528181610a8a01528181610e9f015281816110e201528181611d5601528181612066015281816124b7015281816127a6015281816129f10152818161362b0152818161391e01526139ab01526000818161061d0152818161079401528181610b2c01528181611f0c015281816121a0015261264c01526000818161070201528181610dbe01528181611016015281816111fd0152818161132f015281816113f5015281816114e80152818161163a01528181611747015281816117ed0152818161196301528181611a4b01528181611b5101528181611bf701528181611e8201528181612226015281816122cf015281816125c2015281816128ef01528181612b6b01528181612bf701528181612d1a01528181612da701528181612e3901528181612f1d01528181613025015281816132e10152818161340a0152818161374f015281816137f601526138cb01526000818161058b01528181613ac70152613af701526146cb6000f3fe608060405234801561001057600080fd5b50600436106102535760003560e01c8063a480b7ed11610146578063cd26e92d116100c3578063d89aaaf511610087578063d89aaaf5146106ea578063d8fbc833146106fd578063e37f8a7e14610724578063f0702fcb1461072c578063f286d9b51461073f578063f657af411461075257600080fd5b8063cd26e92d14610336578063d2a87cf81461063f578063d350964514610652578063d61bb596146106bb578063d664f72c146106ce57600080fd5b8063bcbb2bf21161010a578063bcbb2bf2146105db578063c3525c28146105ee578063c46fcbfc146105fd578063c4e41b2214610610578063c72c4d101461061857600080fd5b8063a480b7ed14610573578063a74e472b14610586578063a9a97718146105ad578063b0772d0b146105c0578063b7013b46146105c857600080fd5b8063576f67ed116101d4578063790bf72511610198578063790bf725146104be5780637b1ab592146104d157806385a229321461052d5780638ccb720b14610540578063967f1aaf1461056057600080fd5b8063576f67ed1461039e5780635a208d52146103d15780635de72f6a1461044b57806371cbfc981461048b578063762fb6891461049e57600080fd5b8063338346d21161021b578063338346d21461031b57806336cd097c146103365780633737c7141461034a57806339296cf9146103785780633966a28b1461038b57600080fd5b8063042e02cf14610258578063140680b3146102805780631419cfe1146102a857806316f0115b146102bb5780632af8970e146102fa575b600080fd5b61026b610266366004613d21565b610772565b60405190151581526020015b60405180910390f35b61029361028e366004613d3e565b61078d565b60408051928352602083019190915201610277565b6102936102b6366004613d21565b610a0b565b6102e27f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b039091168152602001610277565b61030d610308366004613d77565b610a22565b604051908152602001610277565b6102e273ae7ab96520de3a18e5e111b5eaab095312d7fe8481565b61026b610344366004613d21565b50600090565b61035d610358366004613d3e565b610d54565b60408051938452602084019290925290820152606001610277565b61030d610386366004613d3e565b610d72565b61026b610399366004613d3e565b610d9c565b6103b16103ac366004613d21565b610e5f565b604080519485526020850193909352918301526060820152608001610277565b6103e46103df366004613d21565b611002565b604080516001600160a01b03909c168c5299151560208c0152971515988a01989098529415156060890152921515608088015261ffff91821660a08801521660c086015260e085015261010084015261012083019190915261014082015261016001610277565b61045e610459366004613d21565b61115c565b604080519687526020870195909552938501929092526060840152608083015260a082015260c001610277565b61030d610499366004613d21565b61118f565b6104b16104ac366004613d21565b61119f565b6040516102779190613dc2565b61026b6104cc366004613d21565b6111db565b6104e46104df366004613d21565b611274565b60408051855181526020808701519082015285820151918101919091526060948501519481019490945263ffffffff909216608084015260a083015260c082015260e001610277565b61030d61053b366004613ded565b6113aa565b61055361054e366004613d21565b6113ef565b6040516102779190613e33565b6103b161056e366004613e80565b6115f4565b61035d610581366004613d3e565b61193a565b61030d7f000000000000000000000000000000000000000000000000000000000000000081565b61030d6105bb366004613d21565b611949565b61055361195f565b61030d6105d6366004613d21565b6119ec565b6103b16105e9366004613e80565b611a05565b61030d670de0b6b3a764000081565b61035d61060b366004613d21565b611d18565b61035d611e7a565b6102e27f000000000000000000000000000000000000000000000000000000000000000081565b61029361064d366004613d21565b612117565b610665610660366004613d77565b612123565b6040516102779190600060e082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015292915050565b6104b16106c9366004613ded565b612171565b6106d761138881565b60405161ffff9091168152602001610277565b61035d6106f8366004613d21565b612479565b6102e27f000000000000000000000000000000000000000000000000000000000000000081565b61035d6125ba565b61030d61073a366004613d3e565b612842565b6104b161074d366004613d21565b612862565b610765610760366004613d21565b61289b565b6040516102779190613ec1565b6000670de0b6b3a76400006107868361118f565b1092915050565b60008060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663fca513a86040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107f0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108149190613f30565b9050600061082186612862565b90506000610830878785612123565b9050600082606001511180156108685750670de0b6b3a76400006108658360600151846040015161295a90919063ffffffff16565b11155b1561087c5760008094509450505050610a04565b6000866001600160a01b031663b16a19de6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108e09190613f30565b6040516370a0823160e01b81526001600160a01b03898116600483015291909116906370a0823190602401602060405180830381865afa158015610928573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061094c9190613f4d565b90508260200151836060015110156109a25761099f8183608001518460200151866060015187602001516109809190613f7c565b61098a9190613f93565b6109949190613fb2565b808218908211021890565b94505b6109bf81836080015184602001518560a0015161098a9190613f93565b6040830151909650156109ff576109fc86836080015184602001516109808660400151886060015189604001516109f69190613f7c565b9061298b565b95505b505050505b9250929050565b600080610a17836129b0565b909590945092505050565b6000610a2e8484610d9c565b610a3a57506000610d4d565b600080610a478487612a83565b935050509150600080610a5a8789612ac4565b60405163c44b11f760e01b81526001600160a01b038981166004830152949650909450600093849350610b2192507f0000000000000000000000000000000000000000000000000000000000000000169063c44b11f7906024015b602060405180830381865afa158015610ad2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610af691906140aa565b5161ffff80821692601083901c821692602081901c831692603082901c60ff169260409290921c1690565b5093509350505060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663fca513a86040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b88573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bac9190613f30565b60405163b3596f0760e01b81526001600160a01b03878116600483015291925060009183169063b3596f0790602401602060405180830381865afa158015610bf8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c1c9190613f4d565b60405163b3596f0760e01b81526001600160a01b038a8116600483015291925060009184169063b3596f0790602401602060405180830381865afa158015610c68573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c8c9190613f4d565b9050610d41610d3586610ca087600a6141aa565b610caa9086613f93565b8a6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ce8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d0c91906141c7565b610d1790600a6141e2565b610d21868e613f93565b610d2b9190613f93565b6109f69190613fb2565b61099488611388612af6565b99505050505050505050505b9392505050565b6000806000610d638585612ac4565b91989097509095509350505050565b6000806000610d818585612ac4565b509250925050610d92858383612b1a565b5095945050505050565b604051630de2bdf560e41b81526001600160a01b0382811660048301526000917f00000000000000000000000000000000000000000000000000000000000000009091169063de2bdf509060240160e060405180830381865afa158015610e07573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e2b9190614201565b60c001518015610e405750610e408383612b49565b15610e4d57506001610e59565b610e5683610772565b90505b92915050565b6000806000806000806000610e7388612c6c565b82516040516335ea6a7560e01b81526001600160a01b03918216600482015293965091945092506000917f0000000000000000000000000000000000000000000000000000000000000000909116906335ea6a759060240161018060405180830381865afa158015610ee9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f0d91906142bf565b905080606001516001600160801b0316955080608001516001600160801b03169450610f9160405180610100016040528088815260200187815260200184604001518152602001846000015181526020018560000151815260200185604001518152602001866040015161ffff168152602001866020015161ffff168152506130bd565b9750610ff560405180610100016040528088815260200187815260200184606001518152602001846020015181526020018560200151815260200185606001518152602001866040015161ffff168152602001866020015161ffff168152506131d0565b9650505050509193509193565b6000806000806000806000806000806000807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316639f382f6a8e6040518263ffffffff1660e01b815260040161106f91906001600160a01b0391909116815260200190565b60e060405180830381865afa15801561108c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110b091906143be565b905080600001519b5080606001519a508060c0015199506000985060009750806020015196508060400151955061113b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663c44b11f78e6040518263ffffffff1660e01b8152600401610ab591906001600160a01b0391909116815260200190565b50809550819650829750839850505050505091939597999b90929496989a50565b60008060008060008061116e87612479565b9197509450915061117e87611d18565b979991985094969495509193925050565b6000610e598260008060006113aa565b6111ca6040518060800160405280600081526020016000815260200160008152602001600081525090565b6111d382612c6c565b949350505050565b604051634f9c17b560e11b81526001600160a01b0382811660048301526000917f000000000000000000000000000000000000000000000000000000000000000090911690639f382f6a9060240160e060405180830381865afa158015611246573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061126a91906143be565b6060015192915050565b61129f6040518060800160405280600081526020016000815260200160008152602001600081525090565b60008060006112cf6040518060800160405280600081526020016000815260200160008152602001600081525090565b6112d886612c6c565b604081015182519198509193506112f092509061327c565b925061130d8560600151826020015161327c90919063ffffffff16565b604051631987357f60e21b81526001600160a01b0388811660048301529193507f00000000000000000000000000000000000000000000000000000000000000009091169063661cd5fc90602401606060405180830381865afa158015611378573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061139c9190614419565b600001519350509193509193565b6000806113b986868686612171565b905080606001516000036113d2576000199150506111d3565b606081015160408201516113e59161295a565b9695505050505050565b606060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663a1d6000c6040518163ffffffff1660e01b8152600401600060405180830381865afa158015611451573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526114799190810190614490565b805190915060008167ffffffffffffffff81111561149957611499613fd4565b6040519080825280602002602001820160405280156114c2578160200160208202803683370190505b50604051630bc45d1960e41b81526001600160a01b0387811660048301529195506000917f0000000000000000000000000000000000000000000000000000000000000000169063bc45d19090602401602060405180830381865afa15801561152f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115539190613f4d565b905060005b838110156115e8576115838286838151811061157657611576614542565b60200260200101516132bd565b156115d85784818151811061159a5761159a614542565b60200260200101518684815181106115b4576115b4614542565b6001600160a01b03909216602092830291909101909101526115d583614558565b92505b6115e181614558565b9050611558565b50508352509092915050565b60008060008060008060006116088a612c6c565b60405163251d5d2b60e21b81526001600160a01b038e811660048301528d8116602483015293965091945092506000917f0000000000000000000000000000000000000000000000000000000000000000169063947574ac906044016040805180830381865afa158015611680573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116a491906145c0565b90506000891180156116b65750825115155b1561171657604082015183516000916116dd916116d29161327c565b8b8111818d18021890565b90506116f683602001518261335f90919063ffffffff16565b825183906117059083906145dc565b905250611712818b613f7c565b9950505b60008911801561172857508360c00151155b156118c657604051635acff02760e01b81526000906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690635acff0279061177f908f906001906004016145f4565b602060405180830381865afa15801561179c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117c09190613f30565b6040516339407b4160e21b81526001600160a01b038e8116600483015280831660248301529192506000917f0000000000000000000000000000000000000000000000000000000000000000169063e501ed04906044016040805180830381865afa158015611833573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061185791906145c0565b60200151905080156118c357600061188a61187f86604001518461327c90919063ffffffff16565b8d8111818f18021890565b90506118a385602001518261335f90919063ffffffff16565b845185906118b29083906145dc565b9052506118bf818d613f7c565b9b50505b50505b88156118f15760608201516118dc908a9061335f565b816020018181516118ed91906145dc565b9052505b606082015160208201516119049161327c565b60208301518251919750611918919061327c565b96506119258b8888612b1a565b80965081995050505050505093509350935093565b6000806000610d638585612a83565b60008061195583612c6c565b5195945050505050565b60607f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663a1d6000c6040518163ffffffff1660e01b8152600401600060405180830381865afa1580156119bf573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526119e79190810190614490565b905090565b6000806119f883612c6c565b6020015195945050505050565b6000806000806000806000611a198a612c6c565b6040516339407b4160e21b81526001600160a01b038e811660048301528d8116602483015293965091945092506000917f0000000000000000000000000000000000000000000000000000000000000000169063e501ed04906044016040805180830381865afa158015611a91573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ab591906145c0565b9050600089118015611acb575060008360200151115b15611b20576000611af06116d28460600151866020015161327c90919063ffffffff16565b8351909150611b0090829061335f565b82518390611b0f9083906145dc565b905250611b1c818b613f7c565b9950505b600089118015611b3257508360c00151155b15611cbc57604051635acff02760e01b81526000906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690635acff02790611b89908f906003906004016145f4565b602060405180830381865afa158015611ba6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bca9190613f30565b60405163251d5d2b60e21b81526001600160a01b038e8116600483015280831660248301529192506000917f0000000000000000000000000000000000000000000000000000000000000000169063947574ac906044016040805180830381865afa158015611c3d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c6191906145c0565b6020015190508015611cb9576000611c8961187f86606001518461327c90919063ffffffff16565b8551909150611c9990829061335f565b84518590611ca89083906145dc565b905250611cb5818d613f7c565b9b50505b50505b8815611ce7576040820151611cd2908a9061335f565b81602001818151611ce391906145dc565b9052505b60408201516020820151611cfa9161327c565b82518251919750611d0b919061327c565b96506119258b8888613396565b600080600080600080611d2a87612c6c565b82516040516335ea6a7560e01b81526001600160a01b03918216600482015293965091945092506000917f0000000000000000000000000000000000000000000000000000000000000000909116906335ea6a759060240161018060405180830381865afa158015611da0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dc491906142bf565b9050600081608001516001600160801b031690506000611e4360405180610100016040528085606001516001600160801b0316815260200184815260200186606001518152602001866020015181526020016000815260200160008152602001886040015161ffff168152602001886020015161ffff168152506131d0565b9050611e598385602001518660600151886133b7565b9098509650611e6a81838a8a613496565b509a979950959750505050505050565b6000806000807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663a1d6000c6040518163ffffffff1660e01b8152600401600060405180830381865afa158015611ede573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052611f069190810190614490565b905060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663fca513a86040518163ffffffff1660e01b8152600401602060405180830381865afa158015611f68573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f8c9190613f30565b825190915060005b81811015612102576000848281518110611fb057611fb0614542565b602002602001015190506000806000611fc884613502565b60405163b3596f0760e01b81526001600160a01b038085166004830152939650919450925060009189169063b3596f0790602401602060405180830381865afa158015612019573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061203d9190613f4d565b60405163c44b11f760e01b81526001600160a01b038681166004830152919250600091612097917f00000000000000000000000000000000000000000000000000000000000000009091169063c44b11f790602401610ab5565b509350505050600081600a6120ac91906141aa565b9050806120b98487613f93565b6120c39190613fb2565b6120cd908f6145dc565b9d50806120da8486613f93565b6120e49190613fb2565b6120ee908e6145dc565b9c5087600101975050505050505050611f94565b5061210d85876145dc565b9350505050909192565b600080610a1783613502565b6121636040518060e00160405280600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b6111d3848484600080613542565b61219c6040518060800160405280600081526020016000815260200160008152602001600081525090565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663fca513a86040518163ffffffff1660e01b8152600401602060405180830381865afa1580156121fc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122209190613f30565b905060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663a1d6000c6040518163ffffffff1660e01b8152600401600060405180830381865afa158015612282573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526122aa9190810190614490565b604051630bc45d1960e41b81526001600160a01b0389811660048301529192506000917f0000000000000000000000000000000000000000000000000000000000000000169063bc45d19090602401602060405180830381865afa158015612316573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061233a9190613f4d565b825190915060005b8181101561246c57600084828151811061235e5761235e614542565b6020026020010151905061237284826132bd565b1580156123915750806001600160a01b03168a6001600160a01b031614155b1561239c575061245c565b6000816001600160a01b03168b6001600160a01b0316146123ca576123c58c8389600080613542565b6123d7565b6123d78c83898d8d613542565b90508060a00151886000018181516123ef91906145dc565b905250606081015160a082015161240591612af6565b8860200181815161241691906145dc565b905250604081015160a082015161242c91612af6565b8860400181815161243d91906145dc565b90525060c08101516060890180516124569083906145dc565b90525050505b61246581614558565b9050612342565b5050505050949350505050565b60008060008060008061248b87612c6c565b82516040516335ea6a7560e01b81526001600160a01b03918216600482015293965091945092506000917f0000000000000000000000000000000000000000000000000000000000000000909116906335ea6a759060240161018060405180830381865afa158015612501573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061252591906142bf565b9050600081606001516001600160801b0316905060006125a460405180610100016040528084815260200185608001516001600160801b0316815260200186604001518152602001866000015181526020016000815260200160008152602001886040015161ffff168152602001886020015161ffff168152506130bd565b9050611e598a8560000151866040015188613714565b6000806000807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663a1d6000c6040518163ffffffff1660e01b8152600401600060405180830381865afa15801561261e573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526126469190810190614490565b905060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663fca513a86040518163ffffffff1660e01b8152600401602060405180830381865afa1580156126a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126cc9190613f30565b825190915060005b818110156121025760008482815181106126f0576126f0614542565b602002602001015190506000806000612708846129b0565b60405163b3596f0760e01b81526001600160a01b038085166004830152939650919450925060009189169063b3596f0790602401602060405180830381865afa158015612759573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061277d9190613f4d565b60405163c44b11f760e01b81526001600160a01b0386811660048301529192506000916127d7917f00000000000000000000000000000000000000000000000000000000000000009091169063c44b11f790602401610ab5565b509350505050600081600a6127ec91906141aa565b9050806127f98487613f93565b6128039190613fb2565b61280d908f6145dc565b9d508061281a8486613f93565b6128249190613fb2565b61282e908e6145dc565b9c50876001019750505050505050506126d4565b60008060006128518585612a83565b509250925050610d92858383613396565b61288d6040518060800160405280600081526020016000815260200160008152602001600081525090565b610e59826000806000612171565b6040805160e081018252600080825260208201819052818301819052606082018190526080820181905260a0820181905260c08201529051630de2bdf560e41b81526001600160a01b0383811660048301527f0000000000000000000000000000000000000000000000000000000000000000169063de2bdf509060240160e060405180830381865afa158015612936573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e599190614201565b60028104670de0b6b3a7640000811904831115820261297857600080fd5b670de0b6b3a76400009092029091010490565b6002810461271081190483111582026129a357600080fd5b6127109092029091010490565b6000806000806000806129c287612c6c565b82516040516335ea6a7560e01b81526001600160a01b038083166004830152919a5093965091945092506000917f0000000000000000000000000000000000000000000000000000000000000000909116906335ea6a759060240161018060405180830381865afa158015612a3b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a5f91906142bf565b9050612a758183602001518460600151866133b7565b979990985095505050505050565b600080600080600080612a9588612c6c565b925050915081600001519550612ab58888836000015184604001516137c6565b979a9199509750945050505050565b600080600080600080612ad688612c6c565b925050915081600001519550612ab588888360200151846060015161389b565b60008161138819048311820215612b0c57600080fd5b506127109102611388010490565b600080600080612b2987610e5f565b935050925050612b3b82828888613496565b935093505050935093915050565b60405163381adc6b60e01b81526001600160a01b0382811660048301526000917f00000000000000000000000000000000000000000000000000000000000000009091169063381adc6b90602401602060405180830381865afa158015612bb4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612bd89190613f4d565b604051630bc45d1960e41b81526001600160a01b0385811660048301527f0000000000000000000000000000000000000000000000000000000000000000169063bc45d19090602401602060405180830381865afa158015612c3e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c629190613f4d565b1615159392505050565b6040805160e081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810191909152612cd06040518060800160405280600081526020016000815260200160008152602001600081525090565b612cfb6040518060800160405280600081526020016000815260200160008152602001600081525090565b604051634f9c17b560e11b81526001600160a01b0385811660048301527f00000000000000000000000000000000000000000000000000000000000000001690639f382f6a9060240160e060405180830381865afa158015612d61573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d8591906143be565b6040516350437e1160e11b81526001600160a01b0386811660048301529194507f00000000000000000000000000000000000000000000000000000000000000009091169063a086fc2290602401608060405180830381865afa158015612df0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e14919061462f565b604051631987357f60e21b81526001600160a01b0386811660048301529193506000917f0000000000000000000000000000000000000000000000000000000000000000169063661cd5fc90602401606060405180830381865afa158015612e80573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ea49190614419565b9050612eb384600001516138fa565b6060840181905260408085018390528601516020870151600093612ee49390929091869161ffff9081169116613b29565b9050612fce6040518060c00160405280836000015181526020018360400151815260200184602001516001600160701b031681526020017f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663854f7ebb8a6040518263ffffffff1660e01b8152600401612f7691906001600160a01b0391909116815260200190565b602060405180830381865afa158015612f93573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612fb79190613f4d565b815286516020820152604080880151910152613c16565b83526040805160c081018252602083810151825260608085015191830191909152848301516001600160701b0316828401529151630175fa5f60e51b81526001600160a01b0389811660048301526130ae938301917f000000000000000000000000000000000000000000000000000000000000000090911690632ebf4be090602401602060405180830381865afa15801561306e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130929190613f4d565b8152602001866020015181526020018660600151815250613c16565b60208401525092949193509150565b60008160200151826000015111156130da5750602081015161311f565b60006130f3836000015184602001518560c00151613caf565b60e084015184519192506131119161310b9084613f7c565b90612af6565b61311b9082613f7c565b9150505b60008260800151118015613137575060008260a00151115b156131cb57600061318f61317861315f85606001518660a0015161327c90919063ffffffff16565b604086015160808701516131729161327c565b9061335f565b676765c793fa10079d601b1b808218908211021890565b835190915061319e908261327c565b6131bd6131b683676765c793fa10079d601b1b613f7c565b849061327c565b6131c791906145dc565b9150505b919050565b60008160200151826000015111156131ed5750602081015161322e565b6000613206836000015184602001518560c00151613caf565b90506132208360e0015182856020015161310b9190613f7c565b61322a90826145dc565b9150505b60008260800151118015613246575060008260a00151115b156131cb57600061326e61317861315f85606001518660a0015161327c90919063ffffffff16565b602084015190915061319e90825b6000816b019d971e4fe8401e740000001904831182021561329c57600080fd5b50676765c793fa10079d601b1b91026b019d971e4fe8401e74000000010490565b60405163381adc6b60e01b81526001600160a01b03828116600483015260009182917f0000000000000000000000000000000000000000000000000000000000000000169063381adc6b90602401602060405180830381865afa158015613328573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061334c9190613f4d565b600181901b178416151591505092915050565b60028104676765c793fa10079d601b1b811904831115820261338057600080fd5b676765c793fa10079d601b1b9092029091010490565b6000806000806133a587610e5f565b509250509150612b3b82828888613496565b6000806133ed6133d485856020015161327c90919063ffffffff16565b60608501516133e3908861327c565b9080821191030290565b610120870151604051630ed1279f60e11b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116600483015292945061348b9287921690631da24f3e90602401602060405180830381865afa158015613461573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906134859190613f4d565b9061327c565b905094509492505050565b6000806134a383856145dc565b905080156134f95783156134d2576134c56134be858361335f565b879061327c565b6134cf90836145dc565b91505b82156134f9576134ec6134e5848361335f565b869061327c565b6134f690836145dc565b91505b94509492505050565b60008060008060008061351487612c6c565b92509250925082600001519550613535878260000151836040015185613714565b9698909750945050505050565b6135826040518060e00160405280600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b60008061358e87612c6c565b825160405163b3596f0760e01b81526001600160a01b03918216600482015293955090935088169163b3596f079150602401602060405180830381865afa1580156135dd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136019190613f4d565b6080840152815160405163c44b11f760e01b81526001600160a01b03918216600482015261365a917f0000000000000000000000000000000000000000000000000000000000000000169063c44b11f790602401610ab5565b50808752604080880193909352606087019390935250600a9190910a6020850152815190820151600091613691918a918c916137c6565b9250505060006136ab898b8560200151866060015161389b565b925050506136d88560200151866080015188846136c891906145dc565b6136d29190613f93565b90613cf1565b60c0860152602085015160808601516136f7908985118a860302613f93565b6137019190613fb2565b60a0860152509298975050505050505050565b8051600090819061373890613729908661327c565b60408501516133e3908861327c565b6040516370a0823160e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081166004830152919350908716906370a0823190602401602060405180830381865afa1580156137a2573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061348b9190613f4d565b6040516339407b4160e21b81526001600160a01b03858116600483015284811660248301526000918291829182917f0000000000000000000000000000000000000000000000000000000000000000169063e501ed04906044015b6040805180830381865afa15801561383d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061386191906145c0565b8051909150613870908761327c565b6020820151909450613882908661327c565b925061388e84846145dc565b9150509450945094915050565b60405163251d5d2b60e21b81526001600160a01b03858116600483015284811660248301526000918291829182917f0000000000000000000000000000000000000000000000000000000000000000169063947574ac90604401613821565b60405163d15e005360e01b81526001600160a01b03828116600483015260009182917f0000000000000000000000000000000000000000000000000000000000000000169063d15e005390602401602060405180830381865afa158015613965573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139899190613f4d565b60405163386497fd60e01b81526001600160a01b0385811660048301529193507f00000000000000000000000000000000000000000000000000000000000000009091169063386497fd90602401602060405180830381865afa1580156139f4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a189190613f4d565b905073ae7ab96520de3a18e5e111b5eaab095312d7fe83196001600160a01b03841601613b2457604051630f451f7160e31b8152676765c793fa10079d601b1b600482015260009073ae7ab96520de3a18e5e111b5eaab095312d7fe8490637a28fb8890602401602060405180830381865afa158015613a9c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613ac09190613f4d565b9050613af07f0000000000000000000000000000000000000000000000000000000000000000613172858461327c565b9250613b207f0000000000000000000000000000000000000000000000000000000000000000613172848461327c565b9150505b915091565b613b546040518060800160405280600081526020016000815260200160008152602001600081525090565b6020840151613b6d9087906001600160701b031661335f565b81526040840151613b889086906001600160701b031661335f565b60208201819052815111613bfb576000613bab8260000151836020015186613caf565b9050613bc18383600001518361310b9190613f7c565b613bcb9082613f7c565b60408301526020820151613be690849061310b908490613f7c565b613bf090826145dc565b606083015250613c0d565b60208101516040820181905260608201525b95945050505050565b60008160a0015160001480613c2d57506080820151155b15613c455760208201516060830151610e599161327c565b6000613c6861317861315f85606001518660a0015161327c90919063ffffffff16565b83519091506131c790613c7c90839061327c565b6020850151613c9a9061348585676765c793fa10079d601b1b613f7c565b613ca491906145dc565b60608501519061327c565b6000816127100390508082840261138819030484118102826113881904841183021761271083111715613ce157600080fd5b6127109302910201611388010490565b600081613cfd57600080fd5b50808206151591040190565b6001600160a01b0381168114613d1e57600080fd5b50565b600060208284031215613d3357600080fd5b8135610d4d81613d09565b60008060408385031215613d5157600080fd5b8235613d5c81613d09565b91506020830135613d6c81613d09565b809150509250929050565b600080600060608486031215613d8c57600080fd5b8335613d9781613d09565b92506020840135613da781613d09565b91506040840135613db781613d09565b809150509250925092565b8151815260208083015190820152604080830151908201526060808301519082015260808101610e59565b60008060008060808587031215613e0357600080fd5b8435613e0e81613d09565b93506020850135613e1e81613d09565b93969395505050506040820135916060013590565b6020808252825182820181905260009190848201906040850190845b81811015613e745783516001600160a01b031683529284019291840191600101613e4f565b50909695505050505050565b600080600060608486031215613e9557600080fd5b8335613ea081613d09565b92506020840135613eb081613d09565b929592945050506040919091013590565b600060e08201905082511515825260208301511515602083015260408301511515604083015260608301511515606083015260808301511515608083015260a0830151151560a083015260c0830151613f1e60c084018215159052565b5092915050565b80516131cb81613d09565b600060208284031215613f4257600080fd5b8151610d4d81613d09565b600060208284031215613f5f57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b600082821015613f8e57613f8e613f66565b500390565b6000816000190483118215151615613fad57613fad613f66565b500290565b600082613fcf57634e487b7160e01b600052601260045260246000fd5b500490565b634e487b7160e01b600052604160045260246000fd5b60405160e0810167ffffffffffffffff8111828210171561400d5761400d613fd4565b60405290565b604051610180810167ffffffffffffffff8111828210171561400d5761400d613fd4565b604051601f8201601f1916810167ffffffffffffffff8111828210171561406057614060613fd4565b604052919050565b60006020828403121561407a57600080fd5b6040516020810181811067ffffffffffffffff8211171561409d5761409d613fd4565b6040529151825250919050565b6000602082840312156140bc57600080fd5b610e568383614068565b600181815b808511156141015781600019048211156140e7576140e7613f66565b808516156140f457918102915b93841c93908002906140cb565b509250929050565b60008261411857506001610e59565b8161412557506000610e59565b816001811461413b576002811461414557614161565b6001915050610e59565b60ff84111561415657614156613f66565b50506001821b610e59565b5060208310610133831016604e8410600b8410161715614184575081810a610e59565b61418e83836140c6565b80600019048211156141a2576141a2613f66565b029392505050565b6000610e568383614109565b805160ff811681146131cb57600080fd5b6000602082840312156141d957600080fd5b610e56826141b6565b6000610e5660ff841683614109565b805180151581146131cb57600080fd5b600060e0828403121561421357600080fd5b61421b613fea565b614224836141f1565b8152614232602084016141f1565b6020820152614243604084016141f1565b6040820152614254606084016141f1565b6060820152614265608084016141f1565b608082015261427660a084016141f1565b60a082015261428760c084016141f1565b60c08201529392505050565b80516001600160801b03811681146131cb57600080fd5b805164ffffffffff811681146131cb57600080fd5b600061018082840312156142d257600080fd5b6142da614013565b6142e48484614068565b81526142f260208401614293565b602082015261430360408401614293565b604082015261431460608401614293565b606082015261432560808401614293565b608082015261433660a08401614293565b60a082015261434760c084016142aa565b60c082015261435860e08401613f25565b60e082015261010061436b818501613f25565b9082015261012061437d848201613f25565b9082015261014061438f848201613f25565b908201526101606143a18482016141b6565b908201529392505050565b805161ffff811681146131cb57600080fd5b600060e082840312156143d057600080fd5b6143d8613fea565b82516143e381613d09565b81526143f1602084016143ac565b6020820152614243604084016143ac565b80516001600160701b03811681146131cb57600080fd5b60006060828403121561442b57600080fd5b6040516060810181811067ffffffffffffffff8211171561444e5761444e613fd4565b604052825163ffffffff8116811461446557600080fd5b815261447360208401614402565b602082015261448460408401614402565b60408201529392505050565b600060208083850312156144a357600080fd5b825167ffffffffffffffff808211156144bb57600080fd5b818501915085601f8301126144cf57600080fd5b8151818111156144e1576144e1613fd4565b8060051b91506144f2848301614037565b818152918301840191848101908884111561450c57600080fd5b938501935b83851015614536578451925061452683613d09565b8282529385019390850190614511565b98975050505050505050565b634e487b7160e01b600052603260045260246000fd5b60006001820161456a5761456a613f66565b5060010190565b60006040828403121561458357600080fd5b6040516040810181811067ffffffffffffffff821117156145a6576145a6613fd4565b604052825181526020928301519281019290925250919050565b6000604082840312156145d257600080fd5b610e568383614571565b600082198211156145ef576145ef613f66565b500190565b6001600160a01b0383168152604081016004831061462257634e487b7160e01b600052602160045260246000fd5b8260208301529392505050565b60006080828403121561464157600080fd5b6040516080810181811067ffffffffffffffff8211171561466457614664613fd4565b806040525082518152602083015160208201526040830151604082015260608301516060820152809150509291505056fea264697066735822122099a0879588664dcd3849e169004648e8123b716ed91f7848bab5fb96ef9215dc64736f6c634300080d0033000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e0

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106102535760003560e01c8063a480b7ed11610146578063cd26e92d116100c3578063d89aaaf511610087578063d89aaaf5146106ea578063d8fbc833146106fd578063e37f8a7e14610724578063f0702fcb1461072c578063f286d9b51461073f578063f657af411461075257600080fd5b8063cd26e92d14610336578063d2a87cf81461063f578063d350964514610652578063d61bb596146106bb578063d664f72c146106ce57600080fd5b8063bcbb2bf21161010a578063bcbb2bf2146105db578063c3525c28146105ee578063c46fcbfc146105fd578063c4e41b2214610610578063c72c4d101461061857600080fd5b8063a480b7ed14610573578063a74e472b14610586578063a9a97718146105ad578063b0772d0b146105c0578063b7013b46146105c857600080fd5b8063576f67ed116101d4578063790bf72511610198578063790bf725146104be5780637b1ab592146104d157806385a229321461052d5780638ccb720b14610540578063967f1aaf1461056057600080fd5b8063576f67ed1461039e5780635a208d52146103d15780635de72f6a1461044b57806371cbfc981461048b578063762fb6891461049e57600080fd5b8063338346d21161021b578063338346d21461031b57806336cd097c146103365780633737c7141461034a57806339296cf9146103785780633966a28b1461038b57600080fd5b8063042e02cf14610258578063140680b3146102805780631419cfe1146102a857806316f0115b146102bb5780632af8970e146102fa575b600080fd5b61026b610266366004613d21565b610772565b60405190151581526020015b60405180910390f35b61029361028e366004613d3e565b61078d565b60408051928352602083019190915201610277565b6102936102b6366004613d21565b610a0b565b6102e27f0000000000000000000000007d2768de32b0b80b7a3454c06bdac94a69ddc7a981565b6040516001600160a01b039091168152602001610277565b61030d610308366004613d77565b610a22565b604051908152602001610277565b6102e273ae7ab96520de3a18e5e111b5eaab095312d7fe8481565b61026b610344366004613d21565b50600090565b61035d610358366004613d3e565b610d54565b60408051938452602084019290925290820152606001610277565b61030d610386366004613d3e565b610d72565b61026b610399366004613d3e565b610d9c565b6103b16103ac366004613d21565b610e5f565b604080519485526020850193909352918301526060820152608001610277565b6103e46103df366004613d21565b611002565b604080516001600160a01b03909c168c5299151560208c0152971515988a01989098529415156060890152921515608088015261ffff91821660a08801521660c086015260e085015261010084015261012083019190915261014082015261016001610277565b61045e610459366004613d21565b61115c565b604080519687526020870195909552938501929092526060840152608083015260a082015260c001610277565b61030d610499366004613d21565b61118f565b6104b16104ac366004613d21565b61119f565b6040516102779190613dc2565b61026b6104cc366004613d21565b6111db565b6104e46104df366004613d21565b611274565b60408051855181526020808701519082015285820151918101919091526060948501519481019490945263ffffffff909216608084015260a083015260c082015260e001610277565b61030d61053b366004613ded565b6113aa565b61055361054e366004613d21565b6113ef565b6040516102779190613e33565b6103b161056e366004613e80565b6115f4565b61035d610581366004613d3e565b61193a565b61030d7f00000000000000000000000000000000000000000382b9abc7861e2c57645ae281565b61030d6105bb366004613d21565b611949565b61055361195f565b61030d6105d6366004613d21565b6119ec565b6103b16105e9366004613e80565b611a05565b61030d670de0b6b3a764000081565b61035d61060b366004613d21565b611d18565b61035d611e7a565b6102e27f000000000000000000000000b53c1a33016b2dc2ff3653530bff1848a515c8c581565b61029361064d366004613d21565b612117565b610665610660366004613d77565b612123565b6040516102779190600060e082019050825182526020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c083015160c083015292915050565b6104b16106c9366004613ded565b612171565b6106d761138881565b60405161ffff9091168152602001610277565b61035d6106f8366004613d21565b612479565b6102e27f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e081565b61035d6125ba565b61030d61073a366004613d3e565b612842565b6104b161074d366004613d21565b612862565b610765610760366004613d21565b61289b565b6040516102779190613ec1565b6000670de0b6b3a76400006107868361118f565b1092915050565b60008060007f000000000000000000000000b53c1a33016b2dc2ff3653530bff1848a515c8c56001600160a01b031663fca513a86040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107f0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108149190613f30565b9050600061082186612862565b90506000610830878785612123565b9050600082606001511180156108685750670de0b6b3a76400006108658360600151846040015161295a90919063ffffffff16565b11155b1561087c5760008094509450505050610a04565b6000866001600160a01b031663b16a19de6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108e09190613f30565b6040516370a0823160e01b81526001600160a01b03898116600483015291909116906370a0823190602401602060405180830381865afa158015610928573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061094c9190613f4d565b90508260200151836060015110156109a25761099f8183608001518460200151866060015187602001516109809190613f7c565b61098a9190613f93565b6109949190613fb2565b808218908211021890565b94505b6109bf81836080015184602001518560a0015161098a9190613f93565b6040830151909650156109ff576109fc86836080015184602001516109808660400151886060015189604001516109f69190613f7c565b9061298b565b95505b505050505b9250929050565b600080610a17836129b0565b909590945092505050565b6000610a2e8484610d9c565b610a3a57506000610d4d565b600080610a478487612a83565b935050509150600080610a5a8789612ac4565b60405163c44b11f760e01b81526001600160a01b038981166004830152949650909450600093849350610b2192507f0000000000000000000000007d2768de32b0b80b7a3454c06bdac94a69ddc7a9169063c44b11f7906024015b602060405180830381865afa158015610ad2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610af691906140aa565b5161ffff80821692601083901c821692602081901c831692603082901c60ff169260409290921c1690565b5093509350505060007f000000000000000000000000b53c1a33016b2dc2ff3653530bff1848a515c8c56001600160a01b031663fca513a86040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b88573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bac9190613f30565b60405163b3596f0760e01b81526001600160a01b03878116600483015291925060009183169063b3596f0790602401602060405180830381865afa158015610bf8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c1c9190613f4d565b60405163b3596f0760e01b81526001600160a01b038a8116600483015291925060009184169063b3596f0790602401602060405180830381865afa158015610c68573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c8c9190613f4d565b9050610d41610d3586610ca087600a6141aa565b610caa9086613f93565b8a6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ce8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d0c91906141c7565b610d1790600a6141e2565b610d21868e613f93565b610d2b9190613f93565b6109f69190613fb2565b61099488611388612af6565b99505050505050505050505b9392505050565b6000806000610d638585612ac4565b91989097509095509350505050565b6000806000610d818585612ac4565b509250925050610d92858383612b1a565b5095945050505050565b604051630de2bdf560e41b81526001600160a01b0382811660048301526000917f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e09091169063de2bdf509060240160e060405180830381865afa158015610e07573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e2b9190614201565b60c001518015610e405750610e408383612b49565b15610e4d57506001610e59565b610e5683610772565b90505b92915050565b6000806000806000806000610e7388612c6c565b82516040516335ea6a7560e01b81526001600160a01b03918216600482015293965091945092506000917f0000000000000000000000007d2768de32b0b80b7a3454c06bdac94a69ddc7a9909116906335ea6a759060240161018060405180830381865afa158015610ee9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f0d91906142bf565b905080606001516001600160801b0316955080608001516001600160801b03169450610f9160405180610100016040528088815260200187815260200184604001518152602001846000015181526020018560000151815260200185604001518152602001866040015161ffff168152602001866020015161ffff168152506130bd565b9750610ff560405180610100016040528088815260200187815260200184606001518152602001846020015181526020018560200151815260200185606001518152602001866040015161ffff168152602001866020015161ffff168152506131d0565b9650505050509193509193565b6000806000806000806000806000806000807f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e06001600160a01b0316639f382f6a8e6040518263ffffffff1660e01b815260040161106f91906001600160a01b0391909116815260200190565b60e060405180830381865afa15801561108c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110b091906143be565b905080600001519b5080606001519a508060c0015199506000985060009750806020015196508060400151955061113b7f0000000000000000000000007d2768de32b0b80b7a3454c06bdac94a69ddc7a96001600160a01b031663c44b11f78e6040518263ffffffff1660e01b8152600401610ab591906001600160a01b0391909116815260200190565b50809550819650829750839850505050505091939597999b90929496989a50565b60008060008060008061116e87612479565b9197509450915061117e87611d18565b979991985094969495509193925050565b6000610e598260008060006113aa565b6111ca6040518060800160405280600081526020016000815260200160008152602001600081525090565b6111d382612c6c565b949350505050565b604051634f9c17b560e11b81526001600160a01b0382811660048301526000917f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e090911690639f382f6a9060240160e060405180830381865afa158015611246573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061126a91906143be565b6060015192915050565b61129f6040518060800160405280600081526020016000815260200160008152602001600081525090565b60008060006112cf6040518060800160405280600081526020016000815260200160008152602001600081525090565b6112d886612c6c565b604081015182519198509193506112f092509061327c565b925061130d8560600151826020015161327c90919063ffffffff16565b604051631987357f60e21b81526001600160a01b0388811660048301529193507f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e09091169063661cd5fc90602401606060405180830381865afa158015611378573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061139c9190614419565b600001519350509193509193565b6000806113b986868686612171565b905080606001516000036113d2576000199150506111d3565b606081015160408201516113e59161295a565b9695505050505050565b606060007f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e06001600160a01b031663a1d6000c6040518163ffffffff1660e01b8152600401600060405180830381865afa158015611451573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526114799190810190614490565b805190915060008167ffffffffffffffff81111561149957611499613fd4565b6040519080825280602002602001820160405280156114c2578160200160208202803683370190505b50604051630bc45d1960e41b81526001600160a01b0387811660048301529195506000917f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e0169063bc45d19090602401602060405180830381865afa15801561152f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115539190613f4d565b905060005b838110156115e8576115838286838151811061157657611576614542565b60200260200101516132bd565b156115d85784818151811061159a5761159a614542565b60200260200101518684815181106115b4576115b4614542565b6001600160a01b03909216602092830291909101909101526115d583614558565b92505b6115e181614558565b9050611558565b50508352509092915050565b60008060008060008060006116088a612c6c565b60405163251d5d2b60e21b81526001600160a01b038e811660048301528d8116602483015293965091945092506000917f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e0169063947574ac906044016040805180830381865afa158015611680573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116a491906145c0565b90506000891180156116b65750825115155b1561171657604082015183516000916116dd916116d29161327c565b8b8111818d18021890565b90506116f683602001518261335f90919063ffffffff16565b825183906117059083906145dc565b905250611712818b613f7c565b9950505b60008911801561172857508360c00151155b156118c657604051635acff02760e01b81526000906001600160a01b037f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e01690635acff0279061177f908f906001906004016145f4565b602060405180830381865afa15801561179c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117c09190613f30565b6040516339407b4160e21b81526001600160a01b038e8116600483015280831660248301529192506000917f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e0169063e501ed04906044016040805180830381865afa158015611833573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061185791906145c0565b60200151905080156118c357600061188a61187f86604001518461327c90919063ffffffff16565b8d8111818f18021890565b90506118a385602001518261335f90919063ffffffff16565b845185906118b29083906145dc565b9052506118bf818d613f7c565b9b50505b50505b88156118f15760608201516118dc908a9061335f565b816020018181516118ed91906145dc565b9052505b606082015160208201516119049161327c565b60208301518251919750611918919061327c565b96506119258b8888612b1a565b80965081995050505050505093509350935093565b6000806000610d638585612a83565b60008061195583612c6c565b5195945050505050565b60607f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e06001600160a01b031663a1d6000c6040518163ffffffff1660e01b8152600401600060405180830381865afa1580156119bf573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526119e79190810190614490565b905090565b6000806119f883612c6c565b6020015195945050505050565b6000806000806000806000611a198a612c6c565b6040516339407b4160e21b81526001600160a01b038e811660048301528d8116602483015293965091945092506000917f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e0169063e501ed04906044016040805180830381865afa158015611a91573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ab591906145c0565b9050600089118015611acb575060008360200151115b15611b20576000611af06116d28460600151866020015161327c90919063ffffffff16565b8351909150611b0090829061335f565b82518390611b0f9083906145dc565b905250611b1c818b613f7c565b9950505b600089118015611b3257508360c00151155b15611cbc57604051635acff02760e01b81526000906001600160a01b037f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e01690635acff02790611b89908f906003906004016145f4565b602060405180830381865afa158015611ba6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bca9190613f30565b60405163251d5d2b60e21b81526001600160a01b038e8116600483015280831660248301529192506000917f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e0169063947574ac906044016040805180830381865afa158015611c3d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c6191906145c0565b6020015190508015611cb9576000611c8961187f86606001518461327c90919063ffffffff16565b8551909150611c9990829061335f565b84518590611ca89083906145dc565b905250611cb5818d613f7c565b9b50505b50505b8815611ce7576040820151611cd2908a9061335f565b81602001818151611ce391906145dc565b9052505b60408201516020820151611cfa9161327c565b82518251919750611d0b919061327c565b96506119258b8888613396565b600080600080600080611d2a87612c6c565b82516040516335ea6a7560e01b81526001600160a01b03918216600482015293965091945092506000917f0000000000000000000000007d2768de32b0b80b7a3454c06bdac94a69ddc7a9909116906335ea6a759060240161018060405180830381865afa158015611da0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dc491906142bf565b9050600081608001516001600160801b031690506000611e4360405180610100016040528085606001516001600160801b0316815260200184815260200186606001518152602001866020015181526020016000815260200160008152602001886040015161ffff168152602001886020015161ffff168152506131d0565b9050611e598385602001518660600151886133b7565b9098509650611e6a81838a8a613496565b509a979950959750505050505050565b6000806000807f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e06001600160a01b031663a1d6000c6040518163ffffffff1660e01b8152600401600060405180830381865afa158015611ede573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052611f069190810190614490565b905060007f000000000000000000000000b53c1a33016b2dc2ff3653530bff1848a515c8c56001600160a01b031663fca513a86040518163ffffffff1660e01b8152600401602060405180830381865afa158015611f68573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f8c9190613f30565b825190915060005b81811015612102576000848281518110611fb057611fb0614542565b602002602001015190506000806000611fc884613502565b60405163b3596f0760e01b81526001600160a01b038085166004830152939650919450925060009189169063b3596f0790602401602060405180830381865afa158015612019573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061203d9190613f4d565b60405163c44b11f760e01b81526001600160a01b038681166004830152919250600091612097917f0000000000000000000000007d2768de32b0b80b7a3454c06bdac94a69ddc7a99091169063c44b11f790602401610ab5565b509350505050600081600a6120ac91906141aa565b9050806120b98487613f93565b6120c39190613fb2565b6120cd908f6145dc565b9d50806120da8486613f93565b6120e49190613fb2565b6120ee908e6145dc565b9c5087600101975050505050505050611f94565b5061210d85876145dc565b9350505050909192565b600080610a1783613502565b6121636040518060e00160405280600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b6111d3848484600080613542565b61219c6040518060800160405280600081526020016000815260200160008152602001600081525090565b60007f000000000000000000000000b53c1a33016b2dc2ff3653530bff1848a515c8c56001600160a01b031663fca513a86040518163ffffffff1660e01b8152600401602060405180830381865afa1580156121fc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122209190613f30565b905060007f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e06001600160a01b031663a1d6000c6040518163ffffffff1660e01b8152600401600060405180830381865afa158015612282573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526122aa9190810190614490565b604051630bc45d1960e41b81526001600160a01b0389811660048301529192506000917f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e0169063bc45d19090602401602060405180830381865afa158015612316573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061233a9190613f4d565b825190915060005b8181101561246c57600084828151811061235e5761235e614542565b6020026020010151905061237284826132bd565b1580156123915750806001600160a01b03168a6001600160a01b031614155b1561239c575061245c565b6000816001600160a01b03168b6001600160a01b0316146123ca576123c58c8389600080613542565b6123d7565b6123d78c83898d8d613542565b90508060a00151886000018181516123ef91906145dc565b905250606081015160a082015161240591612af6565b8860200181815161241691906145dc565b905250604081015160a082015161242c91612af6565b8860400181815161243d91906145dc565b90525060c08101516060890180516124569083906145dc565b90525050505b61246581614558565b9050612342565b5050505050949350505050565b60008060008060008061248b87612c6c565b82516040516335ea6a7560e01b81526001600160a01b03918216600482015293965091945092506000917f0000000000000000000000007d2768de32b0b80b7a3454c06bdac94a69ddc7a9909116906335ea6a759060240161018060405180830381865afa158015612501573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061252591906142bf565b9050600081606001516001600160801b0316905060006125a460405180610100016040528084815260200185608001516001600160801b0316815260200186604001518152602001866000015181526020016000815260200160008152602001886040015161ffff168152602001886020015161ffff168152506130bd565b9050611e598a8560000151866040015188613714565b6000806000807f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e06001600160a01b031663a1d6000c6040518163ffffffff1660e01b8152600401600060405180830381865afa15801561261e573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526126469190810190614490565b905060007f000000000000000000000000b53c1a33016b2dc2ff3653530bff1848a515c8c56001600160a01b031663fca513a86040518163ffffffff1660e01b8152600401602060405180830381865afa1580156126a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126cc9190613f30565b825190915060005b818110156121025760008482815181106126f0576126f0614542565b602002602001015190506000806000612708846129b0565b60405163b3596f0760e01b81526001600160a01b038085166004830152939650919450925060009189169063b3596f0790602401602060405180830381865afa158015612759573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061277d9190613f4d565b60405163c44b11f760e01b81526001600160a01b0386811660048301529192506000916127d7917f0000000000000000000000007d2768de32b0b80b7a3454c06bdac94a69ddc7a99091169063c44b11f790602401610ab5565b509350505050600081600a6127ec91906141aa565b9050806127f98487613f93565b6128039190613fb2565b61280d908f6145dc565b9d508061281a8486613f93565b6128249190613fb2565b61282e908e6145dc565b9c50876001019750505050505050506126d4565b60008060006128518585612a83565b509250925050610d92858383613396565b61288d6040518060800160405280600081526020016000815260200160008152602001600081525090565b610e59826000806000612171565b6040805160e081018252600080825260208201819052818301819052606082018190526080820181905260a0820181905260c08201529051630de2bdf560e41b81526001600160a01b0383811660048301527f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e0169063de2bdf509060240160e060405180830381865afa158015612936573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e599190614201565b60028104670de0b6b3a7640000811904831115820261297857600080fd5b670de0b6b3a76400009092029091010490565b6002810461271081190483111582026129a357600080fd5b6127109092029091010490565b6000806000806000806129c287612c6c565b82516040516335ea6a7560e01b81526001600160a01b038083166004830152919a5093965091945092506000917f0000000000000000000000007d2768de32b0b80b7a3454c06bdac94a69ddc7a9909116906335ea6a759060240161018060405180830381865afa158015612a3b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a5f91906142bf565b9050612a758183602001518460600151866133b7565b979990985095505050505050565b600080600080600080612a9588612c6c565b925050915081600001519550612ab58888836000015184604001516137c6565b979a9199509750945050505050565b600080600080600080612ad688612c6c565b925050915081600001519550612ab588888360200151846060015161389b565b60008161138819048311820215612b0c57600080fd5b506127109102611388010490565b600080600080612b2987610e5f565b935050925050612b3b82828888613496565b935093505050935093915050565b60405163381adc6b60e01b81526001600160a01b0382811660048301526000917f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e09091169063381adc6b90602401602060405180830381865afa158015612bb4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612bd89190613f4d565b604051630bc45d1960e41b81526001600160a01b0385811660048301527f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e0169063bc45d19090602401602060405180830381865afa158015612c3e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c629190613f4d565b1615159392505050565b6040805160e081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810191909152612cd06040518060800160405280600081526020016000815260200160008152602001600081525090565b612cfb6040518060800160405280600081526020016000815260200160008152602001600081525090565b604051634f9c17b560e11b81526001600160a01b0385811660048301527f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e01690639f382f6a9060240160e060405180830381865afa158015612d61573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d8591906143be565b6040516350437e1160e11b81526001600160a01b0386811660048301529194507f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e09091169063a086fc2290602401608060405180830381865afa158015612df0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e14919061462f565b604051631987357f60e21b81526001600160a01b0386811660048301529193506000917f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e0169063661cd5fc90602401606060405180830381865afa158015612e80573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612ea49190614419565b9050612eb384600001516138fa565b6060840181905260408085018390528601516020870151600093612ee49390929091869161ffff9081169116613b29565b9050612fce6040518060c00160405280836000015181526020018360400151815260200184602001516001600160701b031681526020017f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e06001600160a01b031663854f7ebb8a6040518263ffffffff1660e01b8152600401612f7691906001600160a01b0391909116815260200190565b602060405180830381865afa158015612f93573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612fb79190613f4d565b815286516020820152604080880151910152613c16565b83526040805160c081018252602083810151825260608085015191830191909152848301516001600160701b0316828401529151630175fa5f60e51b81526001600160a01b0389811660048301526130ae938301917f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e090911690632ebf4be090602401602060405180830381865afa15801561306e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130929190613f4d565b8152602001866020015181526020018660600151815250613c16565b60208401525092949193509150565b60008160200151826000015111156130da5750602081015161311f565b60006130f3836000015184602001518560c00151613caf565b60e084015184519192506131119161310b9084613f7c565b90612af6565b61311b9082613f7c565b9150505b60008260800151118015613137575060008260a00151115b156131cb57600061318f61317861315f85606001518660a0015161327c90919063ffffffff16565b604086015160808701516131729161327c565b9061335f565b676765c793fa10079d601b1b808218908211021890565b835190915061319e908261327c565b6131bd6131b683676765c793fa10079d601b1b613f7c565b849061327c565b6131c791906145dc565b9150505b919050565b60008160200151826000015111156131ed5750602081015161322e565b6000613206836000015184602001518560c00151613caf565b90506132208360e0015182856020015161310b9190613f7c565b61322a90826145dc565b9150505b60008260800151118015613246575060008260a00151115b156131cb57600061326e61317861315f85606001518660a0015161327c90919063ffffffff16565b602084015190915061319e90825b6000816b019d971e4fe8401e740000001904831182021561329c57600080fd5b50676765c793fa10079d601b1b91026b019d971e4fe8401e74000000010490565b60405163381adc6b60e01b81526001600160a01b03828116600483015260009182917f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e0169063381adc6b90602401602060405180830381865afa158015613328573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061334c9190613f4d565b600181901b178416151591505092915050565b60028104676765c793fa10079d601b1b811904831115820261338057600080fd5b676765c793fa10079d601b1b9092029091010490565b6000806000806133a587610e5f565b509250509150612b3b82828888613496565b6000806133ed6133d485856020015161327c90919063ffffffff16565b60608501516133e3908861327c565b9080821191030290565b610120870151604051630ed1279f60e11b81526001600160a01b037f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e08116600483015292945061348b9287921690631da24f3e90602401602060405180830381865afa158015613461573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906134859190613f4d565b9061327c565b905094509492505050565b6000806134a383856145dc565b905080156134f95783156134d2576134c56134be858361335f565b879061327c565b6134cf90836145dc565b91505b82156134f9576134ec6134e5848361335f565b869061327c565b6134f690836145dc565b91505b94509492505050565b60008060008060008061351487612c6c565b92509250925082600001519550613535878260000151836040015185613714565b9698909750945050505050565b6135826040518060e00160405280600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b60008061358e87612c6c565b825160405163b3596f0760e01b81526001600160a01b03918216600482015293955090935088169163b3596f079150602401602060405180830381865afa1580156135dd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136019190613f4d565b6080840152815160405163c44b11f760e01b81526001600160a01b03918216600482015261365a917f0000000000000000000000007d2768de32b0b80b7a3454c06bdac94a69ddc7a9169063c44b11f790602401610ab5565b50808752604080880193909352606087019390935250600a9190910a6020850152815190820151600091613691918a918c916137c6565b9250505060006136ab898b8560200151866060015161389b565b925050506136d88560200151866080015188846136c891906145dc565b6136d29190613f93565b90613cf1565b60c0860152602085015160808601516136f7908985118a860302613f93565b6137019190613fb2565b60a0860152509298975050505050505050565b8051600090819061373890613729908661327c565b60408501516133e3908861327c565b6040516370a0823160e01b81526001600160a01b037f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e081166004830152919350908716906370a0823190602401602060405180830381865afa1580156137a2573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061348b9190613f4d565b6040516339407b4160e21b81526001600160a01b03858116600483015284811660248301526000918291829182917f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e0169063e501ed04906044015b6040805180830381865afa15801561383d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061386191906145c0565b8051909150613870908761327c565b6020820151909450613882908661327c565b925061388e84846145dc565b9150509450945094915050565b60405163251d5d2b60e21b81526001600160a01b03858116600483015284811660248301526000918291829182917f000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e0169063947574ac90604401613821565b60405163d15e005360e01b81526001600160a01b03828116600483015260009182917f0000000000000000000000007d2768de32b0b80b7a3454c06bdac94a69ddc7a9169063d15e005390602401602060405180830381865afa158015613965573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139899190613f4d565b60405163386497fd60e01b81526001600160a01b0385811660048301529193507f0000000000000000000000007d2768de32b0b80b7a3454c06bdac94a69ddc7a99091169063386497fd90602401602060405180830381865afa1580156139f4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a189190613f4d565b905073ae7ab96520de3a18e5e111b5eaab095312d7fe83196001600160a01b03841601613b2457604051630f451f7160e31b8152676765c793fa10079d601b1b600482015260009073ae7ab96520de3a18e5e111b5eaab095312d7fe8490637a28fb8890602401602060405180830381865afa158015613a9c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613ac09190613f4d565b9050613af07f00000000000000000000000000000000000000000382b9abc7861e2c57645ae2613172858461327c565b9250613b207f00000000000000000000000000000000000000000382b9abc7861e2c57645ae2613172848461327c565b9150505b915091565b613b546040518060800160405280600081526020016000815260200160008152602001600081525090565b6020840151613b6d9087906001600160701b031661335f565b81526040840151613b889086906001600160701b031661335f565b60208201819052815111613bfb576000613bab8260000151836020015186613caf565b9050613bc18383600001518361310b9190613f7c565b613bcb9082613f7c565b60408301526020820151613be690849061310b908490613f7c565b613bf090826145dc565b606083015250613c0d565b60208101516040820181905260608201525b95945050505050565b60008160a0015160001480613c2d57506080820151155b15613c455760208201516060830151610e599161327c565b6000613c6861317861315f85606001518660a0015161327c90919063ffffffff16565b83519091506131c790613c7c90839061327c565b6020850151613c9a9061348585676765c793fa10079d601b1b613f7c565b613ca491906145dc565b60608501519061327c565b6000816127100390508082840261138819030484118102826113881904841183021761271083111715613ce157600080fd5b6127109302910201611388010490565b600081613cfd57600080fd5b50808206151591040190565b6001600160a01b0381168114613d1e57600080fd5b50565b600060208284031215613d3357600080fd5b8135610d4d81613d09565b60008060408385031215613d5157600080fd5b8235613d5c81613d09565b91506020830135613d6c81613d09565b809150509250929050565b600080600060608486031215613d8c57600080fd5b8335613d9781613d09565b92506020840135613da781613d09565b91506040840135613db781613d09565b809150509250925092565b8151815260208083015190820152604080830151908201526060808301519082015260808101610e59565b60008060008060808587031215613e0357600080fd5b8435613e0e81613d09565b93506020850135613e1e81613d09565b93969395505050506040820135916060013590565b6020808252825182820181905260009190848201906040850190845b81811015613e745783516001600160a01b031683529284019291840191600101613e4f565b50909695505050505050565b600080600060608486031215613e9557600080fd5b8335613ea081613d09565b92506020840135613eb081613d09565b929592945050506040919091013590565b600060e08201905082511515825260208301511515602083015260408301511515604083015260608301511515606083015260808301511515608083015260a0830151151560a083015260c0830151613f1e60c084018215159052565b5092915050565b80516131cb81613d09565b600060208284031215613f4257600080fd5b8151610d4d81613d09565b600060208284031215613f5f57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b600082821015613f8e57613f8e613f66565b500390565b6000816000190483118215151615613fad57613fad613f66565b500290565b600082613fcf57634e487b7160e01b600052601260045260246000fd5b500490565b634e487b7160e01b600052604160045260246000fd5b60405160e0810167ffffffffffffffff8111828210171561400d5761400d613fd4565b60405290565b604051610180810167ffffffffffffffff8111828210171561400d5761400d613fd4565b604051601f8201601f1916810167ffffffffffffffff8111828210171561406057614060613fd4565b604052919050565b60006020828403121561407a57600080fd5b6040516020810181811067ffffffffffffffff8211171561409d5761409d613fd4565b6040529151825250919050565b6000602082840312156140bc57600080fd5b610e568383614068565b600181815b808511156141015781600019048211156140e7576140e7613f66565b808516156140f457918102915b93841c93908002906140cb565b509250929050565b60008261411857506001610e59565b8161412557506000610e59565b816001811461413b576002811461414557614161565b6001915050610e59565b60ff84111561415657614156613f66565b50506001821b610e59565b5060208310610133831016604e8410600b8410161715614184575081810a610e59565b61418e83836140c6565b80600019048211156141a2576141a2613f66565b029392505050565b6000610e568383614109565b805160ff811681146131cb57600080fd5b6000602082840312156141d957600080fd5b610e56826141b6565b6000610e5660ff841683614109565b805180151581146131cb57600080fd5b600060e0828403121561421357600080fd5b61421b613fea565b614224836141f1565b8152614232602084016141f1565b6020820152614243604084016141f1565b6040820152614254606084016141f1565b6060820152614265608084016141f1565b608082015261427660a084016141f1565b60a082015261428760c084016141f1565b60c08201529392505050565b80516001600160801b03811681146131cb57600080fd5b805164ffffffffff811681146131cb57600080fd5b600061018082840312156142d257600080fd5b6142da614013565b6142e48484614068565b81526142f260208401614293565b602082015261430360408401614293565b604082015261431460608401614293565b606082015261432560808401614293565b608082015261433660a08401614293565b60a082015261434760c084016142aa565b60c082015261435860e08401613f25565b60e082015261010061436b818501613f25565b9082015261012061437d848201613f25565b9082015261014061438f848201613f25565b908201526101606143a18482016141b6565b908201529392505050565b805161ffff811681146131cb57600080fd5b600060e082840312156143d057600080fd5b6143d8613fea565b82516143e381613d09565b81526143f1602084016143ac565b6020820152614243604084016143ac565b80516001600160701b03811681146131cb57600080fd5b60006060828403121561442b57600080fd5b6040516060810181811067ffffffffffffffff8211171561444e5761444e613fd4565b604052825163ffffffff8116811461446557600080fd5b815261447360208401614402565b602082015261448460408401614402565b60408201529392505050565b600060208083850312156144a357600080fd5b825167ffffffffffffffff808211156144bb57600080fd5b818501915085601f8301126144cf57600080fd5b8151818111156144e1576144e1613fd4565b8060051b91506144f2848301614037565b818152918301840191848101908884111561450c57600080fd5b938501935b83851015614536578451925061452683613d09565b8282529385019390850190614511565b98975050505050505050565b634e487b7160e01b600052603260045260246000fd5b60006001820161456a5761456a613f66565b5060010190565b60006040828403121561458357600080fd5b6040516040810181811067ffffffffffffffff821117156145a6576145a6613fd4565b604052825181526020928301519281019290925250919050565b6000604082840312156145d257600080fd5b610e568383614571565b600082198211156145ef576145ef613f66565b500190565b6001600160a01b0383168152604081016004831061462257634e487b7160e01b600052602160045260246000fd5b8260208301529392505050565b60006080828403121561464157600080fd5b6040516080810181811067ffffffffffffffff8211171561466457614664613fd4565b806040525082518152602083015160208201526040830151604082015260608301516060820152809150509291505056fea264697066735822122099a0879588664dcd3849e169004648e8123b716ed91f7848bab5fb96ef9215dc64736f6c634300080d0033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e0

-----Decoded View---------------
Arg [0] : _morpho (address): 0x777777c9898D384F785Ee44Acfe945efDFf5f3E0

-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 000000000000000000000000777777c9898d384f785ee44acfe945efdff5f3e0


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.