ETH Price: $3,418.88 (-0.58%)
Gas: 2 Gwei

Contract

0x77ca0d4b78D8B4F3c71e20F8c8771C4cb7ABE201
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Value
0x60a06040198920852024-05-17 20:31:1146 days ago1715977871IN
 Create: IonPool
0 ETH0.018357183.53928218

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
IonPool

Compiler Version
v0.8.21+commit.d9974bed

Optimization Enabled:
Yes with 200 runs

Other Settings:
shanghai EvmVersion
File 1 of 36 : IonPool.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.21;

import { Whitelist } from "./Whitelist.sol";
import { SpotOracle } from "./oracles/spot/SpotOracle.sol";
import { RewardToken } from "./token/RewardToken.sol";
import { InterestRate } from "./InterestRate.sol";
import { WadRayMath, RAY } from "./libraries/math/WadRayMath.sol";

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";

/**
 * @notice `IonPool` is the central contract of the Ion Protocol system. All
 * other contracts in the system revolve around it. Directly interacting with
 * `IonPool` may be unintuitive and it is recommended to interface with the
 * protocol through Handler contracts for a more UX-friendly experience.
 *
 * @custom:security-contact [email protected]
 */
contract IonPool is PausableUpgradeable, RewardToken {
    using SafeERC20 for IERC20;
    using SafeCast for *;
    using WadRayMath for *;
    using Math for uint256;
    using EnumerableSet for EnumerableSet.AddressSet;

    // --- Errors ---
    error CeilingExceeded(uint256 newDebt, uint256 debtCeiling);
    error UnsafePositionChange(uint256 newTotalDebtInVault, uint256 collateral, uint256 spot);
    error UnsafePositionChangeWithoutConsent(uint8 ilkIndex, address user, address unconsentedOperator);
    error GemTransferWithoutConsent(uint8 ilkIndex, address user, address unconsentedOperator);
    error UseOfCollateralWithoutConsent(uint8 ilkIndex, address depositor, address unconsentedOperator);
    error TakingWethWithoutConsent(address payer, address unconsentedOperator);
    error VaultCannotBeDusty(uint256 amountLeft, uint256 dust);
    error ArithmeticError();
    error IlkAlreadyAdded(address ilkAddress);
    error IlkNotInitialized(uint256 ilkIndex);
    error DepositSurpassesSupplyCap(uint256 depositAmount, uint256 supplyCap);
    error MaxIlksReached();

    error InvalidIlkAddress();
    error InvalidInterestRateModule(InterestRate invalidInterestRateModule);
    error InvalidWhitelist();

    // --- Events ---
    event IlkInitialized(uint8 indexed ilkIndex, address indexed ilkAddress);
    event IlkSpotUpdated(uint8 indexed ilkIndex, address newSpot);
    event IlkDebtCeilingUpdated(uint8 indexed ilkIndex, uint256 newDebtCeiling);
    event IlkDustUpdated(uint8 indexed ilkIndex, uint256 newDust);
    event SupplyCapUpdated(uint256 newSupplyCap);
    event InterestRateModuleUpdated(address newModule);
    event WhitelistUpdated(address newWhitelist);

    event AddOperator(address indexed user, address indexed operator);
    event RemoveOperator(address indexed user, address indexed operator);
    event MintAndBurnGem(uint8 indexed ilkIndex, address indexed usr, int256 wad);
    event TransferGem(uint8 indexed ilkIndex, address indexed src, address indexed dst, uint256 wad);

    event Supply(
        address indexed user, address indexed underlyingFrom, uint256 amount, uint256 supplyFactor, uint256 newDebt
    );

    event Withdraw(address indexed user, address indexed target, uint256 amount, uint256 supplyFactor, uint256 newDebt);

    event WithdrawCollateral(uint8 indexed ilkIndex, address indexed user, address indexed recipient, uint256 amount);
    event DepositCollateral(uint8 indexed ilkIndex, address indexed user, address indexed depositor, uint256 amount);
    event Borrow(
        uint8 indexed ilkIndex,
        address indexed user,
        address indexed recipient,
        uint256 amountOfNormalizedDebt,
        uint256 ilkRate,
        uint256 totalDebt
    );
    event Repay(
        uint8 indexed ilkIndex,
        address indexed user,
        address indexed payer,
        uint256 amountOfNormalizedDebt,
        uint256 ilkRate,
        uint256 totalDebt
    );

    event RepayBadDebt(address indexed user, address indexed payer, uint256 rad);
    event ConfiscateVault(
        uint8 indexed ilkIndex,
        address indexed u,
        address v,
        address indexed w,
        int256 changeInCollateral,
        int256 changeInNormalizedDebt
    );

    bytes32 public constant GEM_JOIN_ROLE = keccak256("GEM_JOIN_ROLE");
    bytes32 public constant LIQUIDATOR_ROLE = keccak256("LIQUIDATOR_ROLE");
    bytes32 public constant PAUSE_ROLE = keccak256("PAUSE_ROLE");

    address private immutable ADDRESS_THIS = address(this);

    // --- Modifiers ---
    modifier onlyWhitelistedBorrowers(uint8 ilkIndex, address user, bytes32[] memory proof) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        $.whitelist.isWhitelistedBorrower(ilkIndex, _msgSender(), user, proof);
        _;
    }

    modifier onlyWhitelistedLenders(address user, bytes32[] memory proof) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        $.whitelist.isWhitelistedLender(_msgSender(), user, proof);
        _;
    }

    // --- Data ---
    struct Ilk {
        uint104 totalNormalizedDebt; // Total Normalised Debt     [WAD]
        uint104 rate; // Accumulated Rates         [RAY]
        uint48 lastRateUpdate; // block.timestamp of last update; overflows in 800_000 years
        SpotOracle spot; // Oracle that provides price with safety margin
        uint256 debtCeiling; // Debt Ceiling              [RAD]
        uint256 dust; // Vault Debt Floor            [RAD]
    }

    struct Vault {
        uint256 collateral; // Locked Collateral  [WAD]
        uint256 normalizedDebt; // Normalised Debt    [WAD]
    }

    /// @custom:storage-location erc7201:ion.storage.IonPool
    struct IonPoolStorage {
        Ilk[] ilks;
        // remove() should never be called, it will mess up the ordering
        EnumerableSet.AddressSet ilkAddresses;
        mapping(uint256 ilkIndex => mapping(address user => Vault)) vaults;
        mapping(uint256 ilkIndex => mapping(address user => uint256)) gem; // [WAD]
        mapping(address unbackedDebtor => uint256) unbackedDebt; // [RAD]
        mapping(address user => mapping(address operator => uint256)) isOperator;
        uint256 debt; // Total Debt [RAD]
        uint256 liquidity; // liquidity in pool [WAD]
        uint256 supplyCap; // [WAD]
        uint256 totalUnbackedDebt; // Total Unbacked Underlying  [RAD]
        InterestRate interestRateModule;
        Whitelist whitelist;
    }

    // keccak256(abi.encode(uint256(keccak256("ion.storage.IonPool")) - 1)) & ~bytes32(uint256(0xff))
    // solhint-disable-next-line
    bytes32 private constant IonPoolStorageLocation = 0xceba3d526b4d5afd91d1b752bf1fd37917c20a6daf576bcb41dd1c57c1f67e00;

    function _getIonPoolStorage() internal pure returns (IonPoolStorage storage $) {
        assembly {
            $.slot := IonPoolStorageLocation
        }
    }

    constructor() {
        _disableInitializers();
    }

    function initialize(
        address _underlying,
        address _treasury,
        uint8 decimals_,
        string memory name_,
        string memory symbol_,
        address initialDefaultAdmin,
        InterestRate _interestRateModule,
        Whitelist _whitelist
    )
        external
        initializer
    {
        __AccessControlDefaultAdminRules_init(0, initialDefaultAdmin);
        RewardToken._initialize(_underlying, _treasury, decimals_, name_, symbol_);

        _grantRole(ION, initialDefaultAdmin);

        IonPoolStorage storage $ = _getIonPoolStorage();

        $.interestRateModule = _interestRateModule;
        $.whitelist = _whitelist;

        emit InterestRateModuleUpdated(address(_interestRateModule));
        emit WhitelistUpdated(address(_whitelist));
    }

    // --- Administration ---

    /**
     * @notice Initializes a market with a new collateral type.
     * @dev This function and the entire protocol as a whole operates under the
     * assumption that there will never be more than 256 collaterals.
     * @param ilkAddress address of the ERC-20 collateral.
     */
    function initializeIlk(address ilkAddress) external onlyRole(ION) {
        IonPoolStorage storage $ = _getIonPoolStorage();

        if (ilkAddress == address(0)) revert InvalidIlkAddress();
        if (!$.ilkAddresses.add(ilkAddress)) revert IlkAlreadyAdded(ilkAddress);

        uint256 ilksLength = $.ilks.length;

        // Explicitly enforce the max number of collaterals
        if (ilksLength >= uint256(type(uint8).max) + 1) revert MaxIlksReached();

        // Unsafe cast OK since we don't plan on having more than 256
        // collaterals
        uint8 ilkIndex = uint8(ilksLength);
        Ilk memory newIlk;
        $.ilks.push(newIlk);
        Ilk storage ilk = $.ilks[ilkIndex];

        ilk.rate = uint104(RAY);
        // Unsafe cast OK
        ilk.lastRateUpdate = uint48(block.timestamp);

        emit IlkInitialized(ilkIndex, ilkAddress);
    }

    /**
     * @dev Updates the spot oracle for a given collateral.
     * @param ilkIndex index of the collateral.
     * @param newSpot address of the new spot oracle.
     */
    function updateIlkSpot(uint8 ilkIndex, SpotOracle newSpot) external onlyRole(ION) {
        IonPoolStorage storage $ = _getIonPoolStorage();

        $.ilks[ilkIndex].spot = newSpot;

        emit IlkSpotUpdated(ilkIndex, address(newSpot));
    }

    /**
     * @notice A market can be sunset by setting the debt ceiling to 0. It would
     * still be possible to repay debt but creating new debt would not be
     * possible.
     * @dev Updates the debt ceiling for a given collateral.
     * @param ilkIndex index of the collateral.
     * @param newCeiling new debt ceiling.
     */
    function updateIlkDebtCeiling(uint8 ilkIndex, uint256 newCeiling) external onlyRole(ION) {
        IonPoolStorage storage $ = _getIonPoolStorage();

        $.ilks[ilkIndex].debtCeiling = newCeiling;

        emit IlkDebtCeilingUpdated(ilkIndex, newCeiling);
    }

    /**
     * @notice When increasing the `dust`, it is possible that some vaults will
     * be dusty after the update. However, changes to the vault position from
     * there will require that the vault be non-dusty (either by repaying all
     * debt or increasing debt beyond the `dust`).
     * @dev Updates the dust amount for a given collateral.
     * @param ilkIndex index of the collateral.
     * @param newDust new dust
     */
    function updateIlkDust(uint8 ilkIndex, uint256 newDust) external onlyRole(ION) {
        IonPoolStorage storage $ = _getIonPoolStorage();

        $.ilks[ilkIndex].dust = newDust;

        emit IlkDustUpdated(ilkIndex, newDust);
    }

    /**
     * @notice Reducing the supply cap will not affect existing deposits.
     * However, if it is below the `totalSupply`, then no new deposits will be
     * allowed until the `totalSupply` is below the new `supplyCap`.
     * @dev Updates the supply cap.
     * @param newSupplyCap new supply cap.
     */
    function updateSupplyCap(uint256 newSupplyCap) external onlyRole(ION) {
        IonPoolStorage storage $ = _getIonPoolStorage();

        $.supplyCap = newSupplyCap;

        emit SupplyCapUpdated(newSupplyCap);
    }

    /**
     * @dev Updates the interest rate module. There is a check to ensure that
     * `collateralCount()` on the new interest rate module match the current
     * number of collaterals in the pool.
     * @param _interestRateModule new interest rate module.
     */
    function updateInterestRateModule(InterestRate _interestRateModule) external onlyRole(ION) {
        if (address(_interestRateModule) == address(0)) revert InvalidInterestRateModule(_interestRateModule);

        IonPoolStorage storage $ = _getIonPoolStorage();

        // Sanity check
        if (_interestRateModule.COLLATERAL_COUNT() != $.ilks.length) {
            revert InvalidInterestRateModule(_interestRateModule);
        }
        $.interestRateModule = _interestRateModule;

        emit InterestRateModuleUpdated(address(_interestRateModule));
    }

    /**
     * @dev Updates the whitelist.
     * @param _whitelist new whitelist address.
     */
    function updateWhitelist(Whitelist _whitelist) external onlyRole(ION) {
        if (address(_whitelist) == address(0)) revert InvalidWhitelist();

        IonPoolStorage storage $ = _getIonPoolStorage();

        $.whitelist = _whitelist;

        emit WhitelistUpdated(address(_whitelist));
    }

    /**
     * @dev Pause actions but accrue interest as well.
     *
     * Under certain protocol conditions, we want to be able to pause the
     * protocol automatically through monitoring systems. So we want to be able
     * to grant the PAUSE_ROLE to those private keys. In the case of a
     * compromised private key, we can revoke the PAUSE_ROLE from that private
     * key and grant it to a new private key. Unpausing will remain a multisig
     * operation.
     */
    function pause() external onlyRole(PAUSE_ROLE) {
        _accrueInterest();
        _pause();
    }

    /**
     * @dev Unpause actions but this will also update the `lastRateUpdate` to
     * the unpause transaction timestamp. This essentially allows for a pausing
     * and unpausing of the accrual of interest.
     */
    function unpause() external onlyRole(ION) {
        _unpause();
        IonPoolStorage storage $ = _getIonPoolStorage();

        uint256 ilksLength = $.ilks.length;
        for (uint256 i = 0; i < ilksLength;) {
            // Unsafe cast OK
            $.ilks[i].lastRateUpdate = uint48(block.timestamp);

            // forgefmt: disable-next-line
            unchecked { ++i; }
        }
    }

    // --- Interest Calculations ---

    /**
     * @dev Updates accumulators for all `ilk`s based on current interest rates.
     * @return newTotalDebt the new total debt after interest accrual
     */
    function accrueInterest() external whenNotPaused returns (uint256 newTotalDebt) {
        return _accrueInterest();
    }

    function _accrueInterest() internal returns (uint256 newTotalDebt) {
        IonPoolStorage storage $ = _getIonPoolStorage();

        uint256 totalEthSupply = totalSupplyUnaccrued();

        uint256 totalSupplyFactorIncrease;
        uint256 totalTreasuryMintAmount;
        uint256 totalDebtIncrease;

        uint256 ilksLength = $.ilks.length;
        for (uint8 i = 0; i < ilksLength;) {
            (
                uint256 supplyFactorIncrease,
                uint256 treasuryMintAmount,
                uint104 newRateIncrease,
                uint256 newDebtIncrease,
                uint48 timestampIncrease
            ) = _calculateRewardAndDebtDistributionForIlk(i, totalEthSupply);

            if (timestampIncrease > 0) {
                Ilk storage ilk = $.ilks[i];
                ilk.rate += newRateIncrease;
                ilk.lastRateUpdate += timestampIncrease;
                totalDebtIncrease += newDebtIncrease;

                totalSupplyFactorIncrease += supplyFactorIncrease;
                totalTreasuryMintAmount += treasuryMintAmount;
            }

            // forgefmt: disable-next-line
            unchecked { ++i; }
        }

        newTotalDebt = $.debt + totalDebtIncrease;
        $.debt = newTotalDebt;
        _setSupplyFactor(supplyFactorUnaccrued() + totalSupplyFactorIncrease);
        _mintToTreasury(totalTreasuryMintAmount);
    }

    function calculateRewardAndDebtDistribution()
        public
        view
        override
        returns (
            uint256 totalSupplyFactorIncrease,
            uint256 totalTreasuryMintAmount,
            uint104[] memory rateIncreases,
            uint256 totalDebtIncrease,
            uint48[] memory timestampIncreases
        )
    {
        IonPoolStorage storage $ = _getIonPoolStorage();

        uint256 ilksLength = $.ilks.length;

        rateIncreases = new uint104[](ilksLength);
        timestampIncreases = new uint48[](ilksLength);

        uint256 totalEthSupply = totalSupplyUnaccrued();

        for (uint8 i = 0; i < ilksLength;) {
            (
                uint256 supplyFactorIncrease,
                uint256 treasuryMintAmount,
                uint104 newRateIncrease,
                uint256 newDebtIncrease,
                uint48 timestampIncrease
            ) = _calculateRewardAndDebtDistributionForIlk(i, totalEthSupply);

            if (timestampIncrease > 0) {
                rateIncreases[i] = newRateIncrease;
                timestampIncreases[i] = timestampIncrease;
                totalDebtIncrease += newDebtIncrease;

                totalSupplyFactorIncrease += supplyFactorIncrease;
                totalTreasuryMintAmount += treasuryMintAmount;
            }

            // forgefmt: disable-next-line
            unchecked { ++i; }
        }
    }

    /**
     * @notice This is primarily for simulation purposes to see how an
     * individual ilk's state will change after an accrual.
     * @param ilkIndex index of the collateral.
     * @return newRateIncrease the rate increase for the ilk.
     * @return timestampIncrease the timestamp increase for the ilk.
     */
    function calculateRewardAndDebtDistributionForIlk(uint8 ilkIndex)
        public
        view
        returns (uint104 newRateIncrease, uint48 timestampIncrease)
    {
        (,, newRateIncrease,, timestampIncrease) =
            _calculateRewardAndDebtDistributionForIlk(ilkIndex, totalSupplyUnaccrued());
    }

    function _calculateRewardAndDebtDistributionForIlk(
        uint8 ilkIndex,
        uint256 totalEthSupply
    )
        internal
        view
        returns (
            uint256 supplyFactorIncrease,
            uint256 treasuryMintAmount,
            uint104 newRateIncrease,
            uint256 newDebtIncrease,
            uint48 timestampIncrease
        )
    {
        IonPoolStorage storage $ = _getIonPoolStorage();
        Ilk storage ilk = $.ilks[ilkIndex];

        uint256 _totalNormalizedDebt = ilk.totalNormalizedDebt;
        // Because all interest that would have accrued during a pause is
        // cancelled upon `unpause`, we return zero interest while markets are
        // paused.
        if (_totalNormalizedDebt == 0 || block.timestamp == ilk.lastRateUpdate || paused()) {
            // Unsafe cast OK
            // block.timestamp - ilk.lastRateUpdate will almost always be 0
            // here. The exception is on first borrow.
            return (0, 0, 0, 0, uint48(block.timestamp - ilk.lastRateUpdate));
        }

        uint256 totalDebt = _totalNormalizedDebt * ilk.rate; // [WAD] * [RAY] = [RAD]

        (uint256 borrowRate, uint256 reserveFactor) =
            $.interestRateModule.calculateInterestRate(ilkIndex, totalDebt, totalEthSupply);

        // Unsafe cast OK
        timestampIncrease = uint48(block.timestamp) - ilk.lastRateUpdate;

        if (borrowRate == 0) return (0, 0, 0, 0, timestampIncrease);

        // Calculates borrowRate ^ (time) and returns the result with RAY precision
        uint256 borrowRateExpT = _rpow(borrowRate + RAY, timestampIncrease, RAY);

        // Debt distribution
        // This form of rate accrual is much safer than distributing the new
        // debt increase to the total debt since low debt amounts won't cause
        // rounding errors to sky rocket the rate. This form of accrual is still
        // subject to rate inflation, however, it would only be from an
        // extremely high borrow rate rather than being a function of the
        // current total debt in the system. This is very relevant for
        // sunsetting markets, where the goal will be to reduce the total debt
        // to 0.
        newRateIncrease = ilk.rate.rayMulUp(borrowRateExpT - RAY).toUint104(); // [RAY]

        newDebtIncrease = _totalNormalizedDebt * newRateIncrease; // [RAD]

        // Income distribution
        uint256 _normalizedTotalSupply = normalizedTotalSupplyUnaccrued(); // [WAD]

        // If there is no supply, then nothing is being lent out.
        supplyFactorIncrease = _normalizedTotalSupply == 0
            ? 0
            : newDebtIncrease.mulDiv(RAY - reserveFactor, _normalizedTotalSupply.scaleUpToRad(18)); // [RAD] * [RAY] / [RAD]
            // = [RAY]

        treasuryMintAmount = newDebtIncrease.mulDiv(reserveFactor, 1e54); // [RAD] * [RAY] / 1e54 = [WAD]
    }

    // --- Lender Operations ---

    /**
     * @dev Allows lenders to redeem their interest-bearing position for the
     * underlying asset. It is possible that dust amounts more of the position
     * are burned than the underlying received due to rounding.
     * @param receiverOfUnderlying the address to which the redeemed underlying
     * asset should be sent to.
     * @param amount of underlying to reedeem for.
     */
    function withdraw(address receiverOfUnderlying, uint256 amount) external whenNotPaused {
        uint256 newTotalDebt = _accrueInterest();
        IonPoolStorage storage $ = _getIonPoolStorage();

        $.liquidity -= amount;

        uint256 _supplyFactor =
            _burn({ user: _msgSender(), receiverOfUnderlying: receiverOfUnderlying, amount: amount });

        emit Withdraw(_msgSender(), receiverOfUnderlying, amount, _supplyFactor, newTotalDebt);
    }

    /**
     * @dev Allows lenders to deposit their underlying asset into the pool and
     * earn interest on it.
     * @param user the address to receive credit for the position.
     * @param amount of underlying asset to use to create the position.
     * @param proof merkle proof that the user is whitelisted.
     */
    function supply(
        address user,
        uint256 amount,
        bytes32[] calldata proof
    )
        external
        whenNotPaused
        onlyWhitelistedLenders(user, proof)
    {
        uint256 newTotalDebt = _accrueInterest();
        IonPoolStorage storage $ = _getIonPoolStorage();

        $.liquidity += amount;

        uint256 _supplyFactor = _mint({ user: user, senderOfUnderlying: _msgSender(), amount: amount });

        uint256 _supplyCap = $.supplyCap;

        if (totalSupply() > _supplyCap) revert DepositSurpassesSupplyCap(amount, _supplyCap);

        emit Supply(user, _msgSender(), amount, _supplyFactor, newTotalDebt);
    }

    // --- Borrower Operations ---

    /**
     * @dev Allows a borrower to create debt in a position.
     * @param ilkIndex index of the collateral.
     * @param user to create the position for.
     * @param recipient to receive the borrowed funds
     * @param amountOfNormalizedDebt to create.
     * @param proof merkle proof that the user is whitelist.
     */
    function borrow(
        uint8 ilkIndex,
        address user,
        address recipient,
        uint256 amountOfNormalizedDebt,
        bytes32[] memory proof
    )
        external
        whenNotPaused
        onlyWhitelistedBorrowers(ilkIndex, user, proof)
    {
        _accrueInterest();
        (uint104 ilkRate, uint256 newDebt) =
            _modifyPosition(ilkIndex, user, address(0), recipient, 0, amountOfNormalizedDebt.toInt256());

        emit Borrow(ilkIndex, user, recipient, amountOfNormalizedDebt, ilkRate, newDebt);
    }

    /**
     * @dev Allows a borrower to repay debt in a position.
     * @param ilkIndex index of the collateral.
     * @param user to repay the debt for.
     * @param payer to source the funds from.
     * @param amountOfNormalizedDebt to repay.
     */
    function repay(
        uint8 ilkIndex,
        address user,
        address payer,
        uint256 amountOfNormalizedDebt
    )
        external
        whenNotPaused
    {
        _accrueInterest();
        (uint104 ilkRate, uint256 newDebt) =
            _modifyPosition(ilkIndex, user, address(0), payer, 0, -(amountOfNormalizedDebt.toInt256()));

        emit Repay(ilkIndex, user, payer, amountOfNormalizedDebt, ilkRate, newDebt);
    }

    /**
     * @dev Moves collateral from internal `vault.collateral` balances to `gem`
     * @param ilkIndex index of the collateral.
     * @param user to withdraw the collateral for.
     * @param recipient to receive the collateral.
     * @param amount to withdraw.
     */
    function withdrawCollateral(
        uint8 ilkIndex,
        address user,
        address recipient,
        uint256 amount
    )
        external
        whenNotPaused
    {
        _accrueInterest();
        _modifyPosition(ilkIndex, user, recipient, address(0), -(amount.toInt256()), 0);

        emit WithdrawCollateral(ilkIndex, user, recipient, amount);
    }

    /**
     * @dev Moves collateral from `gem` balances to internal `vault.collateral`
     * @param ilkIndex index of the collateral.
     * @param user to deposit the collateral for.
     * @param depositor to deposit the collateral from.
     * @param amount to deposit.
     * @param proof merkle proof that the user is whitelisted.
     */
    function depositCollateral(
        uint8 ilkIndex,
        address user,
        address depositor,
        uint256 amount,
        bytes32[] calldata proof
    )
        external
        whenNotPaused
        onlyWhitelistedBorrowers(ilkIndex, user, proof)
    {
        _accrueInterest();
        _modifyPosition(ilkIndex, user, depositor, address(0), amount.toInt256(), 0);

        emit DepositCollateral(ilkIndex, user, depositor, amount);
    }

    // --- CDP Manipulation ---

    function _modifyPosition(
        uint8 ilkIndex,
        address u,
        address v,
        address w,
        int256 changeInCollateral,
        int256 changeInNormalizedDebt
    )
        internal
        returns (uint104 ilkRate, uint256 newTotalDebt)
    {
        IonPoolStorage storage $ = _getIonPoolStorage();

        ilkRate = $.ilks[ilkIndex].rate;
        // ilk has been initialised
        if (ilkRate == 0) revert IlkNotInitialized(ilkIndex);

        Vault memory _vault = $.vaults[ilkIndex][u];
        _vault.collateral = _add(_vault.collateral, changeInCollateral);
        _vault.normalizedDebt = _add(_vault.normalizedDebt, changeInNormalizedDebt);

        uint104 _totalNormalizedDebt = _add($.ilks[ilkIndex].totalNormalizedDebt, changeInNormalizedDebt).toUint104();

        // Prevent stack too deep
        {
            uint256 newTotalDebtInVault = ilkRate * _vault.normalizedDebt;
            // either debt has decreased, or debt ceilings are not exceeded
            if (
                both(
                    changeInNormalizedDebt > 0,
                    uint256(_totalNormalizedDebt) * uint256(ilkRate) > $.ilks[ilkIndex].debtCeiling
                )
            ) {
                revert CeilingExceeded(uint256(_totalNormalizedDebt) * uint256(ilkRate), $.ilks[ilkIndex].debtCeiling);
            }
            uint256 ilkSpot = $.ilks[ilkIndex].spot.getSpot();
            // vault is either less risky than before, or it is safe
            if (
                both(
                    either(changeInNormalizedDebt > 0, changeInCollateral < 0),
                    newTotalDebtInVault > _vault.collateral * ilkSpot
                )
            ) revert UnsafePositionChange(newTotalDebtInVault, _vault.collateral, ilkSpot);

            // vault is either more safe, or the owner consents
            if (both(either(changeInNormalizedDebt > 0, changeInCollateral < 0), !isAllowed(u, _msgSender()))) {
                revert UnsafePositionChangeWithoutConsent(ilkIndex, u, _msgSender());
            }

            // collateral src consents
            if (both(changeInCollateral > 0, !isAllowed(v, _msgSender()))) {
                revert UseOfCollateralWithoutConsent(ilkIndex, v, _msgSender());
            }
            // debt dst consents
            // Since changeInDebt is no longer being deducted in the form of
            // internal accounting but rather directly in the erc20 WETH form, this
            // contract must also have an approved role for the debt dst address on
            // th erc20 WETH contract. Or else, the transfer will fail.
            if (both(changeInNormalizedDebt < 0, !isAllowed(w, _msgSender()))) {
                revert TakingWethWithoutConsent(w, _msgSender());
            }

            // vault has no debt, or a non-dusty amount
            if (both(_vault.normalizedDebt != 0, newTotalDebtInVault < $.ilks[ilkIndex].dust)) {
                revert VaultCannotBeDusty(newTotalDebtInVault, $.ilks[ilkIndex].dust);
            }
        }

        int256 changeInDebt = ilkRate.toInt256() * changeInNormalizedDebt;

        $.gem[ilkIndex][v] = _sub($.gem[ilkIndex][v], changeInCollateral);
        $.vaults[ilkIndex][u] = _vault;
        $.ilks[ilkIndex].totalNormalizedDebt = _totalNormalizedDebt;
        newTotalDebt = _add($.debt, changeInDebt);
        $.debt = newTotalDebt;

        // If changeInDebt < 0, it is a repayment and WETH is being transferred
        // into the protocol
        _transferWeth(w, changeInDebt);
    }

    // --- Settlement ---

    /**
     * @dev To be used by protocol to settle bad debt using reserves
     * NOTE: Can pay another user's bad debt with the sender's asset
     * @param user the address that owns the bad debt being paid off
     * @param rad amount of debt to be repaid (45 decimals)
     */
    function repayBadDebt(address user, uint256 rad) external whenNotPaused {
        IonPoolStorage storage $ = _getIonPoolStorage();

        $.unbackedDebt[user] -= rad;
        $.totalUnbackedDebt -= rad;
        $.debt -= rad;

        // Must be negative since it is a repayment
        _transferWeth(_msgSender(), -(rad.toInt256()));

        emit RepayBadDebt(user, _msgSender(), rad);
    }

    // --- Helpers ---

    /**
     * @dev Helper function to deal with borrowing and repaying debt. A positive
     * amount is a borrow while negative amount is a repayment
     * @param user receiver if transfer to, or sender if transfer from
     * @param amount amount to transfer [RAD]
     */
    function _transferWeth(address user, int256 amount) internal {
        if (amount == 0) return;
        IonPoolStorage storage $ = _getIonPoolStorage();

        if (amount < 0) {
            uint256 amountUint = uint256(-amount);
            uint256 amountWad = amountUint / RAY;
            if (amountUint % RAY > 0) ++amountWad;

            $.liquidity += amountWad;
            underlying().safeTransferFrom(user, address(this), amountWad);
        } else {
            // Round down in protocol's favor
            uint256 amountWad = uint256(amount) / RAY;

            $.liquidity -= amountWad;

            underlying().safeTransfer(user, amountWad);
        }
    }

    // --- CDP Confiscation ---

    /**
     * @dev This function foregoes pausability for pausability at the
     * liquidation module layer
     * @param ilkIndex index of the collateral.
     * @param u user to confiscate the vault from.
     * @param v address to either credit `gem` to or deduct `gem` from
     * @param changeInCollateral collateral to add or remove from the vault
     * @param changeInNormalizedDebt debt to add or remove from the vault
     */
    function confiscateVault(
        uint8 ilkIndex,
        address u,
        address v,
        address w,
        int256 changeInCollateral,
        int256 changeInNormalizedDebt
    )
        external
        whenNotPaused
        onlyRole(LIQUIDATOR_ROLE)
    {
        _accrueInterest();

        IonPoolStorage storage $ = _getIonPoolStorage();

        Vault storage _vault = $.vaults[ilkIndex][u];
        Ilk storage ilk = $.ilks[ilkIndex];
        uint104 ilkRate = ilk.rate;

        _vault.collateral = _add(_vault.collateral, changeInCollateral);
        _vault.normalizedDebt = _add(_vault.normalizedDebt, changeInNormalizedDebt);
        ilk.totalNormalizedDebt = _add(uint256(ilk.totalNormalizedDebt), changeInNormalizedDebt).toUint104();

        // Unsafe cast OK since we know that ilkRate is less than 2^104
        int256 changeInDebt = int256(uint256(ilkRate)) * changeInNormalizedDebt;

        $.gem[ilkIndex][v] = _sub($.gem[ilkIndex][v], changeInCollateral);
        $.unbackedDebt[w] = _sub($.unbackedDebt[w], changeInDebt);
        $.totalUnbackedDebt = _sub($.totalUnbackedDebt, changeInDebt);

        emit ConfiscateVault(ilkIndex, u, v, w, changeInCollateral, changeInNormalizedDebt);
    }

    // --- Fungibility ---

    /**
     * @dev To be called by GemJoin contracts. After a user deposits collateral, credit the user with collateral
     * internally
     * @param ilkIndex collateral
     * @param usr user
     * @param wad amount to add or remove
     */
    function mintAndBurnGem(uint8 ilkIndex, address usr, int256 wad) external onlyRole(GEM_JOIN_ROLE) whenNotPaused {
        IonPoolStorage storage $ = _getIonPoolStorage();

        $.gem[ilkIndex][usr] = _add($.gem[ilkIndex][usr], wad);

        emit MintAndBurnGem(ilkIndex, usr, wad);
    }

    /**
     * @dev Transfer gem across the internal accounting of the pool
     * @param ilkIndex index of the collateral
     * @param src source of the gem
     * @param dst destination of the gem
     * @param wad amount of gem
     */
    function transferGem(uint8 ilkIndex, address src, address dst, uint256 wad) external whenNotPaused {
        if (!isAllowed(src, _msgSender())) revert GemTransferWithoutConsent(ilkIndex, src, _msgSender());

        IonPoolStorage storage $ = _getIonPoolStorage();

        $.gem[ilkIndex][src] -= wad;
        $.gem[ilkIndex][dst] += wad;
        emit TransferGem(ilkIndex, src, dst, wad);
    }

    // --- Getters ---

    /**
     * @return The address of the collateral at index `ilkIndex`.
     */
    function getIlkAddress(uint256 ilkIndex) external view returns (address) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return $.ilkAddresses.at(ilkIndex);
    }

    /**
     * @return The rate (debt accumulator) for collateral with index `ilkIndex`.
     */
    function rate(uint8 ilkIndex) external view returns (uint256) {
        IonPoolStorage storage $ = _getIonPoolStorage();

        (uint256 newRateIncrease,) = calculateRewardAndDebtDistributionForIlk(ilkIndex);

        return $.ilks[ilkIndex].rate + newRateIncrease;
    }

    /**
     * @return dust amount for collateral with index `ilkIndex`.
     */
    function dust(uint8 ilkIndex) external view returns (uint256) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return $.ilks[ilkIndex].dust;
    }

    /**
     * @return The amount of collateral `user` has for collateral with index `ilkIndex`.
     */
    function collateral(uint8 ilkIndex, address user) external view returns (uint256) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return $.vaults[ilkIndex][user].collateral;
    }

    /**
     * @return The amount of normalized debt `user` has for collateral with index `ilkIndex`.
     */
    function normalizedDebt(uint8 ilkIndex, address user) external view returns (uint256) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return $.vaults[ilkIndex][user].normalizedDebt;
    }

    /**
     * @return All data within vault for `user` with index `ilkIndex`.
     */
    function vault(uint8 ilkIndex, address user) external view returns (uint256, uint256) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return ($.vaults[ilkIndex][user].collateral, $.vaults[ilkIndex][user].normalizedDebt);
    }

    /**
     * @return Whether or not `operator` has permission to make unsafe changes
     * to `user`'s positions.
     */
    function isAllowed(address user, address operator) public view returns (bool) {
        IonPoolStorage storage $ = _getIonPoolStorage();

        return either(user == operator, $.isOperator[user][operator] == 1);
    }

    /**
     * @dev Gets the current borrow rate for borrowing against a given collateral.
     */
    function getCurrentBorrowRate(uint8 ilkIndex) external view returns (uint256 borrowRate, uint256 reserveFactor) {
        IonPoolStorage storage $ = _getIonPoolStorage();

        uint256 totalEthSupply = totalSupplyUnaccrued();

        uint256 _totalNormalizedDebt = $.ilks[ilkIndex].totalNormalizedDebt;
        uint256 _rate = $.ilks[ilkIndex].rate;

        uint256 totalDebt = _totalNormalizedDebt * _rate; // [WAD] * [RAY] / [WAD] = [RAY]

        (borrowRate, reserveFactor) = $.interestRateModule.calculateInterestRate(ilkIndex, totalDebt, totalEthSupply);
        borrowRate += RAY;
    }

    function extsload(bytes32 slot) external view returns (bytes32 value) {
        assembly {
            value := sload(slot)
        }
    }

    /**
     * @dev Address of the implementation. This is stored immutably on the
     * implementation so that it can be read by the proxy.
     */
    function implementation() external view returns (address) {
        return ADDRESS_THIS;
    }

    // --- Auth ---

    /**
     * @dev Allows an `operator` to make unsafe changes to `_msgSender()`s
     * positions.
     */
    function addOperator(address operator) external {
        IonPoolStorage storage $ = _getIonPoolStorage();

        $.isOperator[_msgSender()][operator] = 1;

        emit AddOperator(_msgSender(), operator);
    }

    /**
     * @dev Disallows an `operator` to make unsafe changes to `_msgSender()`s
     * positions.
     */
    function removeOperator(address operator) external {
        IonPoolStorage storage $ = _getIonPoolStorage();

        $.isOperator[_msgSender()][operator] = 0;

        emit RemoveOperator(_msgSender(), operator);
    }

    // --- Math ---

    function _add(uint256 x, int256 y) internal pure returns (uint256 z) {
        // Overflow desirable
        unchecked {
            z = x + uint256(y);
        }
        if (y < 0 && z > x) revert ArithmeticError();
        if (y > 0 && z < x) revert ArithmeticError();
    }

    function _sub(uint256 x, int256 y) internal pure returns (uint256 z) {
        // Underflow desirable
        unchecked {
            z = x - uint256(y);
        }
        if (y > 0 && z > x) revert ArithmeticError();
        if (y < 0 && z < x) revert ArithmeticError();
    }

    /**
     * @dev x and the returned value are to be interpreted as fixed-point
     * integers with scaling factor b. For example, if b == 100, this specifies
     * two decimal digits of precision and the normal decimal value 2.1 would be
     * represented as 210; rpow(210, 2, 100) returns 441 (the two-decimal digit
     * fixed-point representation of 2.1^2 = 4.41) (From MCD docs)
     * @param x base
     * @param n exponent
     * @param b scaling factor
     */
    function _rpow(uint256 x, uint256 n, uint256 b) internal pure returns (uint256 z) {
        assembly {
            switch x
            case 0 {
                switch n
                case 0 { z := b }
                default { z := 0 }
            }
            default {
                switch mod(n, 2)
                case 0 { z := b }
                default { z := x }
                let half := div(b, 2) // for rounding.
                for { n := div(n, 2) } n { n := div(n, 2) } {
                    let xx := mul(x, x)
                    if iszero(eq(div(xx, x), x)) { revert(0, 0) }
                    let xxRound := add(xx, half)
                    if lt(xxRound, xx) { revert(0, 0) }
                    x := div(xxRound, b)
                    if mod(n, 2) {
                        let zx := mul(z, x)
                        if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0, 0) }
                        let zxRound := add(zx, half)
                        if lt(zxRound, zx) { revert(0, 0) }
                        z := div(zxRound, b)
                    }
                }
            }
        }
    }

    // --- Boolean ---

    function either(bool x, bool y) internal pure returns (bool z) {
        assembly {
            z := or(x, y)
        }
    }

    function both(bool x, bool y) internal pure returns (bool z) {
        assembly {
            z := and(x, y)
        }
    }
}

File 2 of 36 : Whitelist.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.21;

import { Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";

/**
 * @notice An external Whitelist module that Ion's system-wide contracts can use
 * to verify that a user is permitted to borrow or lend.
 *
 * A merkle whitelist is used to allow for a large number of addresses to be
 * whitelisted without consuming infordinate amounts of gas for the updates.
 *
 * There is also a protocol whitelist that can be used to allow for a protocol
 * controlled address to bypass the merkle proof check. These
 * protocol-controlled contract are expected to perform whitelist checks
 * themsleves on their own entrypoints.
 *
 * @dev The full merkle tree is stored off-chain and only the root is stored
 * on-chain.
 *
 * @custom:security-contact [email protected]
 */
contract Whitelist is Ownable2Step {
    mapping(address protocolControlledAddress => bool) public protocolWhitelist; // peripheral addresses that can bypass
        // the merkle proof check

    mapping(uint8 ilkIndex => bytes32) public borrowersRoot; // root of the merkle tree of borrowers for each ilk

    bytes32 public lendersRoot; // root of the merkle tree of lenders for each ilk

    // --- Errors ---

    error NotWhitelistedBorrower(uint8 ilkIndex, address addr);
    error NotWhitelistedLender(address addr);

    /**
     * @notice Creates a new `Whitelist` instance.
     * @param _borrowersRoots List borrower merkle roots for each ilk.
     * @param _lendersRoot The lender merkle root.
     */
    constructor(bytes32[] memory _borrowersRoots, bytes32 _lendersRoot) Ownable(msg.sender) {
        for (uint8 i = 0; i < _borrowersRoots.length; i++) {
            borrowersRoot[i] = _borrowersRoots[i];
        }
        lendersRoot = _lendersRoot;
    }

    /**
     * @notice Updates the borrower merkle root for a specific ilk.
     * @param ilkIndex of the ilk.
     * @param _borrowersRoot The new borrower merkle root.
     */
    function updateBorrowersRoot(uint8 ilkIndex, bytes32 _borrowersRoot) external onlyOwner {
        borrowersRoot[ilkIndex] = _borrowersRoot;
    }

    /**
     * @notice Updates the lender merkle root.
     * @param _lendersRoot The new lender merkle root.
     */
    function updateLendersRoot(bytes32 _lendersRoot) external onlyOwner {
        lendersRoot = _lendersRoot;
    }

    /**
     * @notice Approves a protocol controlled address to bypass the merkle proof check.
     * @param addr The address to approve.
     */
    function approveProtocolWhitelist(address addr) external onlyOwner {
        protocolWhitelist[addr] = true;
    }

    /**
     * @notice Revokes a protocol controlled address to bypass the merkle proof check.
     * @param addr The address to revoke approval for.
     */
    function revokeProtocolWhitelist(address addr) external onlyOwner {
        protocolWhitelist[addr] = false;
    }

    /**
     * @notice Called by external modifiers to prove inclusion as a borrower.
     * @dev If the root is just zero, then the whitelist is effectively turned
     * off as every address will be allowed.
     * @return True if the addr is part of the borrower whitelist or the
     * protocol whitelist. False otherwise.
     */
    function isWhitelistedBorrower(
        uint8 ilkIndex,
        address poolCaller,
        address addr,
        bytes32[] calldata proof
    )
        external
        view
        returns (bool)
    {
        if (protocolWhitelist[poolCaller]) return true;
        bytes32 root = borrowersRoot[ilkIndex];
        if (root == 0) return true;
        bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(addr))));
        if (MerkleProof.verify(proof, root, leaf)) {
            return true;
        } else {
            revert NotWhitelistedBorrower(ilkIndex, addr);
        }
    }

    /**
     * @notice Called by external modifiers to prove inclusion as a lender.
     * @dev If the root is just zero, then the whitelist is effectively turned
     * off as every address will be allowed.
     * @return True if the addr is part of the lender whitelist or the protocol
     * whitelist. False otherwise.
     */
    function isWhitelistedLender(
        address poolCaller,
        address addr,
        bytes32[] calldata proof
    )
        external
        view
        returns (bool)
    {
        if (protocolWhitelist[poolCaller]) return true;
        bytes32 root = lendersRoot;
        if (root == bytes32(0)) return true;
        bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(addr))));
        if (MerkleProof.verify(proof, root, leaf)) {
            return true;
        } else {
            revert NotWhitelistedLender(addr);
        }
    }
}

File 3 of 36 : SpotOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

import { ReserveOracle } from "../../oracles/reserve/ReserveOracle.sol";
import { WadRayMath, RAY } from "../../libraries/math/WadRayMath.sol";

import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";

/**
 * @notice The `SpotOracle` is supposed to reflect the current market price of a
 * collateral asset. It is used by `IonPool` to determine the health factor of a
 * vault as a user is opening or closing a position.
 *
 * NOTE: The price data provided by this contract is not used by the liquidation
 * module at all.
 *
 * The spot price will also always be bounded by the collateral's corresponding
 * reserve oracle price to ensure that a user can never open position that is
 * directly liquidatable.
 *
 * @custom:security-contact [email protected]
 */
abstract contract SpotOracle {
    using WadRayMath for uint256;

    uint256 public immutable LTV; // max LTV for a position (below liquidation threshold) [ray]
    ReserveOracle public immutable RESERVE_ORACLE;

    // --- Errors ---
    error InvalidLtv(uint256 ltv);
    error InvalidReserveOracle();

    /**
     * @notice Creates a new `SpotOracle` instance.
     * @param _ltv Loan to value ratio for the collateral.
     * @param _reserveOracle Address for the associated reserve oracle.
     */
    constructor(uint256 _ltv, address _reserveOracle) {
        if (_ltv > RAY) {
            revert InvalidLtv(_ltv);
        }
        if (address(_reserveOracle) == address(0)) {
            revert InvalidReserveOracle();
        }
        LTV = _ltv;
        RESERVE_ORACLE = ReserveOracle(_reserveOracle);
    }

    /**
     * @notice Gets the price of the collateral asset in ETH.
     * @dev Overridden by collateral specific spot oracle contracts.
     * @return price of the asset in ETH. [WAD]
     */
    function getPrice() public view virtual returns (uint256 price);

    // @dev Gets the market price multiplied by the LTV.
    // @return spot value of the asset in ETH [ray]

    /**
     * @notice Gets the risk-adjusted market price.
     * @return spot The risk-adjusted market price.
     */
    function getSpot() external view returns (uint256 spot) {
        uint256 price = getPrice(); // must be [wad]
        uint256 exchangeRate = RESERVE_ORACLE.currentExchangeRate();

        // Min the price with reserve oracle before multiplying by ltv
        uint256 min = Math.min(price, exchangeRate); // [wad]

        spot = LTV.wadMulDown(min); // [ray] * [wad] / [wad] = [ray]
    }
}

File 4 of 36 : RewardToken.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.21;

import { WadRayMath, RAY } from "../libraries/math/WadRayMath.sol";

import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { IERC20Errors } from "./IERC20Errors.sol";
import { ContextUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import { AccessControlDefaultAdminRulesUpgradeable } from
    "@openzeppelin/contracts-upgradeable/access/extensions/AccessControlDefaultAdminRulesUpgradeable.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { MessageHashUtils } from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import { ECDSA } from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";

/**
 * @title RewardToken
 * @notice The supply-side reward accounting portion of the protocol. A lender's
 * balance is measured in two parts: a static balance and a dynamic "supply
 * factor". Their true balance is the product of the two values. The dynamic
 * portion is then able to be used to distribute interest accrued to the lender.
 *
 * @custom:security-contact [email protected]
 */
abstract contract RewardToken is
    ContextUpgradeable,
    AccessControlDefaultAdminRulesUpgradeable,
    IERC20Errors,
    IERC20Metadata
{
    using WadRayMath for uint256;
    using SafeERC20 for IERC20;

    /**
     * @dev Cannot burn amount whose normalized value is less than zero.
     */
    error InvalidBurnAmount();

    /**
     * @dev Cannot mint amount whose normalized value is less than zero.
     */
    error InvalidMintAmount();

    error InvalidUnderlyingAddress();
    error InvalidTreasuryAddress();

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error InvalidReceiver(address receiver);

    /**
     * @dev Cannot transfer the token to address `self`
     */
    error SelfTransfer(address self);

    /**
     * @dev Signature cannot be submitted after `deadline` has passed. Designed to
     * mitigate replay attacks.
     */
    error ERC2612ExpiredSignature(uint256 deadline);

    /**
     * @dev `signer` does not match the `owner` of the tokens. `owner` did not approve.
     */
    error ERC2612InvalidSigner(address signer, address owner);

    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param account Address whose token balance is insufficient.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error InsufficientBalance(address account, uint256 balance, uint256 needed);

    event MintToTreasury(address indexed treasury, uint256 amount, uint256 supplyFactor);

    event TreasuryUpdate(address treasury);

    /// @custom:storage-location erc7201:ion.storage.RewardToken
    struct RewardTokenStorage {
        IERC20 underlying;
        uint8 decimals;
        // A user's true balance at any point will be the value in this mapping times the supplyFactor
        string name;
        string symbol;
        address treasury;
        uint256 normalizedTotalSupply; // [WAD]
        uint256 supplyFactor; // [RAY]
        mapping(address account => uint256) _normalizedBalances; // [WAD]
        mapping(address account => mapping(address spender => uint256)) _allowances;
        mapping(address account => uint256) nonces;
    }

    bytes32 public constant ION = keccak256("ION");

    // keccak256(abi.encode(uint256(keccak256("ion.storage.RewardModule")) - 1)) & ~bytes32(uint256(0xff))
    // solhint-disable-next-line
    bytes32 private constant RewardTokenStorageLocation =
        0xdb3a0d63a7808d7d0422c40bb62354f42bff7602a547c329c1453dbcbeef4900;

    bytes private constant EIP712_REVISION = bytes("1");
    bytes32 private constant EIP712_DOMAIN =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    bytes32 public constant PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");

    function _getRewardTokenStorage() private pure returns (RewardTokenStorage storage $) {
        assembly {
            $.slot := RewardTokenStorageLocation
        }
    }

    function _initialize(
        address _underlying,
        address _treasury,
        uint8 decimals_,
        string memory name_,
        string memory symbol_
    )
        internal
        onlyInitializing
    {
        if (_underlying == address(0)) revert InvalidUnderlyingAddress();
        if (_treasury == address(0)) revert InvalidTreasuryAddress();

        RewardTokenStorage storage $ = _getRewardTokenStorage();

        $.underlying = IERC20(_underlying);
        $.treasury = _treasury;
        $.decimals = decimals_;
        $.name = name_;
        $.symbol = symbol_;
        $.supplyFactor = RAY;

        emit TreasuryUpdate(_treasury);
    }

    /**
     *
     * @param user to burn tokens from
     * @param receiverOfUnderlying to send underlying tokens to
     * @param amount to burn
     */
    function _burn(address user, address receiverOfUnderlying, uint256 amount) internal returns (uint256) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();

        uint256 _supplyFactor = $.supplyFactor;
        uint256 amountScaled = amount.rayDivUp(_supplyFactor);

        if (amountScaled == 0) revert InvalidBurnAmount();
        _burnNormalized(user, amountScaled);

        $.underlying.safeTransfer(receiverOfUnderlying, amount);

        emit Transfer(user, address(0), amount);

        return _supplyFactor;
    }

    /**
     *
     * @param account to decrease balance of
     * @param amount of normalized tokens to burn
     */
    function _burnNormalized(address account, uint256 amount) private {
        RewardTokenStorage storage $ = _getRewardTokenStorage();

        if (account == address(0)) revert InvalidSender(address(0));

        uint256 oldAccountBalance = $._normalizedBalances[account];
        if (oldAccountBalance < amount) revert InsufficientBalance(account, oldAccountBalance, amount);
        // Underflow impossible
        unchecked {
            $._normalizedBalances[account] = oldAccountBalance - amount;
        }

        $.normalizedTotalSupply -= amount;
    }

    /**
     *
     * @param user to mint tokens to
     * @param senderOfUnderlying address to transfer underlying tokens from
     * @param amount of reward tokens to mint
     */
    function _mint(address user, address senderOfUnderlying, uint256 amount) internal returns (uint256) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();

        uint256 _supplyFactor = $.supplyFactor;
        uint256 amountScaled = amount.rayDivDown(_supplyFactor); // [WAD] * [RAY] / [RAY] = [WAD]
        if (amountScaled == 0) revert InvalidMintAmount();
        _mintNormalized(user, amountScaled);

        $.underlying.safeTransferFrom(senderOfUnderlying, address(this), amount);

        emit Transfer(address(0), user, amount);

        return _supplyFactor;
    }

    /**
     *
     * @param account to increase balance of
     * @param amount of normalized tokens to mint
     */
    function _mintNormalized(address account, uint256 amount) private {
        if (account == address(0)) revert InvalidReceiver(address(0));

        RewardTokenStorage storage $ = _getRewardTokenStorage();

        $.normalizedTotalSupply += amount;

        $._normalizedBalances[account] += amount;
    }

    /**
     * @dev This function does not perform any rounding checks.
     * @param amount of tokens to mint to treasury
     */
    function _mintToTreasury(uint256 amount) internal {
        if (amount == 0) return;

        RewardTokenStorage storage $ = _getRewardTokenStorage();

        uint256 _supplyFactor = $.supplyFactor;
        address _treasury = $.treasury;

        // Compared to the normal mint, we don't check for rounding errors. The
        // amount to mint can easily be very small since it is a fraction of the
        // interest accrued. In that case, the treasury will experience a (very
        // small) loss, but it won't cause potentially valid transactions to
        // fail.
        _mintNormalized(_treasury, amount.rayDivDown(_supplyFactor));

        emit Transfer(address(0), _treasury, amount);
        emit MintToTreasury(_treasury, amount, _supplyFactor);
    }

    /**
     *
     * @param spender to approve
     * @param amount to approve
     */
    function approve(address spender, uint256 amount) external returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    /**
     *
     * @param owner of tokens
     * @param spender of tokens
     * @param amount to approve
     */
    function _approve(address owner, address spender, uint256 amount) internal {
        if (owner == address(0)) revert ERC20InvalidApprover(address(0));
        if (spender == address(0)) revert ERC20InvalidSpender(address(0));

        RewardTokenStorage storage $ = _getRewardTokenStorage();

        $._allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Spends allowance
     */
    function _spendAllowance(address owner, address spender, uint256 amount) private {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < amount) {
            revert ERC20InsufficientAllowance(spender, currentAllowance, amount);
        }
        uint256 newAllowance;
        // Underflow impossible
        unchecked {
            newAllowance = currentAllowance - amount;
        }

        RewardTokenStorage storage $ = _getRewardTokenStorage();

        $._allowances[owner][spender] = newAllowance;
    }

    /**
     * @dev Can only be called by owner of the tokens
     * @param to transfer to
     * @param amount to transfer
     */
    function transfer(address to, uint256 amount) public returns (bool) {
        _transfer(_msgSender(), to, amount);
        emit Transfer(_msgSender(), to, amount);
        return true;
    }

    /**
     * @dev For use with `approve()`
     * @param from to transfer from
     * @param to to transfer to
     * @param amount to transfer
     */
    function transferFrom(address from, address to, uint256 amount) public returns (bool) {
        _spendAllowance(from, _msgSender(), amount);
        _transfer(from, to, amount);

        emit Transfer(from, to, amount);
        return true;
    }

    function _transfer(address from, address to, uint256 amount) private {
        if (from == address(0)) revert ERC20InvalidSender(address(0));
        if (to == address(0)) revert ERC20InvalidReceiver(address(0));
        if (from == to) revert SelfTransfer(from);

        RewardTokenStorage storage $ = _getRewardTokenStorage();

        uint256 _supplyFactor = $.supplyFactor;
        uint256 amountNormalized = amount.rayDivDown(_supplyFactor);

        uint256 oldSenderBalance = $._normalizedBalances[from];
        if (oldSenderBalance < amountNormalized) {
            revert ERC20InsufficientBalance(from, oldSenderBalance, amountNormalized);
        }
        // Underflow impossible
        unchecked {
            $._normalizedBalances[from] = oldSenderBalance - amountNormalized;
        }
        $._normalizedBalances[to] += amountNormalized;
    }

    /**
     * @dev implements the permit function as for
     * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md
     * @param owner The owner of the funds
     * @param spender The spender
     * @param value The amount
     * @param deadline The deadline timestamp, type(uint256).max for max deadline
     * @param v Signature param
     * @param s Signature param
     * @param r Signature param
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    )
        public
        virtual
    {
        if (block.timestamp > deadline) {
            revert ERC2612ExpiredSignature(deadline);
        }

        bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));

        bytes32 domainSeparator = keccak256(
            abi.encode(
                EIP712_DOMAIN, keccak256(bytes(name())), keccak256(EIP712_REVISION), block.chainid, address(this)
            )
        );

        bytes32 hash = MessageHashUtils.toTypedDataHash(domainSeparator, structHash);

        address signer = ECDSA.recover(hash, v, r, s);
        if (signer != owner) {
            revert ERC2612InvalidSigner(signer, owner);
        }

        _approve(owner, spender, value);
    }

    /**
     * @dev Returns current allowance
     * @param owner of tokens
     * @param spender of tokens
     */
    function allowance(address owner, address spender) public view returns (uint256) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();
        return $._allowances[owner][spender];
    }

    function nonces(address owner) public view returns (uint256) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();
        return $.nonces[owner];
    }

    /**
     * @dev Consumes a nonce.
     *
     * Returns the current value and increments nonce.
     */
    function _useNonce(address owner) internal virtual returns (uint256) {
        // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
        // decremented or reset. This guarantees that the nonce never overflows.
        RewardTokenStorage storage $ = _getRewardTokenStorage();

        unchecked {
            // It is important to do x++ and not ++x here.
            return $.nonces[owner]++;
        }
    }

    function _setSupplyFactor(uint256 newSupplyFactor) internal {
        RewardTokenStorage storage $ = _getRewardTokenStorage();
        $.supplyFactor = newSupplyFactor;
    }

    /**
     * @dev Updates the treasury address
     * @param newTreasury address of new treasury
     */
    function updateTreasury(address newTreasury) external onlyRole(ION) {
        if (newTreasury == address(0)) revert InvalidTreasuryAddress();

        RewardTokenStorage storage $ = _getRewardTokenStorage();
        $.treasury = newTreasury;

        emit TreasuryUpdate(newTreasury);
    }

    // --- Getters ---

    /**
     * @dev Address of underlying asset
     */
    function underlying() public view returns (IERC20) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();
        return $.underlying;
    }

    /**
     * @dev Decimals of the position asset
     */
    function decimals() public view returns (uint8) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();
        return $.decimals;
    }

    /**
     * @dev Current claim of the underlying token inclusive of interest to be accrued.
     * @param user to get balance of
     */
    function balanceOf(address user) public view returns (uint256) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();

        (uint256 totalSupplyFactorIncrease,,,,) = calculateRewardAndDebtDistribution();

        return $._normalizedBalances[user].rayMulDown($.supplyFactor + totalSupplyFactorIncrease);
    }

    /**
     * @dev Current claim of the underlying token without accounting for interest to be accrued.
     */
    function balanceOfUnaccrued(address user) public view returns (uint256) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();
        return $._normalizedBalances[user].rayMulDown($.supplyFactor);
    }

    /**
     * @dev Accounting is done in normalized balances
     * @param user to get normalized balance of
     */
    function normalizedBalanceOf(address user) external view returns (uint256) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();
        return $._normalizedBalances[user];
    }

    /**
     * @dev Name of the position asset
     */
    function name() public view returns (string memory) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();
        return $.name;
    }

    /**
     * @dev Symbol of the position asset
     */
    function symbol() public view returns (string memory) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();
        return $.symbol;
    }

    /**
     * @dev Current treasury address
     */
    function treasury() public view returns (address) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();
        return $.treasury;
    }

    /**
     * @dev Total claim of the underlying asset belonging to lenders not inclusive of the new interest to be accrued.
     */
    function totalSupplyUnaccrued() public view returns (uint256) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();

        uint256 _normalizedTotalSupply = $.normalizedTotalSupply;

        if (_normalizedTotalSupply == 0) {
            return 0;
        }

        return _normalizedTotalSupply.rayMulDown($.supplyFactor);
    }

    /**
     * @dev Total claim of the underlying asset belonging to lender inclusive of the new interest to be accrued.
     */
    function totalSupply() public view returns (uint256) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();

        uint256 _normalizedTotalSupply = $.normalizedTotalSupply;

        if (_normalizedTotalSupply == 0) {
            return 0;
        }

        (uint256 totalSupplyFactorIncrease, uint256 totalTreasuryMintAmount,,,) = calculateRewardAndDebtDistribution();

        return _normalizedTotalSupply.rayMulDown($.supplyFactor + totalSupplyFactorIncrease) + totalTreasuryMintAmount;
    }

    function normalizedTotalSupplyUnaccrued() public view returns (uint256) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();
        return $.normalizedTotalSupply;
    }

    /**
     * @dev Normalized total supply.
     */
    function normalizedTotalSupply() public view returns (uint256) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();

        (uint256 totalSupplyFactorIncrease, uint256 totalTreasuryMintAmount,,,) = calculateRewardAndDebtDistribution();

        uint256 normalizedTreasuryMintAmount =
            totalTreasuryMintAmount.rayDivDown($.supplyFactor + totalSupplyFactorIncrease);

        return $.normalizedTotalSupply + normalizedTreasuryMintAmount;
    }

    function supplyFactorUnaccrued() public view returns (uint256) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();
        return $.supplyFactor;
    }

    /**
     * @dev Current supply factor
     */
    function supplyFactor() public view returns (uint256) {
        RewardTokenStorage storage $ = _getRewardTokenStorage();

        (uint256 totalSupplyFactorIncrease,,,,) = calculateRewardAndDebtDistribution();

        return $.supplyFactor + totalSupplyFactorIncrease;
    }

    function calculateRewardAndDebtDistribution()
        public
        view
        virtual
        returns (
            uint256 totalSupplyFactorIncrease,
            uint256 totalTreasuryMintAmount,
            uint104[] memory rateIncreases,
            uint256 totalDebtIncrease,
            uint48[] memory timestampIncreases
        );
}

File 5 of 36 : InterestRate.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

import { IYieldOracle } from "./interfaces/IYieldOracle.sol";
import { WadRayMath } from "./libraries/math/WadRayMath.sol";

// forgefmt: disable-start

struct IlkData {
    // Word 1
    uint96 adjustedProfitMargin; // 27 decimals
    uint96 minimumKinkRate; // 27 decimals

    // Word 2
    uint16 reserveFactor; // 4 decimals
    uint96 adjustedBaseRate; // 27 decimals
    uint96 minimumBaseRate; // 27 decimals
    uint16 optimalUtilizationRate; // 4 decimals
    uint16 distributionFactor; // 4 decimals

    // Word 3
    uint96 adjustedAboveKinkSlope; // 27 decimals
    uint96 minimumAboveKinkSlope; // 27 decimals
}

// Word 1
//
//                                                256  240   216   192                     96                      0
//                                                 |    |     |     |     min_kink_rate     |   adj_profit_margin  |
//
uint256 constant ADJUSTED_PROFIT_MARGIN_MASK =    0x0000000000000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF; 
uint256 constant MINIMUM_KINK_RATE_MASK =         0x0000000000000000FFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000;

// Word 2
//
//                                                256  240 224 208                     112                     16   0
//                                                 | __ |   |   |     min_base_rate     |     adj_base_rate     |   |
//                                                        ^   ^                                                   ^
//                                                        ^  opt_util                                 reserve_factor
//                                       distribution_factor

uint256 constant RESERVE_FACTOR_MASK =            0x000000000000000000000000000000000000000000000000000000000000FFFF;
uint256 constant ADJUSTED_BASE_RATE_MASK =        0x000000000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF0000;
uint256 constant MINIMUM_BASE_RATE_MASK =         0x000000000000FFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000;
uint256 constant OPTIMAL_UTILIZATION_MASK =       0x00000000FFFF0000000000000000000000000000000000000000000000000000;
uint256 constant DISTRIBUTION_FACTOR_MASK =       0x0000FFFF00000000000000000000000000000000000000000000000000000000;

// Word 3
//                                                256  240   216   192                     96                      0
//                                                 |    |     |     |  min_above_kink_slope | adj_above_kink_slope |
//
uint256 constant ADJUSTED_ABOVE_KINK_SLOPE_MASK =  0x0000000000000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF;
uint256 constant MINIMUM_ABOVE_KINK_SLOPE_MASK =   0x0000000000000000FFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000; 

// forgefmt: disable-end

// Word 1
uint8 constant ADJUSTED_PROFIT_MARGIN_SHIFT = 0;
uint8 constant MINIMUM_KINK_RATE_SHIFT = 96;

// Word 2
uint8 constant RESERVE_FACTOR_SHIFT = 0;
uint8 constant ADJUSTED_BASE_RATE_SHIFT = 16;
uint8 constant MINIMUM_BASE_RATE_SHIFT = 16 + 96;
uint8 constant OPTIMAL_UTILIZATION_SHIFT = 16 + 96 + 96;
uint8 constant DISTRIBUTION_FACTOR_SHIFT = 16 + 96 + 96 + 16;

// Word 3
uint8 constant ADJUSTED_ABOVE_KINK_SLOPE_SHIFT = 0;
uint8 constant MINIMUM_ABOVE_KINK_SLOPE_SHIFT = 96;

uint48 constant SECONDS_IN_A_YEAR = 31_536_000;

/**
 * @notice An external contract that provides the APY for each collateral type.
 * A modular design here allows for updating of the parameters at a later date
 * without upgrading the core protocol.
 *
 * @dev Each collateral has its own interest rate model, and every operation on
 * the `IonPool` (lend, withdraw, borrow, repay) will alter the interest rate
 * for all collaterals. Therefore, before every operation, the previous interest
 * rate must be accrued. Ion determines the interest rate for each collateral
 * based on various collateral-specific parameters which must be stored
 * on-chain. However, to iterate through all these parameters as contract
 * storage on every operation introduces an immense gas overhead, especially as
 * more collaterals are listed on Ion. Therefore, this contract is heavily
 * optimized to reduce storage reads at the unfortunate cost of code-complexity.
 *
 * @custom:security-contact [email protected]
 */
contract InterestRate {
    using WadRayMath for *;

    error CollateralIndexOutOfBounds();
    error DistributionFactorsDoNotSumToOne(uint256 sum);
    error TotalDebtsLength(uint256 COLLATERAL_COUNT, uint256 totalIlkDebtsLength);

    error InvalidMinimumKinkRate(uint256 minimumKinkRate, uint256 minimumBaseRate);
    error InvalidIlkDataListLength(uint256 length);
    error InvalidOptimalUtilizationRate(uint256 optimalUtilizationRate);
    error InvalidReserveFactor(uint256 reserveFactor);
    error InvalidYieldOracleAddress();

    uint256 private constant MAX_ILKS = 8;

    /**
     * @dev Packed collateral configs
     */
    uint256 private immutable ILKCONFIG_0A;
    uint256 private immutable ILKCONFIG_0B;
    uint256 private immutable ILKCONFIG_0C;
    uint256 private immutable ILKCONFIG_1A;
    uint256 private immutable ILKCONFIG_1B;
    uint256 private immutable ILKCONFIG_1C;
    uint256 private immutable ILKCONFIG_2A;
    uint256 private immutable ILKCONFIG_2B;
    uint256 private immutable ILKCONFIG_2C;
    uint256 private immutable ILKCONFIG_3A;
    uint256 private immutable ILKCONFIG_3B;
    uint256 private immutable ILKCONFIG_3C;
    uint256 private immutable ILKCONFIG_4A;
    uint256 private immutable ILKCONFIG_4B;
    uint256 private immutable ILKCONFIG_4C;
    uint256 private immutable ILKCONFIG_5A;
    uint256 private immutable ILKCONFIG_5B;
    uint256 private immutable ILKCONFIG_5C;
    uint256 private immutable ILKCONFIG_6A;
    uint256 private immutable ILKCONFIG_6B;
    uint256 private immutable ILKCONFIG_6C;
    uint256 private immutable ILKCONFIG_7A;
    uint256 private immutable ILKCONFIG_7B;
    uint256 private immutable ILKCONFIG_7C;

    uint256 public immutable COLLATERAL_COUNT;
    IYieldOracle public immutable YIELD_ORACLE;

    /**
     * @notice Creates a new `InterestRate` instance.
     * @param ilkDataList List of ilk configs.
     * @param _yieldOracle Address of the Yield oracle.
     */
    constructor(IlkData[] memory ilkDataList, IYieldOracle _yieldOracle) {
        if (address(_yieldOracle) == address(0)) revert InvalidYieldOracleAddress();
        if (ilkDataList.length > MAX_ILKS) revert InvalidIlkDataListLength(ilkDataList.length);

        COLLATERAL_COUNT = ilkDataList.length;
        YIELD_ORACLE = _yieldOracle;

        uint256 distributionFactorSum = 0;
        for (uint256 i = 0; i < COLLATERAL_COUNT;) {
            distributionFactorSum += ilkDataList[i].distributionFactor;

            if (ilkDataList[i].minimumKinkRate < ilkDataList[i].minimumBaseRate) {
                revert InvalidMinimumKinkRate(ilkDataList[i].minimumKinkRate, ilkDataList[i].minimumBaseRate);
            }
            if (ilkDataList[i].optimalUtilizationRate == 0) {
                revert InvalidOptimalUtilizationRate(ilkDataList[i].optimalUtilizationRate);
            }
            if (ilkDataList[i].reserveFactor > 1e4) {
                revert InvalidReserveFactor(ilkDataList[i].reserveFactor);
            }

            // forgefmt: disable-next-line
            unchecked { ++i; }
        }

        if (distributionFactorSum != 1e4) revert DistributionFactorsDoNotSumToOne(distributionFactorSum);

        (ILKCONFIG_0A, ILKCONFIG_0B, ILKCONFIG_0C) = _packCollateralConfig(ilkDataList, 0);
        (ILKCONFIG_1A, ILKCONFIG_1B, ILKCONFIG_1C) = _packCollateralConfig(ilkDataList, 1);
        (ILKCONFIG_2A, ILKCONFIG_2B, ILKCONFIG_2C) = _packCollateralConfig(ilkDataList, 2);
        (ILKCONFIG_3A, ILKCONFIG_3B, ILKCONFIG_3C) = _packCollateralConfig(ilkDataList, 3);
        (ILKCONFIG_4A, ILKCONFIG_4B, ILKCONFIG_4C) = _packCollateralConfig(ilkDataList, 4);
        (ILKCONFIG_5A, ILKCONFIG_5B, ILKCONFIG_5C) = _packCollateralConfig(ilkDataList, 5);
        (ILKCONFIG_6A, ILKCONFIG_6B, ILKCONFIG_6C) = _packCollateralConfig(ilkDataList, 6);
        (ILKCONFIG_7A, ILKCONFIG_7B, ILKCONFIG_7C) = _packCollateralConfig(ilkDataList, 7);
    }

    /**
     * @notice Helper function to pack the collateral configs into 3 words. This
     * function is only called during construction.
     * @param ilkDataList The list of ilk configs.
     * @param index The ilkIndex to pack.
     * @return packedConfig_a
     * @return packedConfig_b
     * @return packedConfig_c
     */
    function _packCollateralConfig(
        IlkData[] memory ilkDataList,
        uint256 index
    )
        private
        view
        returns (uint256 packedConfig_a, uint256 packedConfig_b, uint256 packedConfig_c)
    {
        if (index >= COLLATERAL_COUNT) return (0, 0, 0);

        IlkData memory ilkData = ilkDataList[index];

        packedConfig_a = (
            uint256(ilkData.adjustedProfitMargin) << ADJUSTED_PROFIT_MARGIN_SHIFT
                | uint256(ilkData.minimumKinkRate) << MINIMUM_KINK_RATE_SHIFT
        );

        packedConfig_b = (
            uint256(ilkData.reserveFactor) << RESERVE_FACTOR_SHIFT
                | uint256(ilkData.adjustedBaseRate) << ADJUSTED_BASE_RATE_SHIFT
                | uint256(ilkData.minimumBaseRate) << MINIMUM_BASE_RATE_SHIFT
                | uint256(ilkData.optimalUtilizationRate) << OPTIMAL_UTILIZATION_SHIFT
                | uint256(ilkData.distributionFactor) << DISTRIBUTION_FACTOR_SHIFT
        );

        packedConfig_c = (
            uint256(ilkData.adjustedAboveKinkSlope) << ADJUSTED_ABOVE_KINK_SLOPE_SHIFT
                | uint256(ilkData.minimumAboveKinkSlope) << MINIMUM_ABOVE_KINK_SLOPE_SHIFT
        );
    }

    /**
     * @notice Helper function to unpack the collateral configs from the 3
     * words.
     * @param index The ilkIndex to unpack.
     * @return ilkData The unpacked collateral config.
     */
    function unpackCollateralConfig(uint256 index) external view returns (IlkData memory ilkData) {
        return _unpackCollateralConfig(index);
    }

    function _unpackCollateralConfig(uint256 index) internal view returns (IlkData memory ilkData) {
        if (index > COLLATERAL_COUNT - 1) revert CollateralIndexOutOfBounds();

        uint256 packedConfig_a;
        uint256 packedConfig_b;
        uint256 packedConfig_c;

        if (index == 0) {
            packedConfig_a = ILKCONFIG_0A;
            packedConfig_b = ILKCONFIG_0B;
            packedConfig_c = ILKCONFIG_0C;
        } else if (index == 1) {
            packedConfig_a = ILKCONFIG_1A;
            packedConfig_b = ILKCONFIG_1B;
            packedConfig_c = ILKCONFIG_1C;
        } else if (index == 2) {
            packedConfig_a = ILKCONFIG_2A;
            packedConfig_b = ILKCONFIG_2B;
            packedConfig_c = ILKCONFIG_2C;
        } else if (index == 3) {
            packedConfig_a = ILKCONFIG_3A;
            packedConfig_b = ILKCONFIG_3B;
            packedConfig_c = ILKCONFIG_3C;
        } else if (index == 4) {
            packedConfig_a = ILKCONFIG_4A;
            packedConfig_b = ILKCONFIG_4B;
            packedConfig_c = ILKCONFIG_4C;
        } else if (index == 5) {
            packedConfig_a = ILKCONFIG_5A;
            packedConfig_b = ILKCONFIG_5B;
            packedConfig_c = ILKCONFIG_5C;
        } else if (index == 6) {
            packedConfig_a = ILKCONFIG_6A;
            packedConfig_b = ILKCONFIG_6B;
            packedConfig_c = ILKCONFIG_6C;
        } else if (index == 7) {
            packedConfig_a = ILKCONFIG_7A;
            packedConfig_b = ILKCONFIG_7B;
            packedConfig_c = ILKCONFIG_7C;
        }

        uint96 adjustedProfitMargin =
            uint96((packedConfig_a & ADJUSTED_PROFIT_MARGIN_MASK) >> ADJUSTED_PROFIT_MARGIN_SHIFT);
        uint96 minimumKinkRate = uint96((packedConfig_a & MINIMUM_KINK_RATE_MASK) >> MINIMUM_KINK_RATE_SHIFT);

        uint16 reserveFactor = uint16((packedConfig_b & RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_SHIFT);
        uint96 adjustedBaseRate = uint96((packedConfig_b & ADJUSTED_BASE_RATE_MASK) >> ADJUSTED_BASE_RATE_SHIFT);
        uint96 minimumBaseRate = uint96((packedConfig_b & MINIMUM_BASE_RATE_MASK) >> MINIMUM_BASE_RATE_SHIFT);
        uint16 optimalUtilizationRate = uint16((packedConfig_b & OPTIMAL_UTILIZATION_MASK) >> OPTIMAL_UTILIZATION_SHIFT);
        uint16 distributionFactor = uint16((packedConfig_b & DISTRIBUTION_FACTOR_MASK) >> DISTRIBUTION_FACTOR_SHIFT);

        uint96 adjustedAboveKinkSlope =
            uint96((packedConfig_c & ADJUSTED_ABOVE_KINK_SLOPE_MASK) >> ADJUSTED_ABOVE_KINK_SLOPE_SHIFT);
        uint96 minimumAboveKinkSlope =
            uint96((packedConfig_c & MINIMUM_ABOVE_KINK_SLOPE_MASK) >> MINIMUM_ABOVE_KINK_SLOPE_SHIFT);

        ilkData = IlkData({
            adjustedProfitMargin: adjustedProfitMargin,
            minimumKinkRate: minimumKinkRate,
            reserveFactor: reserveFactor,
            adjustedBaseRate: adjustedBaseRate,
            minimumBaseRate: minimumBaseRate,
            optimalUtilizationRate: optimalUtilizationRate,
            distributionFactor: distributionFactor,
            adjustedAboveKinkSlope: adjustedAboveKinkSlope,
            minimumAboveKinkSlope: minimumAboveKinkSlope
        });
    }

    /**
     * @notice Calculates the interest rate for a given collateral.
     * @param ilkIndex Index of the collateral.
     * @param totalIlkDebt Total debt of the collateral. [RAD]
     * @param totalEthSupply Total eth supply of the system. [WAD]
     * @return The borrow rate for the collateral. [RAY]
     * @return The reserve factor for the collateral. [RAY]
     */
    function calculateInterestRate(
        uint256 ilkIndex,
        uint256 totalIlkDebt,
        uint256 totalEthSupply
    )
        external
        view
        returns (uint256, uint256)
    {
        IlkData memory ilkData = _unpackCollateralConfig(ilkIndex);
        uint256 optimalUtilizationRateRay = ilkData.optimalUtilizationRate.scaleUpToRay(4);
        uint256 collateralApyRayInSeconds = YIELD_ORACLE.apys(ilkIndex).scaleUpToRay(8) / SECONDS_IN_A_YEAR;

        uint256 distributionFactor = ilkData.distributionFactor;
        // The only time the distribution factor will be set to 0 is when a
        // market has been sunset. In this case, we want to prevent division by
        // 0, but we also want to prevent the borrow rate from skyrocketing. So
        // we will return a reasonable borrow rate of kink utilization on the
        // minimum curve.
        if (distributionFactor == 0) {
            return (ilkData.minimumKinkRate, ilkData.reserveFactor.scaleUpToRay(4));
        }

        // If the `totalEthSupply` is small enough to truncate to zero, then
        // treat the utilization as zero.
        uint256 totalEthSupplyScaled = totalEthSupply.wadMulDown(distributionFactor.scaleUpToWad(4));

        // [RAD] / [WAD] = [RAY]
        uint256 utilizationRate = totalEthSupplyScaled == 0 ? 0 : totalIlkDebt / totalEthSupplyScaled;

        // Avoid stack too deep
        uint256 adjustedBelowKinkSlope;
        {
            uint256 slopeNumerator;
            unchecked {
                slopeNumerator = collateralApyRayInSeconds - ilkData.adjustedProfitMargin - ilkData.adjustedBaseRate;
            }

            // Underflow occurred
            // If underflow occurred, then the Apy was too low or the profitMargin was too high and
            // we would want to switch to minimum borrow rate. Set slopeNumerator to zero such
            // that adjusted borrow rate is below the minimum borrow rate.
            if (slopeNumerator > collateralApyRayInSeconds) {
                slopeNumerator = 0;
            }

            adjustedBelowKinkSlope = slopeNumerator.rayDivDown(optimalUtilizationRateRay);
        }

        uint256 minimumBelowKinkSlope =
            (ilkData.minimumKinkRate - ilkData.minimumBaseRate).rayDivDown(optimalUtilizationRateRay);

        // Below kink
        if (utilizationRate < optimalUtilizationRateRay) {
            uint256 adjustedBorrowRate = adjustedBelowKinkSlope.rayMulDown(utilizationRate) + ilkData.adjustedBaseRate;
            uint256 minimumBorrowRate = minimumBelowKinkSlope.rayMulDown(utilizationRate) + ilkData.minimumBaseRate;

            if (adjustedBorrowRate < minimumBorrowRate) {
                return (minimumBorrowRate, ilkData.reserveFactor.scaleUpToRay(4));
            } else {
                return (adjustedBorrowRate, ilkData.reserveFactor.scaleUpToRay(4));
            }
        }
        // Above kink
        else {
            // For the above kink calculation, we will use the below kink slope
            // for all utilization up until the kink. From that point on we will
            // use the above kink slope.
            uint256 excessUtil = utilizationRate - optimalUtilizationRateRay;

            uint256 adjustedNormalRate =
                adjustedBelowKinkSlope.rayMulDown(optimalUtilizationRateRay) + ilkData.adjustedBaseRate;
            uint256 minimumNormalRate =
                minimumBelowKinkSlope.rayMulDown(optimalUtilizationRateRay) + ilkData.minimumBaseRate;

            // [WAD] * [RAY] / [WAD] = [RAY]
            uint256 adjustedBorrowRate = ilkData.adjustedAboveKinkSlope.rayMulDown(excessUtil) + adjustedNormalRate;
            uint256 minimumBorrowRate = ilkData.minimumAboveKinkSlope.rayMulDown(excessUtil) + minimumNormalRate;

            if (adjustedBorrowRate < minimumBorrowRate) {
                return (minimumBorrowRate, ilkData.reserveFactor.scaleUpToRay(4));
            } else {
                return (adjustedBorrowRate, ilkData.reserveFactor.scaleUpToRay(4));
            }
        }
    }
}

File 6 of 36 : WadRayMath.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";

uint256 constant WAD = 1e18;
uint256 constant RAY = 1e27;
uint256 constant RAD = 1e45;

/**
 * @title WadRayMath
 *
 * @notice This library provides mul/div[up/down] functionality for WAD, RAY and
 * RAD with phantom overflow protection as well as scale[up/down] functionality
 * for WAD, RAY and RAD.
 *
 * @custom:security-contact [email protected]
 */
library WadRayMath {
    using Math for uint256;

    error NotScalingUp(uint256 from, uint256 to);
    error NotScalingDown(uint256 from, uint256 to);

    /**
     * @notice Multiplies two WAD numbers and returns the result as a WAD
     * rounding the result down.
     * @param a Multiplicand.
     * @param b Multiplier.
     */
    function wadMulDown(uint256 a, uint256 b) internal pure returns (uint256) {
        return a.mulDiv(b, WAD);
    }

    /**
     * @notice Multiplies two WAD numbers and returns the result as a WAD
     * rounding the result up.
     * @param a Multiplicand.
     * @param b Multiplier.
     */
    function wadMulUp(uint256 a, uint256 b) internal pure returns (uint256) {
        return a.mulDiv(b, WAD, Math.Rounding.Ceil);
    }

    /**
     * @notice Divides two WAD numbers and returns the result as a WAD rounding
     * the result down.
     * @param a Dividend.
     * @param b Divisor.
     */
    function wadDivDown(uint256 a, uint256 b) internal pure returns (uint256) {
        return a.mulDiv(WAD, b);
    }

    /**
     * @notice Divides two WAD numbers and returns the result as a WAD rounding
     * the result up.
     * @param a Dividend.
     * @param b Divisor.
     */
    function wadDivUp(uint256 a, uint256 b) internal pure returns (uint256) {
        return a.mulDiv(WAD, b, Math.Rounding.Ceil);
    }

    /**
     * @notice Multiplies two RAY numbers and returns the result as a RAY
     * rounding the result down.
     * @param a Multiplicand
     * @param b Multiplier
     */
    function rayMulDown(uint256 a, uint256 b) internal pure returns (uint256) {
        return a.mulDiv(b, RAY);
    }

    /**
     * @notice Multiplies two RAY numbers and returns the result as a RAY
     * rounding the result up.
     * @param a Multiplicand
     * @param b Multiplier
     */
    function rayMulUp(uint256 a, uint256 b) internal pure returns (uint256) {
        return a.mulDiv(b, RAY, Math.Rounding.Ceil);
    }

    /**
     * @notice Divides two RAY numbers and returns the result as a RAY
     * rounding the result down.
     * @param a Dividend
     * @param b Divisor
     */
    function rayDivDown(uint256 a, uint256 b) internal pure returns (uint256) {
        return a.mulDiv(RAY, b);
    }

    /**
     * @notice Divides two RAY numbers and returns the result as a RAY
     * rounding the result up.
     * @param a Dividend
     * @param b Divisor
     */
    function rayDivUp(uint256 a, uint256 b) internal pure returns (uint256) {
        return a.mulDiv(RAY, b, Math.Rounding.Ceil);
    }

    /**
     * @notice Multiplies two RAD numbers and returns the result as a RAD
     * rounding the result down.
     * @param a Multiplicand
     * @param b Multiplier
     */
    function radMulDown(uint256 a, uint256 b) internal pure returns (uint256) {
        return a.mulDiv(b, RAD);
    }

    /**
     * @notice Multiplies two RAD numbers and returns the result as a RAD
     * rounding the result up.
     * @param a Multiplicand
     * @param b Multiplier
     */
    function radMulUp(uint256 a, uint256 b) internal pure returns (uint256) {
        return a.mulDiv(b, RAD, Math.Rounding.Ceil);
    }

    /**
     * @notice Divides two RAD numbers and returns the result as a RAD rounding
     * the result down.
     * @param a Dividend
     * @param b Divisor
     */
    function radDivDown(uint256 a, uint256 b) internal pure returns (uint256) {
        return a.mulDiv(RAD, b);
    }

    /**
     * @notice Divides two RAD numbers and returns the result as a RAD rounding
     * the result up.
     * @param a Dividend
     * @param b Divisor
     */
    function radDivUp(uint256 a, uint256 b) internal pure returns (uint256) {
        return a.mulDiv(RAD, b, Math.Rounding.Ceil);
    }

    // --- Scalers ---

    /**
     * @notice Scales a value up from WAD. NOTE: The `scale` value must be
     * less than 18.
     * @param value to scale up.
     * @param scale of the returned value.
     */
    function scaleUpToWad(uint256 value, uint256 scale) internal pure returns (uint256) {
        return scaleUp(value, scale, 18);
    }

    /**
     * @notice Scales a value up from RAY. NOTE: The `scale` value must be
     * less than 27.
     * @param value to scale up.
     * @param scale of the returned value.
     */
    function scaleUpToRay(uint256 value, uint256 scale) internal pure returns (uint256) {
        return scaleUp(value, scale, 27);
    }

    /**
     * @notice Scales a value up from RAD. NOTE: The `scale` value must be
     * less than 45.
     * @param value to scale up.
     * @param scale of the returned value.
     */
    function scaleUpToRad(uint256 value, uint256 scale) internal pure returns (uint256) {
        return scaleUp(value, scale, 45);
    }

    /**
     * @notice Scales a value down to WAD. NOTE: The `scale` value must be
     * greater than 18.
     * @param value to scale down.
     * @param scale of the returned value.
     */
    function scaleDownToWad(uint256 value, uint256 scale) internal pure returns (uint256) {
        return scaleDown(value, scale, 18);
    }

    /**
     * @notice Scales a value down to RAY. NOTE: The `scale` value must be
     * greater than 27.
     * @param value to scale down.
     * @param scale of the returned value.
     */
    function scaleDownToRay(uint256 value, uint256 scale) internal pure returns (uint256) {
        return scaleDown(value, scale, 27);
    }

    /**
     * @notice Scales a value down to RAD. NOTE: The `scale` value must be
     * greater than 45.
     * @param value to scale down.
     * @param scale of the returned value.
     */
    function scaleDownToRad(uint256 value, uint256 scale) internal pure returns (uint256) {
        return scaleDown(value, scale, 45);
    }

    /**
     * @notice Scales a value up from one fixed-point precision to another.
     * @param value to scale up.
     * @param from Precision to scale from.
     * @param to Precision to scale to.
     */
    function scaleUp(uint256 value, uint256 from, uint256 to) internal pure returns (uint256) {
        if (from >= to) revert NotScalingUp(from, to);
        return value * (10 ** (to - from));
    }

    /**
     * @notice Scales a value down from one fixed-point precision to another.
     * @param value to scale down.
     * @param from Precision to scale from.
     * @param to Precision to scale to.
     */
    function scaleDown(uint256 value, uint256 from, uint256 to) internal pure returns (uint256) {
        if (from <= to) revert NotScalingDown(from, to);
        return value / (10 ** (from - to));
    }
}

File 7 of 36 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

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

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

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

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

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

File 8 of 36 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

File 9 of 36 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }
}

File 10 of 36 : EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

File 11 of 36 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

File 12 of 36 : PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Pausable
    struct PausableStorage {
        bool _paused;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;

    function _getPausableStorage() private pure returns (PausableStorage storage $) {
        assembly {
            $.slot := PausableStorageLocation
        }
    }

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

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

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        PausableStorage storage $ = _getPausableStorage();
        return $._paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = false;
        emit Unpaused(_msgSender());
    }
}

File 13 of 36 : Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

File 14 of 36 : Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

File 15 of 36 : MerkleProof.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MerkleProof.sol)

pragma solidity ^0.8.20;

/**
 * @dev These functions deal with verification of Merkle Tree proofs.
 *
 * The tree and the proofs can be generated using our
 * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
 * You will find a quickstart guide in the readme.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the Merkle tree could be reinterpreted as a leaf value.
 * OpenZeppelin's JavaScript library generates Merkle trees that are safe
 * against this attack out of the box.
 */
library MerkleProof {
    /**
     *@dev The multiproof provided is not valid.
     */
    error MerkleProofInvalidMultiproof();

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     */
    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Calldata version of {verify}
     */
    function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProofCalldata(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leafs & pre-images are assumed to be sorted.
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Calldata version of {processProof}
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Calldata version of {multiProofVerify}
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofLen = proof.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proofLen != totalHashes + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](totalHashes);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

        if (totalHashes > 0) {
            if (proofPos != proofLen) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[totalHashes - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Calldata version of {processMultiProof}.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofLen = proof.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proofLen != totalHashes + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](totalHashes);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

        if (totalHashes > 0) {
            if (proofPos != proofLen) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[totalHashes - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Sorts the pair (a, b) and hashes the result.
     */
    function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
        return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
    }

    /**
     * @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
     */
    function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

File 16 of 36 : ReserveOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

import { IReserveFeed } from "../../interfaces/IReserveFeed.sol";
import { WadRayMath, RAY } from "../../libraries/math/WadRayMath.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";

// should equal to the number of feeds available in the contract
uint8 constant FEED_COUNT = 3;
uint256 constant UPDATE_COOLDOWN = 58 minutes;

/**
 * @notice Reserve oracles are used to determine the LST provider exchange rate
 * and is utilizated by Ion's liquidation module. Liquidations will only be
 * triggered against this exchange rate and will be completely market-price
 * agnostic. Importantly, this means that liquidations will only be triggered
 * through lack of debt repayment or slashing events.
 *
 * @dev In order to protect against potential provider bugs or incorrect one-off
 * values (malicious or accidental), the reserve oracle does not use live data.
 * Instead it will query the exchange every intermittent period and persist the
 * value and this value can only move up or down by a maximum percentage per query.
 *
 * If additional data sources are available, they can be involved as `FEED`s. If
 * other `FEED`s are provided to the reserve oracle, a mean of all the `FEED`s
 * is compared to the protocol exchange rate and the minimum of the two is used
 * as the new exchange rate. This final value is subject to the bounding rules.
 *
 * @custom:security-contact [email protected]
 */
abstract contract ReserveOracle {
    using WadRayMath for uint256;

    uint8 public immutable ILK_INDEX;
    uint8 public immutable QUORUM; // the number of feeds to aggregate
    uint256 public immutable MAX_CHANGE; // maximum change allowed in percentage [ray] i.e. 3e25 [ray] would be 3%

    IReserveFeed public immutable FEED0; // different reserve oracle feeds excluding the protocol exchange rate
    IReserveFeed public immutable FEED1;
    IReserveFeed public immutable FEED2;

    uint256 public currentExchangeRate; // [wad] the bounded queried last time
    uint256 public lastUpdated; // [wad] the bounded queried last time

    // --- Events ---
    event UpdateExchangeRate(uint256 exchangeRate);

    // --- Errors ---
    error InvalidQuorum(uint8 invalidQuorum);
    error InvalidFeedLength(uint256 invalidLength);
    error InvalidMaxChange(uint256 invalidMaxChange);
    error InvalidMinMax(uint256 invalidMin, uint256 invalidMax);
    error InvalidInitialization(uint256 invalidExchangeRate);
    error UpdateCooldown(uint256 lastUpdated);

    /**
     * @notice Creates a new `ReserveOracle` instance.
     * @param _ilkIndex of the associated collateral.
     * @param _feeds Alternative data sources to be used for the reserve oracle.
     * @param _quorum The number of feeds to aggregate.
     * @param _maxChange Maximum percent change between exchange rate updates. [RAY]
     */
    constructor(uint8 _ilkIndex, address[] memory _feeds, uint8 _quorum, uint256 _maxChange) {
        if (_feeds.length != FEED_COUNT) revert InvalidFeedLength(_feeds.length);
        if (_quorum > FEED_COUNT) revert InvalidQuorum(_quorum);
        if (_maxChange == 0 || _maxChange > RAY) revert InvalidMaxChange(_maxChange);

        ILK_INDEX = _ilkIndex;
        QUORUM = _quorum;
        MAX_CHANGE = _maxChange;

        FEED0 = IReserveFeed(_feeds[0]);
        FEED1 = IReserveFeed(_feeds[1]);
        FEED2 = IReserveFeed(_feeds[2]);
    }

    // --- Override ---

    /**
     * @notice Returns the protocol exchange rate.
     * @dev Must be implemented in the child contract with LST-specific logic.
     * @return The protocol exchange rate.
     */
    function _getProtocolExchangeRate() internal view virtual returns (uint256);

    /**
     * @notice Returns the protocol exchange rate.
     * @return The protocol exchange rate.
     */
    function getProtocolExchangeRate() external view returns (uint256) {
        return _getProtocolExchangeRate();
    }

    /**
     * @notice Queries values from whitelisted data feeds and calculates the
     * mean. This does not include the protocol exchange rate.
     * @param _ILK_INDEX of the associated collateral.
     */
    function _aggregate(uint8 _ILK_INDEX) internal view returns (uint256 val) {
        if (QUORUM == 0) {
            return type(uint256).max;
        } else if (QUORUM == 1) {
            val = FEED0.getExchangeRate(_ILK_INDEX);
        } else if (QUORUM == 2) {
            uint256 feed0ExchangeRate = FEED0.getExchangeRate(_ILK_INDEX);
            uint256 feed1ExchangeRate = FEED1.getExchangeRate(_ILK_INDEX);
            val = ((feed0ExchangeRate + feed1ExchangeRate) / uint256(QUORUM));
        } else if (QUORUM == 3) {
            uint256 feed0ExchangeRate = FEED0.getExchangeRate(_ILK_INDEX);
            uint256 feed1ExchangeRate = FEED1.getExchangeRate(_ILK_INDEX);
            uint256 feed2ExchangeRate = FEED2.getExchangeRate(_ILK_INDEX);
            val = ((feed0ExchangeRate + feed1ExchangeRate + feed2ExchangeRate) / uint256(QUORUM));
        }
    }

    /**
     * @notice Bounds the value between the min and the max.
     * @param value The value to be bounded.
     * @param min The minimum bound.
     * @param max The maximum bound.
     */
    function _bound(uint256 value, uint256 min, uint256 max) internal pure returns (uint256) {
        if (min > max) revert InvalidMinMax(min, max);

        return Math.max(min, Math.min(max, value));
    }

    /**
     * @notice Initializes the `currentExchangeRate` state variable.
     * @dev Called once during construction.
     */
    function _initializeExchangeRate() internal {
        currentExchangeRate = Math.min(_getProtocolExchangeRate(), _aggregate(ILK_INDEX));
        if (currentExchangeRate == 0) {
            revert InvalidInitialization(currentExchangeRate);
        }

        emit UpdateExchangeRate(currentExchangeRate);
    }

    /**
     * @notice Updates the `currentExchangeRate` state variable.
     * @dev Takes the minimum between the aggregated values and the protocol exchange rate,
     * then bounds it up to the maximum change and writes the bounded value to the state.
     * NOTE: keepers should call this update to reflect recent values
     */
    function updateExchangeRate() external {
        if (block.timestamp - lastUpdated < UPDATE_COOLDOWN) revert UpdateCooldown(lastUpdated);

        uint256 _currentExchangeRate = currentExchangeRate;

        uint256 minimum = Math.min(_getProtocolExchangeRate(), _aggregate(ILK_INDEX));
        uint256 diff = _currentExchangeRate.rayMulDown(MAX_CHANGE);

        uint256 bounded = _bound(minimum, _currentExchangeRate - diff, _currentExchangeRate + diff);
        currentExchangeRate = bounded;

        lastUpdated = block.timestamp;

        emit UpdateExchangeRate(bounded);
    }
}

File 17 of 36 : IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

File 18 of 36 : IERC20Errors.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.21;

/**
 * @dev Standard ERC20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

File 19 of 36 : ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

File 20 of 36 : AccessControlDefaultAdminRulesUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/AccessControlDefaultAdminRules.sol)

pragma solidity ^0.8.20;

import {IAccessControlDefaultAdminRules} from "@openzeppelin/contracts/access/extensions/IAccessControlDefaultAdminRules.sol";
import {AccessControlUpgradeable} from "../AccessControlUpgradeable.sol";
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IERC5313} from "@openzeppelin/contracts/interfaces/IERC5313.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Extension of {AccessControl} that allows specifying special rules to manage
 * the `DEFAULT_ADMIN_ROLE` holder, which is a sensitive role with special permissions
 * over other roles that may potentially have privileged rights in the system.
 *
 * If a specific role doesn't have an admin role assigned, the holder of the
 * `DEFAULT_ADMIN_ROLE` will have the ability to grant it and revoke it.
 *
 * This contract implements the following risk mitigations on top of {AccessControl}:
 *
 * * Only one account holds the `DEFAULT_ADMIN_ROLE` since deployment until it's potentially renounced.
 * * Enforces a 2-step process to transfer the `DEFAULT_ADMIN_ROLE` to another account.
 * * Enforces a configurable delay between the two steps, with the ability to cancel before the transfer is accepted.
 * * The delay can be changed by scheduling, see {changeDefaultAdminDelay}.
 * * It is not possible to use another role to manage the `DEFAULT_ADMIN_ROLE`.
 *
 * Example usage:
 *
 * ```solidity
 * contract MyToken is AccessControlDefaultAdminRules {
 *   constructor() AccessControlDefaultAdminRules(
 *     3 days,
 *     msg.sender // Explicit initial `DEFAULT_ADMIN_ROLE` holder
 *    ) {}
 * }
 * ```
 */
abstract contract AccessControlDefaultAdminRulesUpgradeable is Initializable, IAccessControlDefaultAdminRules, IERC5313, AccessControlUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControlDefaultAdminRules
    struct AccessControlDefaultAdminRulesStorage {
        // pending admin pair read/written together frequently
        address _pendingDefaultAdmin;
        uint48 _pendingDefaultAdminSchedule; // 0 == unset

        uint48 _currentDelay;
        address _currentDefaultAdmin;

        // pending delay pair read/written together frequently
        uint48 _pendingDelay;
        uint48 _pendingDelaySchedule; // 0 == unset
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControlDefaultAdminRules")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessControlDefaultAdminRulesStorageLocation = 0xeef3dac4538c82c8ace4063ab0acd2d15cdb5883aa1dff7c2673abb3d8698400;

    function _getAccessControlDefaultAdminRulesStorage() private pure returns (AccessControlDefaultAdminRulesStorage storage $) {
        assembly {
            $.slot := AccessControlDefaultAdminRulesStorageLocation
        }
    }

    /**
     * @dev Sets the initial values for {defaultAdminDelay} and {defaultAdmin} address.
     */
    function __AccessControlDefaultAdminRules_init(uint48 initialDelay, address initialDefaultAdmin) internal onlyInitializing {
        __AccessControlDefaultAdminRules_init_unchained(initialDelay, initialDefaultAdmin);
    }

    function __AccessControlDefaultAdminRules_init_unchained(uint48 initialDelay, address initialDefaultAdmin) internal onlyInitializing {
        AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
        if (initialDefaultAdmin == address(0)) {
            revert AccessControlInvalidDefaultAdmin(address(0));
        }
        $._currentDelay = initialDelay;
        _grantRole(DEFAULT_ADMIN_ROLE, initialDefaultAdmin);
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlDefaultAdminRules).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC5313-owner}.
     */
    function owner() public view virtual returns (address) {
        return defaultAdmin();
    }

    ///
    /// Override AccessControl role management
    ///

    /**
     * @dev See {AccessControl-grantRole}. Reverts for `DEFAULT_ADMIN_ROLE`.
     */
    function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControl) {
        if (role == DEFAULT_ADMIN_ROLE) {
            revert AccessControlEnforcedDefaultAdminRules();
        }
        super.grantRole(role, account);
    }

    /**
     * @dev See {AccessControl-revokeRole}. Reverts for `DEFAULT_ADMIN_ROLE`.
     */
    function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControl) {
        if (role == DEFAULT_ADMIN_ROLE) {
            revert AccessControlEnforcedDefaultAdminRules();
        }
        super.revokeRole(role, account);
    }

    /**
     * @dev See {AccessControl-renounceRole}.
     *
     * For the `DEFAULT_ADMIN_ROLE`, it only allows renouncing in two steps by first calling
     * {beginDefaultAdminTransfer} to the `address(0)`, so it's required that the {pendingDefaultAdmin} schedule
     * has also passed when calling this function.
     *
     * After its execution, it will not be possible to call `onlyRole(DEFAULT_ADMIN_ROLE)` functions.
     *
     * NOTE: Renouncing `DEFAULT_ADMIN_ROLE` will leave the contract without a {defaultAdmin},
     * thereby disabling any functionality that is only available for it, and the possibility of reassigning a
     * non-administrated role.
     */
    function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControl) {
        AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
        if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) {
            (address newDefaultAdmin, uint48 schedule) = pendingDefaultAdmin();
            if (newDefaultAdmin != address(0) || !_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) {
                revert AccessControlEnforcedDefaultAdminDelay(schedule);
            }
            delete $._pendingDefaultAdminSchedule;
        }
        super.renounceRole(role, account);
    }

    /**
     * @dev See {AccessControl-_grantRole}.
     *
     * For `DEFAULT_ADMIN_ROLE`, it only allows granting if there isn't already a {defaultAdmin} or if the
     * role has been previously renounced.
     *
     * NOTE: Exposing this function through another mechanism may make the `DEFAULT_ADMIN_ROLE`
     * assignable again. Make sure to guarantee this is the expected behavior in your implementation.
     */
    function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
        AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
        if (role == DEFAULT_ADMIN_ROLE) {
            if (defaultAdmin() != address(0)) {
                revert AccessControlEnforcedDefaultAdminRules();
            }
            $._currentDefaultAdmin = account;
        }
        return super._grantRole(role, account);
    }

    /**
     * @dev See {AccessControl-_revokeRole}.
     */
    function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
        AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
        if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) {
            delete $._currentDefaultAdmin;
        }
        return super._revokeRole(role, account);
    }

    /**
     * @dev See {AccessControl-_setRoleAdmin}. Reverts for `DEFAULT_ADMIN_ROLE`.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual override {
        if (role == DEFAULT_ADMIN_ROLE) {
            revert AccessControlEnforcedDefaultAdminRules();
        }
        super._setRoleAdmin(role, adminRole);
    }

    ///
    /// AccessControlDefaultAdminRules accessors
    ///

    /**
     * @inheritdoc IAccessControlDefaultAdminRules
     */
    function defaultAdmin() public view virtual returns (address) {
        AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
        return $._currentDefaultAdmin;
    }

    /**
     * @inheritdoc IAccessControlDefaultAdminRules
     */
    function pendingDefaultAdmin() public view virtual returns (address newAdmin, uint48 schedule) {
        AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
        return ($._pendingDefaultAdmin, $._pendingDefaultAdminSchedule);
    }

    /**
     * @inheritdoc IAccessControlDefaultAdminRules
     */
    function defaultAdminDelay() public view virtual returns (uint48) {
        AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
        uint48 schedule = $._pendingDelaySchedule;
        return (_isScheduleSet(schedule) && _hasSchedulePassed(schedule)) ? $._pendingDelay : $._currentDelay;
    }

    /**
     * @inheritdoc IAccessControlDefaultAdminRules
     */
    function pendingDefaultAdminDelay() public view virtual returns (uint48 newDelay, uint48 schedule) {
        AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
        schedule = $._pendingDelaySchedule;
        return (_isScheduleSet(schedule) && !_hasSchedulePassed(schedule)) ? ($._pendingDelay, schedule) : (0, 0);
    }

    /**
     * @inheritdoc IAccessControlDefaultAdminRules
     */
    function defaultAdminDelayIncreaseWait() public view virtual returns (uint48) {
        return 5 days;
    }

    ///
    /// AccessControlDefaultAdminRules public and internal setters for defaultAdmin/pendingDefaultAdmin
    ///

    /**
     * @inheritdoc IAccessControlDefaultAdminRules
     */
    function beginDefaultAdminTransfer(address newAdmin) public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
        _beginDefaultAdminTransfer(newAdmin);
    }

    /**
     * @dev See {beginDefaultAdminTransfer}.
     *
     * Internal function without access restriction.
     */
    function _beginDefaultAdminTransfer(address newAdmin) internal virtual {
        uint48 newSchedule = SafeCast.toUint48(block.timestamp) + defaultAdminDelay();
        _setPendingDefaultAdmin(newAdmin, newSchedule);
        emit DefaultAdminTransferScheduled(newAdmin, newSchedule);
    }

    /**
     * @inheritdoc IAccessControlDefaultAdminRules
     */
    function cancelDefaultAdminTransfer() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
        _cancelDefaultAdminTransfer();
    }

    /**
     * @dev See {cancelDefaultAdminTransfer}.
     *
     * Internal function without access restriction.
     */
    function _cancelDefaultAdminTransfer() internal virtual {
        _setPendingDefaultAdmin(address(0), 0);
    }

    /**
     * @inheritdoc IAccessControlDefaultAdminRules
     */
    function acceptDefaultAdminTransfer() public virtual {
        (address newDefaultAdmin, ) = pendingDefaultAdmin();
        if (_msgSender() != newDefaultAdmin) {
            // Enforce newDefaultAdmin explicit acceptance.
            revert AccessControlInvalidDefaultAdmin(_msgSender());
        }
        _acceptDefaultAdminTransfer();
    }

    /**
     * @dev See {acceptDefaultAdminTransfer}.
     *
     * Internal function without access restriction.
     */
    function _acceptDefaultAdminTransfer() internal virtual {
        AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
        (address newAdmin, uint48 schedule) = pendingDefaultAdmin();
        if (!_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) {
            revert AccessControlEnforcedDefaultAdminDelay(schedule);
        }
        _revokeRole(DEFAULT_ADMIN_ROLE, defaultAdmin());
        _grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
        delete $._pendingDefaultAdmin;
        delete $._pendingDefaultAdminSchedule;
    }

    ///
    /// AccessControlDefaultAdminRules public and internal setters for defaultAdminDelay/pendingDefaultAdminDelay
    ///

    /**
     * @inheritdoc IAccessControlDefaultAdminRules
     */
    function changeDefaultAdminDelay(uint48 newDelay) public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
        _changeDefaultAdminDelay(newDelay);
    }

    /**
     * @dev See {changeDefaultAdminDelay}.
     *
     * Internal function without access restriction.
     */
    function _changeDefaultAdminDelay(uint48 newDelay) internal virtual {
        uint48 newSchedule = SafeCast.toUint48(block.timestamp) + _delayChangeWait(newDelay);
        _setPendingDelay(newDelay, newSchedule);
        emit DefaultAdminDelayChangeScheduled(newDelay, newSchedule);
    }

    /**
     * @inheritdoc IAccessControlDefaultAdminRules
     */
    function rollbackDefaultAdminDelay() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
        _rollbackDefaultAdminDelay();
    }

    /**
     * @dev See {rollbackDefaultAdminDelay}.
     *
     * Internal function without access restriction.
     */
    function _rollbackDefaultAdminDelay() internal virtual {
        _setPendingDelay(0, 0);
    }

    /**
     * @dev Returns the amount of seconds to wait after the `newDelay` will
     * become the new {defaultAdminDelay}.
     *
     * The value returned guarantees that if the delay is reduced, it will go into effect
     * after a wait that honors the previously set delay.
     *
     * See {defaultAdminDelayIncreaseWait}.
     */
    function _delayChangeWait(uint48 newDelay) internal view virtual returns (uint48) {
        uint48 currentDelay = defaultAdminDelay();

        // When increasing the delay, we schedule the delay change to occur after a period of "new delay" has passed, up
        // to a maximum given by defaultAdminDelayIncreaseWait, by default 5 days. For example, if increasing from 1 day
        // to 3 days, the new delay will come into effect after 3 days. If increasing from 1 day to 10 days, the new
        // delay will come into effect after 5 days. The 5 day wait period is intended to be able to fix an error like
        // using milliseconds instead of seconds.
        //
        // When decreasing the delay, we wait the difference between "current delay" and "new delay". This guarantees
        // that an admin transfer cannot be made faster than "current delay" at the time the delay change is scheduled.
        // For example, if decreasing from 10 days to 3 days, the new delay will come into effect after 7 days.
        return
            newDelay > currentDelay
                ? uint48(Math.min(newDelay, defaultAdminDelayIncreaseWait())) // no need to safecast, both inputs are uint48
                : currentDelay - newDelay;
    }

    ///
    /// Private setters
    ///

    /**
     * @dev Setter of the tuple for pending admin and its schedule.
     *
     * May emit a DefaultAdminTransferCanceled event.
     */
    function _setPendingDefaultAdmin(address newAdmin, uint48 newSchedule) private {
        AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
        (, uint48 oldSchedule) = pendingDefaultAdmin();

        $._pendingDefaultAdmin = newAdmin;
        $._pendingDefaultAdminSchedule = newSchedule;

        // An `oldSchedule` from `pendingDefaultAdmin()` is only set if it hasn't been accepted.
        if (_isScheduleSet(oldSchedule)) {
            // Emit for implicit cancellations when another default admin was scheduled.
            emit DefaultAdminTransferCanceled();
        }
    }

    /**
     * @dev Setter of the tuple for pending delay and its schedule.
     *
     * May emit a DefaultAdminDelayChangeCanceled event.
     */
    function _setPendingDelay(uint48 newDelay, uint48 newSchedule) private {
        AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage();
        uint48 oldSchedule = $._pendingDelaySchedule;

        if (_isScheduleSet(oldSchedule)) {
            if (_hasSchedulePassed(oldSchedule)) {
                // Materialize a virtual delay
                $._currentDelay = $._pendingDelay;
            } else {
                // Emit for implicit cancellations when another delay was scheduled.
                emit DefaultAdminDelayChangeCanceled();
            }
        }

        $._pendingDelay = newDelay;
        $._pendingDelaySchedule = newSchedule;
    }

    ///
    /// Private helpers
    ///

    /**
     * @dev Defines if an `schedule` is considered set. For consistency purposes.
     */
    function _isScheduleSet(uint48 schedule) private pure returns (bool) {
        return schedule != 0;
    }

    /**
     * @dev Defines if an `schedule` is considered passed. For consistency purposes.
     */
    function _hasSchedulePassed(uint48 schedule) private view returns (bool) {
        return schedule < block.timestamp;
    }
}

File 21 of 36 : MessageHashUtils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
 *
 * The library provides methods for generating a hash of a message that conforms to the
 * https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing a bytes32 `messageHash` with
     * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
     * keccak256, although any bytes32 value can be safely used because the final digest will
     * be re-hashed.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing an arbitrary `message` with
     * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
        return
            keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x00` (data with intended validator).
     *
     * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
     * `validator` address. Then hashing the result.
     *
     * See {ECDSA-recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(hex"19_00", validator, data));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
     *
     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
     * `\x19\x01` and hashing the result. It corresponds to the hash signed by the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
     *
     * See {ECDSA-recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }
}

File 22 of 36 : ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     */
    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError, bytes32) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

File 23 of 36 : IYieldOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

interface IYieldOracle {
    function apys(uint256 ilkIndex) external view returns (uint32);
}

File 24 of 36 : IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

File 25 of 36 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}

File 26 of 36 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

File 27 of 36 : Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

File 28 of 36 : IReserveFeed.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.21;

/**
 * @title IReserveFeed interface
 * @notice Interface for the reserve feeds for Ion Protocol.
 *
 */
interface IReserveFeed {
    /**
     * @dev updates the total reserve of the validator backed asset
     * @param ilkIndex the ilk index of the asset
     * @param reserve the total ETH reserve of the asset in wei
     */
    function updateExchangeRate(uint8 ilkIndex, uint256 reserve) external;

    /**
     * @dev returns the total reserve of the validator backed asset
     * @param ilkIndex the ilk index of the asset
     * @return the total ETH reserve of the asset in wei
     */
    function getExchangeRate(uint8 ilkIndex) external view returns (uint256);
}

File 29 of 36 : IAccessControlDefaultAdminRules.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/IAccessControlDefaultAdminRules.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev External interface of AccessControlDefaultAdminRules declared to support ERC165 detection.
 */
interface IAccessControlDefaultAdminRules is IAccessControl {
    /**
     * @dev The new default admin is not a valid default admin.
     */
    error AccessControlInvalidDefaultAdmin(address defaultAdmin);

    /**
     * @dev At least one of the following rules was violated:
     *
     * - The `DEFAULT_ADMIN_ROLE` must only be managed by itself.
     * - The `DEFAULT_ADMIN_ROLE` must only be held by one account at the time.
     * - Any `DEFAULT_ADMIN_ROLE` transfer must be in two delayed steps.
     */
    error AccessControlEnforcedDefaultAdminRules();

    /**
     * @dev The delay for transferring the default admin delay is enforced and
     * the operation must wait until `schedule`.
     *
     * NOTE: `schedule` can be 0 indicating there's no transfer scheduled.
     */
    error AccessControlEnforcedDefaultAdminDelay(uint48 schedule);

    /**
     * @dev Emitted when a {defaultAdmin} transfer is started, setting `newAdmin` as the next
     * address to become the {defaultAdmin} by calling {acceptDefaultAdminTransfer} only after `acceptSchedule`
     * passes.
     */
    event DefaultAdminTransferScheduled(address indexed newAdmin, uint48 acceptSchedule);

    /**
     * @dev Emitted when a {pendingDefaultAdmin} is reset if it was never accepted, regardless of its schedule.
     */
    event DefaultAdminTransferCanceled();

    /**
     * @dev Emitted when a {defaultAdminDelay} change is started, setting `newDelay` as the next
     * delay to be applied between default admin transfer after `effectSchedule` has passed.
     */
    event DefaultAdminDelayChangeScheduled(uint48 newDelay, uint48 effectSchedule);

    /**
     * @dev Emitted when a {pendingDefaultAdminDelay} is reset if its schedule didn't pass.
     */
    event DefaultAdminDelayChangeCanceled();

    /**
     * @dev Returns the address of the current `DEFAULT_ADMIN_ROLE` holder.
     */
    function defaultAdmin() external view returns (address);

    /**
     * @dev Returns a tuple of a `newAdmin` and an accept schedule.
     *
     * After the `schedule` passes, the `newAdmin` will be able to accept the {defaultAdmin} role
     * by calling {acceptDefaultAdminTransfer}, completing the role transfer.
     *
     * A zero value only in `acceptSchedule` indicates no pending admin transfer.
     *
     * NOTE: A zero address `newAdmin` means that {defaultAdmin} is being renounced.
     */
    function pendingDefaultAdmin() external view returns (address newAdmin, uint48 acceptSchedule);

    /**
     * @dev Returns the delay required to schedule the acceptance of a {defaultAdmin} transfer started.
     *
     * This delay will be added to the current timestamp when calling {beginDefaultAdminTransfer} to set
     * the acceptance schedule.
     *
     * NOTE: If a delay change has been scheduled, it will take effect as soon as the schedule passes, making this
     * function returns the new delay. See {changeDefaultAdminDelay}.
     */
    function defaultAdminDelay() external view returns (uint48);

    /**
     * @dev Returns a tuple of `newDelay` and an effect schedule.
     *
     * After the `schedule` passes, the `newDelay` will get into effect immediately for every
     * new {defaultAdmin} transfer started with {beginDefaultAdminTransfer}.
     *
     * A zero value only in `effectSchedule` indicates no pending delay change.
     *
     * NOTE: A zero value only for `newDelay` means that the next {defaultAdminDelay}
     * will be zero after the effect schedule.
     */
    function pendingDefaultAdminDelay() external view returns (uint48 newDelay, uint48 effectSchedule);

    /**
     * @dev Starts a {defaultAdmin} transfer by setting a {pendingDefaultAdmin} scheduled for acceptance
     * after the current timestamp plus a {defaultAdminDelay}.
     *
     * Requirements:
     *
     * - Only can be called by the current {defaultAdmin}.
     *
     * Emits a DefaultAdminRoleChangeStarted event.
     */
    function beginDefaultAdminTransfer(address newAdmin) external;

    /**
     * @dev Cancels a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
     *
     * A {pendingDefaultAdmin} not yet accepted can also be cancelled with this function.
     *
     * Requirements:
     *
     * - Only can be called by the current {defaultAdmin}.
     *
     * May emit a DefaultAdminTransferCanceled event.
     */
    function cancelDefaultAdminTransfer() external;

    /**
     * @dev Completes a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
     *
     * After calling the function:
     *
     * - `DEFAULT_ADMIN_ROLE` should be granted to the caller.
     * - `DEFAULT_ADMIN_ROLE` should be revoked from the previous holder.
     * - {pendingDefaultAdmin} should be reset to zero values.
     *
     * Requirements:
     *
     * - Only can be called by the {pendingDefaultAdmin}'s `newAdmin`.
     * - The {pendingDefaultAdmin}'s `acceptSchedule` should've passed.
     */
    function acceptDefaultAdminTransfer() external;

    /**
     * @dev Initiates a {defaultAdminDelay} update by setting a {pendingDefaultAdminDelay} scheduled for getting
     * into effect after the current timestamp plus a {defaultAdminDelay}.
     *
     * This function guarantees that any call to {beginDefaultAdminTransfer} done between the timestamp this
     * method is called and the {pendingDefaultAdminDelay} effect schedule will use the current {defaultAdminDelay}
     * set before calling.
     *
     * The {pendingDefaultAdminDelay}'s effect schedule is defined in a way that waiting until the schedule and then
     * calling {beginDefaultAdminTransfer} with the new delay will take at least the same as another {defaultAdmin}
     * complete transfer (including acceptance).
     *
     * The schedule is designed for two scenarios:
     *
     * - When the delay is changed for a larger one the schedule is `block.timestamp + newDelay` capped by
     * {defaultAdminDelayIncreaseWait}.
     * - When the delay is changed for a shorter one, the schedule is `block.timestamp + (current delay - new delay)`.
     *
     * A {pendingDefaultAdminDelay} that never got into effect will be canceled in favor of a new scheduled change.
     *
     * Requirements:
     *
     * - Only can be called by the current {defaultAdmin}.
     *
     * Emits a DefaultAdminDelayChangeScheduled event and may emit a DefaultAdminDelayChangeCanceled event.
     */
    function changeDefaultAdminDelay(uint48 newDelay) external;

    /**
     * @dev Cancels a scheduled {defaultAdminDelay} change.
     *
     * Requirements:
     *
     * - Only can be called by the current {defaultAdmin}.
     *
     * May emit a DefaultAdminDelayChangeCanceled event.
     */
    function rollbackDefaultAdminDelay() external;

    /**
     * @dev Maximum time in seconds for an increase to {defaultAdminDelay} (that is scheduled using {changeDefaultAdminDelay})
     * to take effect. Default to 5 days.
     *
     * When the {defaultAdminDelay} is scheduled to be increased, it goes into effect after the new delay has passed with
     * the purpose of giving enough time for reverting any accidental change (i.e. using milliseconds instead of seconds)
     * that may lock the contract. However, to avoid excessive schedules, the wait is capped by this function and it can
     * be overrode for a custom {defaultAdminDelay} increase scheduling.
     *
     * IMPORTANT: Make sure to add a reasonable amount of time while overriding this value, otherwise,
     * there's a risk of setting a high new delay that goes into effect almost immediately without the
     * possibility of human intervention in the case of an input error (eg. set milliseconds instead of seconds).
     */
    function defaultAdminDelayIncreaseWait() external view returns (uint48);
}

File 30 of 36 : AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;


    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
    struct AccessControlStorage {
        mapping(bytes32 role => RoleData) _roles;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;

    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
        assembly {
            $.slot := AccessControlStorageLocation
        }
    }

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        AccessControlStorage storage $ = _getAccessControlStorage();
        bytes32 previousAdminRole = getRoleAdmin(role);
        $._roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (!hasRole(role, account)) {
            $._roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (hasRole(role, account)) {
            $._roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

File 31 of 36 : IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

File 32 of 36 : IERC5313.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5313.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface for the Light Contract Ownership Standard.
 *
 * A standardized minimal interface required to identify an account that controls a contract
 */
interface IERC5313 {
    /**
     * @dev Gets the address of the owner.
     */
    function owner() external view returns (address);
}

File 33 of 36 : Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

File 34 of 36 : ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165Upgradeable is Initializable, IERC165 {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

File 35 of 36 : SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

File 36 of 36 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

Settings
{
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@balancer-labs/v2-interfaces/=lib/balancer-v2-monorepo/pkg/interfaces/",
    "@balancer-labs/v2-pool-stable/=lib/balancer-v2-monorepo/pkg/pool-stable/",
    "@chainlink/contracts/=lib/chainlink/contracts/",
    "@uniswap/v3-periphery/=lib/v3-periphery/",
    "@uniswap/v3-core/=lib/v3-core/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "balancer-v2-monorepo/=lib/balancer-v2-monorepo/",
    "chainlink/=lib/chainlink/",
    "ds-test/=lib/forge-safe/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-safe/=lib/forge-safe/src/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "solady/=lib/solady/",
    "solidity-stringutils/=lib/forge-safe/lib/surl/lib/solidity-stringutils/",
    "solmate/=lib/forge-safe/lib/solmate/src/",
    "surl/=lib/forge-safe/lib/surl/",
    "v3-core/=lib/v3-core/",
    "v3-periphery/=lib/v3-periphery/contracts/",
    "solarray/=lib/solarray/src/",
    "pendle-core-v2-public/=lib/pendle-core-v2-public/contracts/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "shanghai",
  "viaIR": false,
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"uint48","name":"schedule","type":"uint48"}],"name":"AccessControlEnforcedDefaultAdminDelay","type":"error"},{"inputs":[],"name":"AccessControlEnforcedDefaultAdminRules","type":"error"},{"inputs":[{"internalType":"address","name":"defaultAdmin","type":"address"}],"name":"AccessControlInvalidDefaultAdmin","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"ArithmeticError","type":"error"},{"inputs":[{"internalType":"uint256","name":"newDebt","type":"uint256"},{"internalType":"uint256","name":"debtCeiling","type":"uint256"}],"name":"CeilingExceeded","type":"error"},{"inputs":[{"internalType":"uint256","name":"depositAmount","type":"uint256"},{"internalType":"uint256","name":"supplyCap","type":"uint256"}],"name":"DepositSurpassesSupplyCap","type":"error"},{"inputs":[],"name":"ECDSAInvalidSignature","type":"error"},{"inputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"name":"ECDSAInvalidSignatureLength","type":"error"},{"inputs":[{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"ECDSAInvalidSignatureS","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"allowance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC20InvalidApprover","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC20InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC20InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"}],"name":"ERC20InvalidSpender","type":"error"},{"inputs":[{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"ERC2612ExpiredSignature","type":"error"},{"inputs":[{"internalType":"address","name":"signer","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"ERC2612InvalidSigner","type":"error"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"unconsentedOperator","type":"address"}],"name":"GemTransferWithoutConsent","type":"error"},{"inputs":[{"internalType":"address","name":"ilkAddress","type":"address"}],"name":"IlkAlreadyAdded","type":"error"},{"inputs":[{"internalType":"uint256","name":"ilkIndex","type":"uint256"}],"name":"IlkNotInitialized","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"InsufficientBalance","type":"error"},{"inputs":[],"name":"InvalidBurnAmount","type":"error"},{"inputs":[],"name":"InvalidIlkAddress","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[{"internalType":"contract InterestRate","name":"invalidInterestRateModule","type":"address"}],"name":"InvalidInterestRateModule","type":"error"},{"inputs":[],"name":"InvalidMintAmount","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"InvalidSender","type":"error"},{"inputs":[],"name":"InvalidTreasuryAddress","type":"error"},{"inputs":[],"name":"InvalidUnderlyingAddress","type":"error"},{"inputs":[],"name":"InvalidWhitelist","type":"error"},{"inputs":[],"name":"MathOverflowedMulDiv","type":"error"},{"inputs":[],"name":"MaxIlksReached","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[{"internalType":"uint256","name":"from","type":"uint256"},{"internalType":"uint256","name":"to","type":"uint256"}],"name":"NotScalingUp","type":"error"},{"inputs":[{"internalType":"uint8","name":"bits","type":"uint8"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"SafeCastOverflowedUintDowncast","type":"error"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"SafeCastOverflowedUintToInt","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[{"internalType":"address","name":"self","type":"address"}],"name":"SelfTransfer","type":"error"},{"inputs":[{"internalType":"address","name":"payer","type":"address"},{"internalType":"address","name":"unconsentedOperator","type":"address"}],"name":"TakingWethWithoutConsent","type":"error"},{"inputs":[{"internalType":"uint256","name":"newTotalDebtInVault","type":"uint256"},{"internalType":"uint256","name":"collateral","type":"uint256"},{"internalType":"uint256","name":"spot","type":"uint256"}],"name":"UnsafePositionChange","type":"error"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"unconsentedOperator","type":"address"}],"name":"UnsafePositionChangeWithoutConsent","type":"error"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"address","name":"depositor","type":"address"},{"internalType":"address","name":"unconsentedOperator","type":"address"}],"name":"UseOfCollateralWithoutConsent","type":"error"},{"inputs":[{"internalType":"uint256","name":"amountLeft","type":"uint256"},{"internalType":"uint256","name":"dust","type":"uint256"}],"name":"VaultCannotBeDusty","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"}],"name":"AddOperator","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountOfNormalizedDebt","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"ilkRate","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalDebt","type":"uint256"}],"name":"Borrow","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"indexed":true,"internalType":"address","name":"u","type":"address"},{"indexed":false,"internalType":"address","name":"v","type":"address"},{"indexed":true,"internalType":"address","name":"w","type":"address"},{"indexed":false,"internalType":"int256","name":"changeInCollateral","type":"int256"},{"indexed":false,"internalType":"int256","name":"changeInNormalizedDebt","type":"int256"}],"name":"ConfiscateVault","type":"event"},{"anonymous":false,"inputs":[],"name":"DefaultAdminDelayChangeCanceled","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint48","name":"newDelay","type":"uint48"},{"indexed":false,"internalType":"uint48","name":"effectSchedule","type":"uint48"}],"name":"DefaultAdminDelayChangeScheduled","type":"event"},{"anonymous":false,"inputs":[],"name":"DefaultAdminTransferCanceled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"newAdmin","type":"address"},{"indexed":false,"internalType":"uint48","name":"acceptSchedule","type":"uint48"}],"name":"DefaultAdminTransferScheduled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"depositor","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"DepositCollateral","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"indexed":false,"internalType":"uint256","name":"newDebtCeiling","type":"uint256"}],"name":"IlkDebtCeilingUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"indexed":false,"internalType":"uint256","name":"newDust","type":"uint256"}],"name":"IlkDustUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"indexed":true,"internalType":"address","name":"ilkAddress","type":"address"}],"name":"IlkInitialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"indexed":false,"internalType":"address","name":"newSpot","type":"address"}],"name":"IlkSpotUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newModule","type":"address"}],"name":"InterestRateModuleUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"indexed":true,"internalType":"address","name":"usr","type":"address"},{"indexed":false,"internalType":"int256","name":"wad","type":"int256"}],"name":"MintAndBurnGem","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"treasury","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"supplyFactor","type":"uint256"}],"name":"MintToTreasury","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"}],"name":"RemoveOperator","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"payer","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountOfNormalizedDebt","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"ilkRate","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalDebt","type":"uint256"}],"name":"Repay","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"payer","type":"address"},{"indexed":false,"internalType":"uint256","name":"rad","type":"uint256"}],"name":"RepayBadDebt","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"underlyingFrom","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"supplyFactor","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newDebt","type":"uint256"}],"name":"Supply","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newSupplyCap","type":"uint256"}],"name":"SupplyCapUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"indexed":true,"internalType":"address","name":"src","type":"address"},{"indexed":true,"internalType":"address","name":"dst","type":"address"},{"indexed":false,"internalType":"uint256","name":"wad","type":"uint256"}],"name":"TransferGem","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"treasury","type":"address"}],"name":"TreasuryUpdate","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newWhitelist","type":"address"}],"name":"WhitelistUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"target","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"supplyFactor","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newDebt","type":"uint256"}],"name":"Withdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"WithdrawCollateral","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GEM_JOIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ION","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LIQUIDATOR_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PAUSE_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PERMIT_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"acceptDefaultAdminTransfer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"accrueInterest","outputs":[{"internalType":"uint256","name":"newTotalDebt","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"}],"name":"addOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"balanceOfUnaccrued","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newAdmin","type":"address"}],"name":"beginDefaultAdminTransfer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amountOfNormalizedDebt","type":"uint256"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"}],"name":"borrow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"calculateRewardAndDebtDistribution","outputs":[{"internalType":"uint256","name":"totalSupplyFactorIncrease","type":"uint256"},{"internalType":"uint256","name":"totalTreasuryMintAmount","type":"uint256"},{"internalType":"uint104[]","name":"rateIncreases","type":"uint104[]"},{"internalType":"uint256","name":"totalDebtIncrease","type":"uint256"},{"internalType":"uint48[]","name":"timestampIncreases","type":"uint48[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"}],"name":"calculateRewardAndDebtDistributionForIlk","outputs":[{"internalType":"uint104","name":"newRateIncrease","type":"uint104"},{"internalType":"uint48","name":"timestampIncrease","type":"uint48"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"cancelDefaultAdminTransfer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint48","name":"newDelay","type":"uint48"}],"name":"changeDefaultAdminDelay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"address","name":"user","type":"address"}],"name":"collateral","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"address","name":"u","type":"address"},{"internalType":"address","name":"v","type":"address"},{"internalType":"address","name":"w","type":"address"},{"internalType":"int256","name":"changeInCollateral","type":"int256"},{"internalType":"int256","name":"changeInNormalizedDebt","type":"int256"}],"name":"confiscateVault","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"defaultAdmin","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"defaultAdminDelay","outputs":[{"internalType":"uint48","name":"","type":"uint48"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"defaultAdminDelayIncreaseWait","outputs":[{"internalType":"uint48","name":"","type":"uint48"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"depositor","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"}],"name":"depositCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"}],"name":"dust","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"extsload","outputs":[{"internalType":"bytes32","name":"value","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"}],"name":"getCurrentBorrowRate","outputs":[{"internalType":"uint256","name":"borrowRate","type":"uint256"},{"internalType":"uint256","name":"reserveFactor","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"ilkIndex","type":"uint256"}],"name":"getIlkAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"implementation","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_underlying","type":"address"},{"internalType":"address","name":"_treasury","type":"address"},{"internalType":"uint8","name":"decimals_","type":"uint8"},{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"},{"internalType":"address","name":"initialDefaultAdmin","type":"address"},{"internalType":"contract InterestRate","name":"_interestRateModule","type":"address"},{"internalType":"contract Whitelist","name":"_whitelist","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"ilkAddress","type":"address"}],"name":"initializeIlk","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isAllowed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"address","name":"usr","type":"address"},{"internalType":"int256","name":"wad","type":"int256"}],"name":"mintAndBurnGem","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"normalizedBalanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"address","name":"user","type":"address"}],"name":"normalizedDebt","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"normalizedTotalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"normalizedTotalSupplyUnaccrued","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingDefaultAdmin","outputs":[{"internalType":"address","name":"newAdmin","type":"address"},{"internalType":"uint48","name":"schedule","type":"uint48"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingDefaultAdminDelay","outputs":[{"internalType":"uint48","name":"newDelay","type":"uint48"},{"internalType":"uint48","name":"schedule","type":"uint48"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"}],"name":"rate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"}],"name":"removeOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"payer","type":"address"},{"internalType":"uint256","name":"amountOfNormalizedDebt","type":"uint256"}],"name":"repay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"rad","type":"uint256"}],"name":"repayBadDebt","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rollbackDefaultAdminDelay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"}],"name":"supply","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"supplyFactor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"supplyFactorUnaccrued","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupplyUnaccrued","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"address","name":"src","type":"address"},{"internalType":"address","name":"dst","type":"address"},{"internalType":"uint256","name":"wad","type":"uint256"}],"name":"transferGem","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"treasury","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"underlying","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"uint256","name":"newCeiling","type":"uint256"}],"name":"updateIlkDebtCeiling","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"uint256","name":"newDust","type":"uint256"}],"name":"updateIlkDust","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"contract SpotOracle","name":"newSpot","type":"address"}],"name":"updateIlkSpot","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract InterestRate","name":"_interestRateModule","type":"address"}],"name":"updateInterestRateModule","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newSupplyCap","type":"uint256"}],"name":"updateSupplyCap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newTreasury","type":"address"}],"name":"updateTreasury","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract Whitelist","name":"_whitelist","type":"address"}],"name":"updateWhitelist","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"address","name":"user","type":"address"}],"name":"vault","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"receiverOfUnderlying","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"ilkIndex","type":"uint8"},{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdrawCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60a06040523060805234801562000014575f80fd5b506200001f62000025565b620000d9565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000900460ff1615620000765760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b0390811614620000d65780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b608051615c3d620000f25f395f61068c0152615c3d5ff3fe608060405234801561000f575f80fd5b506004361061046f575f3560e01c80638456cb591161024d578063a9059cbb11610140578063d547741f116100bf578063e5a97f0711610084578063e5a97f0714610a5f578063e862114a14610a72578063efff005f14610a85578063f09b808d14610a98578063f3fef3a314610aa0575f80fd5b8063d547741f14610a0a578063d602b9fd14610a1d578063d831efd814610a25578063dcec05bf14610a38578063dd62ed3e14610a4c575f80fd5b8063c358b49a11610105578063c358b49a146109b1578063cc8463c8146109b9578063cefc1429146109c1578063cf6eefb7146109c9578063d505accf146109f7575f80fd5b8063a9059cbb1461095d578063ac8a584a14610970578063b827735f14610983578063b85e868e14610996578063c0cc5edf1461099e575f80fd5b806397939743116101cc578063a217fddf11610191578063a217fddf146108ef578063a36f653d146108f6578063a6afed9514610909578063a716272814610911578063a778d7b314610924575f80fd5b8063979397431461087c5780639870d7fe1461088f5780639a3db79b146108a2578063a1654379146108b5578063a1eda53c146108c8575f80fd5b80638fb5400e116102125780638fb5400e14610828578063918a2f421461083b57806391d148541461084e5780639306f2f81461086157806395d89b4114610874575f80fd5b80638456cb59146107ea5780638459b437146107f257806384ef8ffc146108055780638ba765071461080d5780638da5cb5b14610820575f80fd5b80633ea7ddda116103655780636908d3df116102e45780637638eb42116102a95780637638eb42146107855780637886fe2f146107985780637ca5643d146107b15780637ecebe00146107c45780637f51bb1f146107d7575f80fd5b80636908d3df1461071c5780636f307dc3146107445780636f424d761461074c57806370a082311461075f578063743f9c0c14610772575f80fd5b80635c975abb1161032a5780635c975abb146106c45780635d451d39146106db57806361d027b3146106ee578063634e93da146106f6578063649a5ec714610709575f80fd5b80633ea7ddda146106355780633f4ba83a1461065c5780634f1a43e31461066457806357fc90b2146106775780635c60da1b1461068a575f80fd5b80631e2eaeaf116103f1578063313ce567116103b6578063313ce567146105bb57806336568abe146105d5578063389ed267146105e85780633c04b5471461060f5780633d0f963e14610622575f80fd5b80631e2eaeaf1461054957806323b872dd1461055b578063248a9ca31461056e5780632f2ff15d1461058157806330adf81f14610594575f80fd5b8063095ea7b311610437578063095ea7b3146104f55780630aa6220b146105085780631059c5331461051257806316d8887a1461051a57806318160ddd14610541575f80fd5b806301ffc9a714610473578063022d63fb1461049b578063023da9f9146104b757806306fdde03146104d8578063070a9645146104ed575b5f80fd5b610486610481366004614f01565b610ab3565b60405190151581526020015b60405180910390f35b620697805b60405165ffffffffffff9091168152602001610492565b6104ca6104c5366004614f3c565b610add565b604051908152602001610492565b6104e0610b08565b6040516104929190614f79565b6104ca610ba6565b610486610503366004614fab565b610bd8565b610510610bed565b005b6104ca610c02565b6104ca7f5e17fc5225d4a099df75359ce1f405503ca79498a8dc46a7d583235a0ee45c1681565b6104ca610c34565b6104ca610557366004614fd5565b5490565b610486610569366004614fec565b610c95565b6104ca61057c366004614fd5565b610cf1565b61051061058f36600461502a565b610d11565b6104ca7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c981565b6105c3610d3d565b60405160ff9091168152602001610492565b6105106105e336600461502a565b610d58565b6104ca7f139c2898040ef16910dc9f44dc697df79363da767d8bc92f2e310312b816e46d81565b6104ca61061d36600461506d565b610e1f565b610510610630366004614f3c565b610e8b565b6104ca7fc8e63ee95f263967af737f71b1c5d180e676a7f8b91a501b355a526a9a8fe3eb81565b610510610f2e565b610510610672366004614f3c565b610fbb565b6104ca610685366004615086565b6110ef565b7f00000000000000000000000000000000000000000000000000000000000000005b6040516001600160a01b039091168152602001610492565b5f80516020615bc88339815191525460ff16610486565b6104ca6106e9366004614f3c565b61112e565b6106ac611164565b610510610704366004614f3c565b611181565b6105106107173660046150b0565b611194565b61072f61072a36600461506d565b6111a7565b60408051928352602083019190915201610492565b6106ac6112d9565b6104ca61075a366004615086565b6112f3565b6104ca61076d366004614f3c565b61132f565b6105106107803660046150d5565b61137d565b610510610793366004615086565b611406565b6107a06114ad565b604051610492959493929190615121565b6105106107bf366004615205565b611630565b6104ca6107d2366004614f3c565b6117bb565b6105106107e5366004614f3c565b6117e6565b610510611880565b6105106108003660046150d5565b6118bb565b6106ac611958565b6104ca61081b36600461506d565b611973565b6106ac6119ae565b610510610836366004614f3c565b6119bc565b61051061084936600461525d565b611bc8565b61048661085c36600461502a565b611cff565b61051061086f366004615320565b611d35565b6104e0611e4e565b61051061088a366004615401565b611e6a565b61051061089d366004614f3c565b6120b2565b61072f6108b0366004615086565b612111565b6104866108c3366004615469565b61215b565b6108d06121a1565b6040805165ffffffffffff938416815292909116602083015201610492565b6104ca5f81565b610510610904366004615485565b612210565b6104ca612292565b61051061091f36600461549f565b6122a3565b61093761093236600461506d565b61237f565b604080516001600160681b03909316835265ffffffffffff909116602083015201610492565b61048661096b366004614fab565b6123a0565b61051061097e366004614f3c565b6123e2565b610510610991366004615526565b612440565b6104ca612629565b6105106109ac3660046150d5565b612673565b6104ca61279c565b6104a06127b0565b610510612828565b6109d1612867565b604080516001600160a01b03909316835265ffffffffffff909116602083015201610492565b610510610a053660046155f3565b612894565b610510610a1836600461502a565b612a6e565b610510612a96565b610510610a33366004614fab565b612aa8565b6104ca5f80516020615b4883398151915281565b6104ca610a5a366004615469565b612b81565b610510610a6d366004614fd5565b612bbb565b610510610a80366004615485565b612c15565b6106ac610a93366004614fd5565b612c97565b6104ca612cb0565b610510610aae366004614fab565b612cc4565b5f6001600160e01b031982166318a4c3c360e11b1480610ad75750610ad782612d55565b92915050565b5f80610ae7612d89565b6001600160a01b039093165f90815260069093016020525050604090205490565b60605f610b13612d89565b9050806001018054610b249061565c565b80601f0160208091040260200160405190810160405280929190818152602001828054610b509061565c565b8015610b9b5780601f10610b7257610100808354040283529160200191610b9b565b820191905f5260205f20905b815481529060010190602001808311610b7e57829003601f168201915b505050505091505090565b5f80610bb0612d89565b90505f610bbb6114ad565b505050509050808260050154610bd191906156a8565b9250505090565b5f610be4338484612dad565b50600192915050565b5f610bf781612e72565b610bff612e7c565b50565b5f80610c0c612d89565b60048101549091505f819003610c24575f9250505090565b6005820154610bd1908290612e88565b5f80610c3e612d89565b60048101549091505f819003610c56575f9250505090565b5f80610c606114ad565b5050509150915080610c82838660050154610c7b91906156a8565b8590612e88565b610c8c91906156a8565b94505050505090565b5f610ca1843384612e9f565b610cac848484612f14565b826001600160a01b0316846001600160a01b03165f80516020615b8883398151915284604051610cde91815260200190565b60405180910390a35060015b9392505050565b5f9081525f80516020615ba8833981519152602052604090206001015490565b81610d2f57604051631fe1e13d60e11b815260040160405180910390fd5b610d398282613049565b5050565b5f80610d47612d89565b54600160a01b900460ff1692915050565b5f80516020615b6883398151915282158015610d8c5750610d77611958565b6001600160a01b0316826001600160a01b0316145b15610e10575f80610d9b612867565b90925090506001600160a01b038216151580610dbd575065ffffffffffff8116155b80610dd057504265ffffffffffff821610155b15610dfd576040516319ca5ebb60e01b815265ffffffffffff821660048201526024015b60405180910390fd5b5050805465ffffffffffff60a01b191681555b610e1a8383613065565b505050565b5f80610e29613098565b90505f610e358461237f565b506001600160681b0316905080825f018560ff1681548110610e5957610e596156bb565b5f918252602090912060049091020154610e839190600160681b90046001600160681b03166156a8565b949350505050565b5f80516020615b48833981519152610ea281612e72565b6001600160a01b038216610ec957604051635c4ff00360e11b815260040160405180910390fd5b5f610ed2613098565b600c810180546001600160a01b0319166001600160a01b0386169081179091556040519081529091507f86eba8651458cc924e4911e8a0a31258558de0474fdc43da05cea932cf130aad906020015b60405180910390a1505050565b5f80516020615b48833981519152610f4581612e72565b610f4d6130bc565b5f610f56613098565b80549091505f5b81811015610fb55742835f018281548110610f7a57610f7a6156bb565b5f9182526020909120600490910201805465ffffffffffff92909216600160d01b026001600160d01b03909216919091179055600101610f5d565b50505050565b5f80516020615b48833981519152610fd281612e72565b6001600160a01b0382166110045760405163397b518b60e01b81526001600160a01b0383166004820152602401610df4565b5f61100d613098565b9050805f0180549050836001600160a01b03166348d4b4876040518163ffffffff1660e01b8152600401602060405180830381865afa158015611052573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061107691906156cf565b1461109f5760405163397b518b60e01b81526001600160a01b0384166004820152602401610df4565b600b810180546001600160a01b0319166001600160a01b0385169081179091556040519081527fad74a16b1bf6b1857f574482614816fe1f79ae6b578f5374e9ce760a2ede778690602001610f21565b5f806110f9613098565b60ff85165f9081526003909101602090815260408083206001600160a01b038716845290915290206001015491505092915050565b5f80611138612d89565b60058101546001600160a01b0385165f908152600683016020526040902054919250610cea9190612e88565b5f8061116e612d89565b600301546001600160a01b031692915050565b5f61118b81612e72565b610d398261311b565b5f61119e81612e72565b610d398261318d565b5f805f6111b2613098565b90505f6111bd610c02565b90505f825f018660ff16815481106111d7576111d76156bb565b5f918252602082206004909102015484546001600160681b039091169250849060ff891690811061120a5761120a6156bb565b5f91825260208220600490910201546001600160681b03600160681b90910416915061123682846156e6565b600b86015460405163fe4bab4360e01b815260ff8b16600482015260248101839052604481018790529192506001600160a01b03169063fe4bab43906064016040805180830381865afa15801561128f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112b391906156fd565b90975095506112cd676765c793fa10079d601b1b886156a8565b96505050505050915091565b5f806112e3612d89565b546001600160a01b031692915050565b5f806112fd613098565b60ff85165f9081526003909101602090815260408083206001600160a01b038716845290915290205491505092915050565b5f80611339612d89565b90505f6113446114ad565b505050509050610e8381836005015461135d91906156a8565b6001600160a01b0386165f90815260068501602052604090205490612e88565b6113856131fc565b61138d61322c565b506113ad8484845f61139e866133b6565b6113a79061571f565b5f6133e6565b5050816001600160a01b0316836001600160a01b03168560ff167f4363355d2aba118cce1b43c1cae9804f170e1cb6ede1116d421898bffef033a9846040516113f891815260200190565b60405180910390a450505050565b5f80516020615b4883398151915261141d81612e72565b5f611426613098565b905082815f018560ff1681548110611440576114406156bb565b5f9182526020918290206004919091020160010180546001600160a01b0319166001600160a01b03938416179055604051918516825260ff8616917f19df743a62793f3366940d678082fc6bc7926c06b86cd00dced146172870cbd691015b60405180910390a250505050565b5f8060605f60605f6114bd613098565b80549091508067ffffffffffffffff8111156114db576114db6152db565b604051908082528060200260200182016040528015611504578160200160208202803683370190505b5094508067ffffffffffffffff811115611520576115206152db565b604051908082528060200260200182016040528015611549578160200160208202803683370190505b5092505f611555610c02565b90505f5b828160ff161015611625575f805f805f6115738688613974565b945094509450945094505f8165ffffffffffff16111561161557828c8760ff16815181106115a3576115a36156bb565b60200260200101906001600160681b031690816001600160681b031681525050808a8760ff16815181106115d9576115d96156bb565b65ffffffffffff909216602092830291909101909101526115fa828c6156a8565b9a50611606858f6156a8565b9d50611612848e6156a8565b9c505b8560010195505050505050611559565b505050509091929394565b6116386131fc565b838282808060200260200160405190810160405280939291908181526020018383602002808284375f920182905250925061167591506130989050565b600c810154604051631db4866560e01b81529192506001600160a01b031690631db48665906116ac90339087908790600401615772565b602060405180830381865afa1580156116c7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906116eb919061579d565b505f6116f561322c565b90505f611700613098565b905087816008015f82825461171591906156a8565b909155505f90506117278a338b613c02565b600983015490915080611738610c34565b111561176157604051634f453d2760e11b8152600481018b905260248101829052604401610df4565b604080518b815260208101849052808201869052905133916001600160a01b038e16917feeb36d8164983f8a9f179702390cae566b9dfbea2d9df6344a56dbbccb428cf49181900360600190a35050505050505050505050565b5f806117c5612d89565b6001600160a01b039093165f90815260089093016020525050604090205490565b5f80516020615b488339815191526117fd81612e72565b6001600160a01b0382166118245760405163cfe2ea6360e01b815260040160405180910390fd5b5f61182d612d89565b6003810180546001600160a01b0319166001600160a01b0386169081179091556040519081529091507f8a3509a4057c89a5993a4a3140c2ebf7e829d325d8998eaa6c48adcff98b2cef90602001610f21565b7f139c2898040ef16910dc9f44dc697df79363da767d8bc92f2e310312b816e46d6118aa81612e72565b6118b261322c565b50610bff613c9a565b6118c36131fc565b6118cb61322c565b505f806118ed86865f875f6118df896133b6565b6118e89061571f565b6133e6565b604080518681526001600160681b038416602082015290810182905291935091506001600160a01b03808616919087169060ff8916907f406d000a5cb1dc8c35a7c089a430fac3d79fdbb8b3e37ee6a8707ce9d4ff46e69060600160405180910390a4505050505050565b5f80516020615be8833981519152546001600160a01b031690565b5f8061197d613098565b9050805f018360ff1681548110611996576119966156bb565b905f5260205f20906004020160030154915050919050565b5f6119b7611958565b905090565b5f80516020615b488339815191526119d381612e72565b5f6119dc613098565b90506001600160a01b038316611a0557604051633a49766560e01b815260040160405180910390fd5b611a126001820184613ce2565b611a3a5760405163186b96a960e21b81526001600160a01b0384166004820152602401610df4565b8054611a4860ff60016156a8565b8110611a67576040516361d73a8560e01b815260040160405180910390fd5b6040805160c0810182525f8082526020808301828152938301828152606084018381526080850184815260a08601858152895460018082018c558b8852958720885160049092020180549951955165ffffffffffff16600160d01b026001600160d01b036001600160681b03978816600160681b026001600160d01b0319909c1697909316969096179990991716939093178755905192860180546001600160a01b039094166001600160a01b03199094169390931790925590516002850155516003909301929092558354839290859060ff8516908110611b4b57611b4b6156bb565b5f91825260208220600490910201805465ffffffffffff4216600160d01b026001600160681b0390911617676765c793fa10079d60831b1781556040519092506001600160a01b0389169160ff8616917f15a7f70e00454c5cbf91f222531e25be8763187b123c94b14c64fe949726dc459190a350505050505050565b611bd06131fc565b85858383808060200260200160405190810160405280939291908181526020018383602002808284375f9201829052509250611c0e91506130989050565b600c81015460405163b5406b3d60e01b81529192506001600160a01b03169063b5406b3d90611c479087903390889088906004016157bc565b602060405180830381865afa158015611c62573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c86919061579d565b50611c8f61322c565b50611ca08a8a8a5f6113a78c6133b6565b5050876001600160a01b0316896001600160a01b03168b60ff167fc125b447f095d22865ad610ebdc8ae9eff252e7d7011ca37e783c98a53970bc48a604051611ceb91815260200190565b60405180910390a450505050505050505050565b5f9182525f80516020615ba8833981519152602090815260408084206001600160a01b0393909316845291905290205460ff1690565b611d3d6131fc565b8484825f611d49613098565b600c81015460405163b5406b3d60e01b81529192506001600160a01b03169063b5406b3d90611d829087903390889088906004016157bc565b602060405180830381865afa158015611d9d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611dc1919061579d565b50611dca61322c565b505f80611dde8b8b5f8c5f6118e88e6133b6565b604080518b81526001600160681b038416602082015290810182905291935091506001600160a01b03808b1691908c169060ff8e16907fe3e92e977f830d2a0b92c58e8866694b5dc929a35e2b95846f427de0f0bb412f9060600160405180910390a45050505050505050505050565b60605f611e59612d89565b9050806002018054610b249061565c565b611e726131fc565b7f5e17fc5225d4a099df75359ce1f405503ca79498a8dc46a7d583235a0ee45c16611e9c81612e72565b611ea461322c565b505f611eae613098565b60ff89165f81815260038301602090815260408083206001600160a01b038d1684529091528120835493945092909184918110611eed57611eed6156bb565b5f918252602090912060049091020180548354919250600160681b90046001600160681b031690611f1e9088613cf6565b83556001830154611f2f9087613cf6565b60018401558154611f5290611f4d906001600160681b031688613cf6565b613d51565b82546cffffffffffffffffffffffffff19166001600160681b039182161783555f90611f8190889084166157f0565b60ff8d165f90815260048701602090815260408083206001600160a01b038f168452909152902054909150611fb69089613d84565b856004015f8e60ff1681526020019081526020015f205f8c6001600160a01b03166001600160a01b031681526020019081526020015f2081905550612020856005015f8b6001600160a01b03166001600160a01b031681526020019081526020015f205482613d84565b6001600160a01b038a165f908152600587016020526040902055600a8501546120499082613d84565b85600a0181905550886001600160a01b03168b6001600160a01b03168d60ff167f196d7e6690c90edaf3483b0e23c0043895364c7ff093bb21292343c17020a1088d8c8c60405161209c9392919061581f565b60405180910390a4505050505050505050505050565b5f6120bb613098565b335f81815260068301602090815260408083206001600160a01b03881680855292528083206001905551939450927f51778c51d58ce676f156168a160fc5e14ad3c40027f7d6bf7ce613de46dda9a09190a35050565b5f805f61211c613098565b60ff86165f908152600391909101602090815260408083206001600160a01b0388168452909152902080546001909101549093509150505b9250929050565b5f80612165613098565b6001600160a01b038581165f81815260068401602090815260408083209489168084529490915290205492935014600190911417949350505050565b5f80516020615be8833981519152545f90600160d01b900465ffffffffffff165f80516020615b6883398151915281158015906121e657504265ffffffffffff831610155b6121f1575f80612207565b6001810154600160a01b900465ffffffffffff16825b92509250509091565b5f80516020615b4883398151915261222781612e72565b5f612230613098565b905082815f018560ff168154811061224a5761224a6156bb565b905f5260205f209060040201600201819055508360ff167f8867ae66007046a7ea4546c9cbb61f764adf577521a9831db2d82ec3d60bafbc8460405161149f91815260200190565b5f61229b6131fc565b6119b761322c565b7fc8e63ee95f263967af737f71b1c5d180e676a7f8b91a501b355a526a9a8fe3eb6122cd81612e72565b6122d56131fc565b5f6122de613098565b60ff86165f90815260048201602090815260408083206001600160a01b03891684529091529020549091506123139084613cf6565b60ff86165f81815260048401602090815260408083206001600160a01b038a1680855292529182902093909355517fe728fa61c700a3632cfd3973376b45b5f0bfdb3c2ea1946fd6d4fcda49e1d42f906123709087815260200190565b60405180910390a35050505050565b5f806123928361238d610c02565b613974565b919791965090945050505050565b5f6123ac338484612f14565b6040518281526001600160a01b0384169033905f80516020615b888339815191529060200160405180910390a350600192915050565b5f6123eb613098565b335f81815260068301602090815260408083206001600160a01b038816808552925280832083905551939450927fb157cf3e9ae29eb366b3bdda54b41d4738ada5daa73f8d2f1bef6280bb1418e49190a35050565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff16159067ffffffffffffffff165f811580156124855750825b90505f8267ffffffffffffffff1660011480156124a15750303b155b9050811580156124af575080155b156124cd5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff1916600117855583156124f757845460ff60401b1916600160401b1785555b6125015f89613dde565b61250e8d8d8d8d8d613df0565b6125255f80516020615b4883398151915289613f04565b505f61252f613098565b600b810180546001600160a01b038b81166001600160a01b03199283168117909355600c84018054918c16919092161790556040519081529091507fad74a16b1bf6b1857f574482614816fe1f79ae6b578f5374e9ce760a2ede77869060200160405180910390a16040516001600160a01b03881681527f86eba8651458cc924e4911e8a0a31258558de0474fdc43da05cea932cf130aad9060200160405180910390a150831561261a57845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050505050505050565b5f80612633612d89565b90505f8061263f6114ad565b505050915091505f61266183856005015461265a91906156a8565b8390613f70565b9050808460040154610c8c91906156a8565b61267b6131fc565b612685833361215b565b6126bc57604051631dda4a7d60e01b815260ff851660048201526001600160a01b0384166024820152336044820152606401610df4565b5f6126c5613098565b60ff86165f90815260048201602090815260408083206001600160a01b0389168452909152812080549293508492909190612701908490615840565b909155505060ff85165f90815260048201602090815260408083206001600160a01b03871684529091528120805484929061273d9084906156a8565b92505081905550826001600160a01b0316846001600160a01b03168660ff167fd511a95568d89bafbaf4849c74af18618e15f0c4aaeaa0a5212564935063723f8560405161278d91815260200190565b60405180910390a45050505050565b5f806127a6612d89565b6005015492915050565b5f80516020615be8833981519152545f905f80516020615b6883398151915290600160d01b900465ffffffffffff1680158015906127f557504265ffffffffffff8216105b61280f578154600160d01b900465ffffffffffff16610bd1565b5060010154600160a01b900465ffffffffffff16919050565b5f612831612867565b509050336001600160a01b0382161461285f57604051636116401160e11b8152336004820152602401610df4565b610bff613f87565b5f80516020615b68833981519152546001600160a01b03811691600160a01b90910465ffffffffffff1690565b834211156128b85760405163313c898160e11b815260048101859052602401610df4565b5f7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98888886128e68c614020565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090505f7f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f612960610b08565b805160209182012060408051808201825260018152603160f81b90840152805192830193909352918101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260c0016040516020818303038152906040528051906020012090505f612a00828460405161190160f01b8152600281019290925260228201526042902090565b90505f612a0f82888888614053565b90508a6001600160a01b0316816001600160a01b031614612a56576040516325c0072360e11b81526001600160a01b0380831660048301528c166024820152604401610df4565b612a618b8b8b612dad565b5050505050505050505050565b81612a8c57604051631fe1e13d60e11b815260040160405180910390fd5b610d39828261407f565b5f612aa081612e72565b610bff61409b565b612ab06131fc565b5f612ab9613098565b6001600160a01b0384165f908152600582016020526040812080549293508492909190612ae7908490615840565b925050819055508181600a015f828254612b019190615840565b9250508190555081816007015f828254612b1b9190615840565b90915550612b3c905033612b2e846133b6565b612b379061571f565b6140a5565b60405182815233906001600160a01b038516907f88bdc625ef6cf9ddf1e8078b975bd3079c95fa9c9ea2cfc3312e4ad53acb4a6d9060200160405180910390a3505050565b5f80612b8b612d89565b6001600160a01b039485165f90815260079190910160209081526040808320959096168252939093525050205490565b5f80516020615b48833981519152612bd281612e72565b5f612bdb613098565b600981018490556040518481529091507f4e44c8be34d12f1b7f56b13b4bbe97e64ca37a91916f86c73412da80c21748e290602001610f21565b5f80516020615b48833981519152612c2c81612e72565b5f612c35613098565b905082815f018560ff1681548110612c4f57612c4f6156bb565b905f5260205f209060040201600301819055508360ff167ff91e5e89199cb20fefcea995829cab2d6a5afb4a343b4438335f4e5f69173f098460405161149f91815260200190565b5f80612ca1613098565b9050610cea600182018461419c565b5f80612cba612d89565b6004015492915050565b612ccc6131fc565b5f612cd561322c565b90505f612ce0613098565b905082816008015f828254612cf59190615840565b909155505f9050612d073386866141a7565b60408051868152602081018390529081018590529091506001600160a01b0386169033907febff2602b3f468259e1e99f613fed6691f3a6526effe6ef3e768ba7ae7a36c4f90606001612370565b5f6001600160e01b03198216637965db0b60e01b1480610ad757506301ffc9a760e01b6001600160e01b0319831614610ad7565b7fdb3a0d63a7808d7d0422c40bb62354f42bff7602a547c329c1453dbcbeef490090565b6001600160a01b038316612dd65760405163e602df0560e01b81525f6004820152602401610df4565b6001600160a01b038216612dff57604051634a1406b160e11b81525f6004820152602401610df4565b5f612e08612d89565b6001600160a01b038581165f8181526007840160209081526040808320948916808452948252918290208790559051868152939450919290917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a350505050565b610bff8133614230565b612e865f80614269565b565b5f610cea8383676765c793fa10079d601b1b614341565b5f612eaa8484612b81565b905081811015612ed357828183604051637dc7a0d960e11b8152600401610df49392919061581f565b8181035f612edf612d89565b6001600160a01b039687165f908152600790910160209081526040808320979098168252959095525093909220929092555050565b6001600160a01b038316612f3d57604051634b637e8f60e11b81525f6004820152602401610df4565b6001600160a01b038216612f665760405163ec442f0560e01b81525f6004820152602401610df4565b816001600160a01b0316836001600160a01b031603612fa35760405163514ae31560e01b81526001600160a01b0384166004820152602401610df4565b5f612fac612d89565b60058101549091505f612fbf8483613f70565b6001600160a01b0387165f908152600685016020526040902054909150818110156130035786818360405163391434e360e21b8152600401610df49392919061581f565b6001600160a01b038088165f90815260068601602052604080822085850390559188168152908120805484929061303b9084906156a8565b909155505050505050505050565b61305282610cf1565b61305b81612e72565b610fb58383613f04565b6001600160a01b038116331461308e5760405163334bd91960e11b815260040160405180910390fd5b610e1a8282614400565b7fceba3d526b4d5afd91d1b752bf1fd37917c20a6daf576bcb41dd1c57c1f67e0090565b6130c4614457565b5f80516020615bc8833981519152805460ff191681557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a150565b5f6131246127b0565b61312d42614486565b6131379190615853565b905061314382826144b8565b60405165ffffffffffff821681526001600160a01b038316907f3377dc44241e779dd06afab5b788a35ca5f3b778836e2990bdb26a2a4b2e5ed69060200160405180910390a25050565b5f61319782614542565b6131a042614486565b6131aa9190615853565b90506131b68282614269565b6040805165ffffffffffff8085168252831660208201527ff1038c18cf84a56e432fdbfaf746924b7ea511dfe03a6506a0ceba4888788d9b910160405180910390a15050565b5f80516020615bc88339815191525460ff1615612e865760405163d93c066560e01b815260040160405180910390fd5b5f80613236613098565b90505f613241610c02565b82549091505f9081908190815b818160ff16101561336f575f805f805f613268868c613974565b945094509450945094505f8165ffffffffffff16111561335f575f8c5f018760ff168154811061329a5761329a6156bb565b905f5260205f209060040201905083815f01600d8282829054906101000a90046001600160681b03166132cd9190615872565b92506101000a8154816001600160681b0302191690836001600160681b0316021790555081815f01601a8282829054906101000a900465ffffffffffff166133159190615853565b92506101000a81548165ffffffffffff021916908365ffffffffffff160217905550828961334391906156a8565b985061334f868c6156a8565b9a5061335b858b6156a8565b9950505b856001019550505050505061324e565b5081866007015461338091906156a8565b6007870181905596506133a48461339561279c565b61339f91906156a8565b614589565b6133ad8361459c565b50505050505090565b5f6001600160ff1b038211156133e25760405163123baf0360e11b815260048101839052602401610df4565b5090565b5f805f6133f1613098565b9050805f018960ff168154811061340a5761340a6156bb565b5f91825260208220600490910201546001600160681b03600160681b90910416935083900361345157604051637a42d32b60e11b815260ff8a166004820152602401610df4565b60ff89165f90815260038201602090815260408083206001600160a01b038c168452825291829020825180840190935280548084526001909101549183019190915261349d9087613cf6565b815260208101516134ae9086613cf6565b602082015281545f906134f390611f4d90859060ff8f169081106134d4576134d46156bb565b5f9182526020909120600490910201546001600160681b031688613cf6565b90505f8260200151866001600160681b031661350f91906156e6565b90506135615f8813855f018e60ff168154811061352e5761352e6156bb565b905f5260205f20906004020160020154886001600160681b0316856001600160681b031661355c91906156e6565b111690565b156135c75761357c6001600160681b038088169084166156e6565b845f018d60ff1681548110613593576135936156bb565b905f5260205f20906004020160020154604051631604695560e31b8152600401610df4929190918252602082015260400190565b5f845f018d60ff16815481106135df576135df6156bb565b905f5260205f2090600402016001015f9054906101000a90046001600160a01b03166001600160a01b0316632b37269c6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561363c573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061366091906156cf565b90506136856136725f8a135f8c121790565b855161367f9084906156e6565b84111690565b156136b7578351604051631e09d3a360e31b815260048101849052602481019190915260448101829052606401610df4565b6136d66136c75f8a135f8c121790565b6136d18e3361215b565b151690565b1561370e576040516315df6de160e31b815260ff8e1660048201526001600160a01b038d166024820152336044820152606401610df4565b61371e5f8a136136d18d3361215b565b156137565760405163f7c30b4560e01b815260ff8e1660048201526001600160a01b038c166024820152336044820152606401610df4565b6137665f89126136d18c3361215b565b156137955760405163e236d98560e01b81526001600160a01b038b166004820152336024820152604401610df4565b6137cd84602001515f1415865f018f60ff16815481106137b7576137b76156bb565b905f5260205f2090600402016003015484101690565b1561381e5781855f018e60ff16815481106137ea576137ea6156bb565b905f5260205f2090600402016003015460405163e6fe673d60e01b8152600401610df4929190918252602082015260400190565b50505f86613834876001600160681b03166133b6565b61383e91906157f0565b60ff8d165f90815260048601602090815260408083206001600160a01b038f1684529091529020549091506138739089613d84565b846004015f8e60ff1681526020019081526020015f205f8c6001600160a01b03166001600160a01b031681526020019081526020015f208190555082846003015f8e60ff1681526020019081526020015f205f8d6001600160a01b03166001600160a01b031681526020019081526020015f205f820151815f01556020820151816001015590505081845f018d60ff1681548110613913576139136156bb565b905f5260205f2090600402015f015f6101000a8154816001600160681b0302191690836001600160681b03160217905550613952846007015482613cf6565b60078501819055945061396589826140a5565b50505050965096945050505050565b5f805f805f80613982613098565b90505f815f018960ff168154811061399c5761399c6156bb565b5f918252602090912060049091020180549091506001600160681b03168015806139d557508154600160d01b900465ffffffffffff1642145b806139ee57505f80516020615bc88339815191525460ff165b15613a285781545f90819081908190613a1690600160d01b900465ffffffffffff1642615840565b97509750975097509750505050613bf8565b81545f90613a4690600160681b90046001600160681b0316836156e6565b600b85015460405163fe4bab4360e01b815260ff8e16600482015260248101839052604481018d90529192505f9182916001600160a01b03169063fe4bab43906064016040805180830381865afa158015613aa3573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ac791906156fd565b86549193509150613ae790600160d01b900465ffffffffffff1642615892565b9650815f03613b07575f805f809a509a509a509a50505050505050613bf8565b5f613b3a613b20676765c793fa10079d601b1b856156a8565b8965ffffffffffff16676765c793fa10079d601b1b614647565b9050613b6f611f4d613b57676765c793fa10079d601b1b84615840565b8854600160681b90046001600160681b0316906146ff565b9950613b846001600160681b038b16866156e6565b98505f613b8f612cb0565b90508015613bc757613bc2613baf84676765c793fa10079d601b1b615840565b613bba836012614718565b8c9190614341565b613bc9565b5f5b9c50613bed8a84760a70c3c40a64e6c51999090b65f67d9240000000000000614341565b9b5050505050505050505b9295509295909350565b5f80613c0c612d89565b60058101549091505f613c1f8583613f70565b9050805f03613c415760405163199f5a0360e31b815260040160405180910390fd5b613c4b8782614725565b8254613c62906001600160a01b03168730886147a4565b6040518581526001600160a01b038816905f905f80516020615b88833981519152906020015b60405180910390a35095945050505050565b613ca26131fc565b5f80516020615bc8833981519152805460ff191660011781557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258336130fd565b5f610cea836001600160a01b03841661480b565b8181015f82128015613d0757508281115b15613d2557604051630fc12e3560e11b815260040160405180910390fd5b5f82138015613d3357508281105b15610ad757604051630fc12e3560e11b815260040160405180910390fd5b5f6001600160681b038211156133e2576040516306dfcc6560e41b81526068600482015260248101839052604401610df4565b8082035f82138015613d9557508281115b15613db357604051630fc12e3560e11b815260040160405180910390fd5b5f82128015613d33575082811015610ad757604051630fc12e3560e11b815260040160405180910390fd5b613de6614857565b610d3982826148a0565b613df8614857565b6001600160a01b038516613e1f5760405163e9a1cca560e01b815260040160405180910390fd5b6001600160a01b038416613e465760405163cfe2ea6360e01b815260040160405180910390fd5b5f613e4f612d89565b80546003820180546001600160a01b0319166001600160a01b038981169190911790915588166001600160a81b031990911617600160a01b60ff871602178155905060018101613e9f84826158fe565b5060028101613eae83826158fe565b50676765c793fa10079d601b1b60058201556040516001600160a01b03861681527f8a3509a4057c89a5993a4a3140c2ebf7e829d325d8998eaa6c48adcff98b2cef9060200160405180910390a1505050505050565b5f5f80516020615b6883398151915283613f66575f613f21611958565b6001600160a01b031614613f4857604051631fe1e13d60e11b815260040160405180910390fd5b6001810180546001600160a01b0319166001600160a01b0385161790555b610e838484614906565b5f610cea83676765c793fa10079d601b1b84614341565b5f80516020615b688339815191525f80613f9f612867565b91509150613fb48165ffffffffffff16151590565b1580613fc857504265ffffffffffff821610155b15613ff0576040516319ca5ebb60e01b815265ffffffffffff82166004820152602401610df4565b6140015f613ffc611958565b614400565b5061400c5f83613f04565b505081546001600160d01b03191690915550565b5f8061402a612d89565b6001600160a01b039093165f908152600890930160205250506040902080546001810190915590565b5f805f80614063888888886149ae565b9250925092506140738282614a76565b50909695505050505050565b61408882610cf1565b61409181612e72565b610fb58383614400565b612e865f806144b8565b805f036140b0575050565b5f6140b9613098565b90505f82121561414e575f6140cd8361571f565b90505f6140e5676765c793fa10079d601b1b836159ce565b90505f6140fd676765c793fa10079d601b1b846159e1565b111561410f5761410c816159f4565b90505b80836008015f82825461412291906156a8565b9091555061414790508530836141366112d9565b6001600160a01b03169291906147a4565b5050505050565b5f614164676765c793fa10079d601b1b846159ce565b905080826008015f8282546141799190615840565b90915550610fb59050848261418c6112d9565b6001600160a01b03169190614b2e565b5f610cea8383614b5f565b5f806141b1612d89565b60058101549091505f6141c48583614b85565b9050805f036141e6576040516302075cc160e41b815260040160405180910390fd5b6141f08782614b9e565b8254614206906001600160a01b03168787614b2e565b6040518581525f906001600160a01b038916905f80516020615b8883398151915290602001613c88565b61423a8282611cff565b610d395760405163e2517d3f60e01b81526001600160a01b038216600482015260248101839052604401610df4565b5f80516020615be8833981519152545f80516020615b6883398151915290600160d01b900465ffffffffffff168015614303574265ffffffffffff821610156142da57600182015482546001600160d01b0316600160a01b90910465ffffffffffff16600160d01b02178255614303565b6040517f2b1fa2edafe6f7b9e97c1a9e0c3660e645beb2dcaa2d45bdbf9beaf5472e1ec5905f90a15b5060010180546001600160a01b0316600160a01b65ffffffffffff948516026001600160d01b031617600160d01b9290931691909102919091179055565b5f838302815f1985870982811083820303915050805f036143755783828161436b5761436b6159ba565b0492505050610cea565b8084116143955760405163227bc15360e01b815260040160405180910390fd5b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f5f80516020615b68833981519152831580156144355750614420611958565b6001600160a01b0316836001600160a01b0316145b1561444d576001810180546001600160a01b03191690555b610e838484614c50565b5f80516020615bc88339815191525460ff16612e8657604051638dfc202b60e01b815260040160405180910390fd5b5f65ffffffffffff8211156133e2576040516306dfcc6560e41b81526030600482015260248101839052604401610df4565b5f80516020615b688339815191525f6144cf612867565b835465ffffffffffff8616600160a01b026001600160d01b03199091166001600160a01b03881617178455915061450f90508165ffffffffffff16151590565b15610fb5576040517f8886ebfc4259abdbc16601dd8fb5678e54878f47b3c34836cfc51154a9605109905f90a150505050565b5f8061454c6127b0565b90508065ffffffffffff168365ffffffffffff16116145745761456f8382615892565b610cea565b610cea65ffffffffffff841662069780614cc9565b5f614592612d89565b6005019190915550565b805f036145a65750565b5f6145af612d89565b60058101546003820154919250906001600160a01b03166145d9816145d48685613f70565b614725565b6040518481526001600160a01b038216905f905f80516020615b888339815191529060200160405180910390a360408051858152602081018490526001600160a01b038316917f095a1e7fd552d6bba4d4bcc1c4127215dafdd5a52103be432762e64f2e13250a910161149f565b5f8380156146e25760018416801561466157859250614665565b8392505b50600283046002850494505b84156146dc578586028687820414614687575f80fd5b81810181811015614696575f80fd5b85900496505060018516156146d15785830283878204141587151516156146bb575f80fd5b818101818110156146ca575f80fd5b8590049350505b600285049450614671565b506146f7565b8380156146f1575f92506146f5565b8392505b505b509392505050565b5f610cea8383676765c793fa10079d601b1b6001614cde565b5f610cea8383602d614d2d565b6001600160a01b03821661474e57604051639cfea58360e01b81525f6004820152602401610df4565b5f614757612d89565b905081816004015f82825461476c91906156a8565b90915550506001600160a01b0383165f9081526006820160205260408120805484929061479a9084906156a8565b9091555050505050565b6040516001600160a01b038481166024830152838116604483015260648201839052610fb59186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050614d77565b5f81815260018301602052604081205461485057508154600181810184555f848152602080822090930184905584548482528286019093526040902091909155610ad7565b505f610ad7565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff16612e8657604051631afcd79f60e31b815260040160405180910390fd5b6148a8614857565b5f80516020615b688339815191526001600160a01b0382166148df57604051636116401160e11b81525f6004820152602401610df4565b80546001600160d01b0316600160d01b65ffffffffffff851602178155610fb55f83613f04565b5f5f80516020615ba883398151915261491f8484611cff565b61499e575f848152602082815260408083206001600160a01b03871684529091529020805460ff191660011790556149543390565b6001600160a01b0316836001600160a01b0316857f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a46001915050610ad7565b5f915050610ad7565b5092915050565b5f80807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411156149e757505f91506003905082614a6c565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa158015614a38573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b038116614a6357505f925060019150829050614a6c565b92505f91508190505b9450945094915050565b5f826003811115614a8957614a89615a0c565b03614a92575050565b6001826003811115614aa657614aa6615a0c565b03614ac45760405163f645eedf60e01b815260040160405180910390fd5b6002826003811115614ad857614ad8615a0c565b03614af95760405163fce698f760e01b815260048101829052602401610df4565b6003826003811115614b0d57614b0d615a0c565b03610d39576040516335e2f38360e21b815260048101829052602401610df4565b6040516001600160a01b03838116602483015260448201839052610e1a91859182169063a9059cbb906064016147d9565b5f825f018281548110614b7457614b746156bb565b905f5260205f200154905092915050565b5f610cea83676765c793fa10079d601b1b846001614cde565b5f614ba7612d89565b90506001600160a01b038316614bd2576040516313053d9360e21b81525f6004820152602401610df4565b6001600160a01b0383165f90815260068201602052604090205482811015614c135783818460405163db42144d60e01b8152600401610df49392919061581f565b6001600160a01b0384165f90815260068301602052604081208483039055600483018054859290614c45908490615840565b909155505050505050565b5f5f80516020615ba8833981519152614c698484611cff565b1561499e575f848152602082815260408083206001600160a01b0387168085529252808320805460ff1916905551339287917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a46001915050610ad7565b5f818310614cd75781610cea565b5090919050565b5f80614ceb868686614341565b9050614cf683614dd8565b8015614d1157505f8480614d0c57614d0c6159ba565b868809115b15614d2457614d216001826156a8565b90505b95945050505050565b5f818310614d5857604051631a065cf160e01b81526004810184905260248101839052604401610df4565b614d628383615840565b614d6d90600a615b00565b610e8390856156e6565b5f614d8b6001600160a01b03841683614e04565b905080515f14158015614daf575080806020019051810190614dad919061579d565b155b15610e1a57604051635274afe760e01b81526001600160a01b0384166004820152602401610df4565b5f6002826003811115614ded57614ded615a0c565b614df79190615b0b565b60ff166001149050919050565b6060610cea83835f845f80856001600160a01b03168486604051614e289190615b2c565b5f6040518083038185875af1925050503d805f8114614e62576040519150601f19603f3d011682016040523d82523d5f602084013e614e67565b606091505b5091509150614e77868383614e81565b9695505050505050565b606082614e915761456f82614ed8565b8151158015614ea857506001600160a01b0384163b155b15614ed157604051639996b31560e01b81526001600160a01b0385166004820152602401610df4565b5080610cea565b805115614ee85780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b5f60208284031215614f11575f80fd5b81356001600160e01b031981168114610cea575f80fd5b6001600160a01b0381168114610bff575f80fd5b5f60208284031215614f4c575f80fd5b8135610cea81614f28565b5f5b83811015614f71578181015183820152602001614f59565b50505f910152565b602081525f8251806020840152614f97816040850160208701614f57565b601f01601f19169190910160400192915050565b5f8060408385031215614fbc575f80fd5b8235614fc781614f28565b946020939093013593505050565b5f60208284031215614fe5575f80fd5b5035919050565b5f805f60608486031215614ffe575f80fd5b833561500981614f28565b9250602084013561501981614f28565b929592945050506040919091013590565b5f806040838503121561503b575f80fd5b82359150602083013561504d81614f28565b809150509250929050565b803560ff81168114615068575f80fd5b919050565b5f6020828403121561507d575f80fd5b610cea82615058565b5f8060408385031215615097575f80fd5b6150a083615058565b9150602083013561504d81614f28565b5f602082840312156150c0575f80fd5b813565ffffffffffff81168114610cea575f80fd5b5f805f80608085870312156150e8575f80fd5b6150f185615058565b9350602085013561510181614f28565b9250604085013561511181614f28565b9396929550929360600135925050565b5f60a082018783526020878185015260a0604085015281875180845260c08601915082890193505f5b8181101561516f5784516001600160681b03168352938301939183019160010161514a565b505060608501879052848103608086015285518082529082019250818601905f5b818110156151b457825165ffffffffffff1685529383019391830191600101615190565b50929a9950505050505050505050565b5f8083601f8401126151d4575f80fd5b50813567ffffffffffffffff8111156151eb575f80fd5b6020830191508360208260051b8501011115612154575f80fd5b5f805f8060608587031215615218575f80fd5b843561522381614f28565b935060208501359250604085013567ffffffffffffffff811115615245575f80fd5b615251878288016151c4565b95989497509550505050565b5f805f805f8060a08789031215615272575f80fd5b61527b87615058565b9550602087013561528b81614f28565b9450604087013561529b81614f28565b935060608701359250608087013567ffffffffffffffff8111156152bd575f80fd5b6152c989828a016151c4565b979a9699509497509295939492505050565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff81118282101715615318576153186152db565b604052919050565b5f805f805f60a08688031215615334575f80fd5b61533d86615058565b945060208087013561534e81614f28565b9450604087013561535e81614f28565b935060608701359250608087013567ffffffffffffffff80821115615381575f80fd5b818901915089601f830112615394575f80fd5b8135818111156153a6576153a66152db565b8060051b91506153b78483016152ef565b818152918301840191848101908c8411156153d0575f80fd5b938501935b838510156153ee578435825293850193908501906153d5565b8096505050505050509295509295909350565b5f805f805f8060c08789031215615416575f80fd5b61541f87615058565b9550602087013561542f81614f28565b9450604087013561543f81614f28565b9350606087013561544f81614f28565b9598949750929560808101359460a0909101359350915050565b5f806040838503121561547a575f80fd5b82356150a081614f28565b5f8060408385031215615496575f80fd5b614fc783615058565b5f805f606084860312156154b1575f80fd5b61500984615058565b5f82601f8301126154c9575f80fd5b813567ffffffffffffffff8111156154e3576154e36152db565b6154f6601f8201601f19166020016152ef565b81815284602083860101111561550a575f80fd5b816020850160208301375f918101602001919091529392505050565b5f805f805f805f80610100898b03121561553e575f80fd5b883561554981614f28565b9750602089013561555981614f28565b965061556760408a01615058565b9550606089013567ffffffffffffffff80821115615583575f80fd5b61558f8c838d016154ba565b965060808b01359150808211156155a4575f80fd5b506155b18b828c016154ba565b94505060a08901356155c281614f28565b925060c08901356155d281614f28565b915060e08901356155e281614f28565b809150509295985092959890939650565b5f805f805f805f60e0888a031215615609575f80fd5b873561561481614f28565b9650602088013561562481614f28565b9550604088013594506060880135935061564060808901615058565b925060a0880135915060c0880135905092959891949750929550565b600181811c9082168061567057607f821691505b60208210810361568e57634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52601160045260245ffd5b80820180821115610ad757610ad7615694565b634e487b7160e01b5f52603260045260245ffd5b5f602082840312156156df575f80fd5b5051919050565b8082028115828204841417610ad757610ad7615694565b5f806040838503121561570e575f80fd5b505080516020909101519092909150565b5f600160ff1b820161573357615733615694565b505f0390565b5f8151808452602080850194508084015f5b838110156157675781518752958201959082019060010161574b565b509495945050505050565b6001600160a01b038481168252831660208201526060604082018190525f90614d2490830184615739565b5f602082840312156157ad575f80fd5b81518015158114610cea575f80fd5b60ff851681526001600160a01b038481166020830152831660408201526080606082018190525f90614e7790830184615739565b8082025f8212600160ff1b8414161561580b5761580b615694565b8181058314821517610ad757610ad7615694565b6001600160a01b039390931683526020830191909152604082015260600190565b81810381811115610ad757610ad7615694565b65ffffffffffff8181168382160190808211156149a7576149a7615694565b6001600160681b038181168382160190808211156149a7576149a7615694565b65ffffffffffff8281168282160390808211156149a7576149a7615694565b601f821115610e1a575f81815260208120601f850160051c810160208610156158d75750805b601f850160051c820191505b818110156158f6578281556001016158e3565b505050505050565b815167ffffffffffffffff811115615918576159186152db565b61592c81615926845461565c565b846158b1565b602080601f83116001811461595f575f84156159485750858301515b5f19600386901b1c1916600185901b1785556158f6565b5f85815260208120601f198616915b8281101561598d5788860151825594840194600190910190840161596e565b50858210156159aa57878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b634e487b7160e01b5f52601260045260245ffd5b5f826159dc576159dc6159ba565b500490565b5f826159ef576159ef6159ba565b500690565b5f60018201615a0557615a05615694565b5060010190565b634e487b7160e01b5f52602160045260245ffd5b600181815b80851115615a5a57815f1904821115615a4057615a40615694565b80851615615a4d57918102915b93841c9390800290615a25565b509250929050565b5f82615a7057506001610ad7565b81615a7c57505f610ad7565b8160018114615a925760028114615a9c57615ab8565b6001915050610ad7565b60ff841115615aad57615aad615694565b50506001821b610ad7565b5060208310610133831016604e8410600b8410161715615adb575081810a610ad7565b615ae58383615a20565b805f1904821115615af857615af8615694565b029392505050565b5f610cea8383615a62565b5f60ff831680615b1d57615b1d6159ba565b8060ff84160691505092915050565b5f8251615b3d818460208701614f57565b919091019291505056fe5ab1a5ffb29c47d95dec8c5f9ad49a551754822b51a3359ed1c21e2be24beefaeef3dac4538c82c8ace4063ab0acd2d15cdb5883aa1dff7c2673abb3d8698400ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800cd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300eef3dac4538c82c8ace4063ab0acd2d15cdb5883aa1dff7c2673abb3d8698401a264697066735822122015e733dc03be8e0e48b181c40c5cbbdd7355a98c3b19dcf74958e9219194d7d664736f6c63430008150033

Deployed Bytecode

0x608060405234801561000f575f80fd5b506004361061046f575f3560e01c80638456cb591161024d578063a9059cbb11610140578063d547741f116100bf578063e5a97f0711610084578063e5a97f0714610a5f578063e862114a14610a72578063efff005f14610a85578063f09b808d14610a98578063f3fef3a314610aa0575f80fd5b8063d547741f14610a0a578063d602b9fd14610a1d578063d831efd814610a25578063dcec05bf14610a38578063dd62ed3e14610a4c575f80fd5b8063c358b49a11610105578063c358b49a146109b1578063cc8463c8146109b9578063cefc1429146109c1578063cf6eefb7146109c9578063d505accf146109f7575f80fd5b8063a9059cbb1461095d578063ac8a584a14610970578063b827735f14610983578063b85e868e14610996578063c0cc5edf1461099e575f80fd5b806397939743116101cc578063a217fddf11610191578063a217fddf146108ef578063a36f653d146108f6578063a6afed9514610909578063a716272814610911578063a778d7b314610924575f80fd5b8063979397431461087c5780639870d7fe1461088f5780639a3db79b146108a2578063a1654379146108b5578063a1eda53c146108c8575f80fd5b80638fb5400e116102125780638fb5400e14610828578063918a2f421461083b57806391d148541461084e5780639306f2f81461086157806395d89b4114610874575f80fd5b80638456cb59146107ea5780638459b437146107f257806384ef8ffc146108055780638ba765071461080d5780638da5cb5b14610820575f80fd5b80633ea7ddda116103655780636908d3df116102e45780637638eb42116102a95780637638eb42146107855780637886fe2f146107985780637ca5643d146107b15780637ecebe00146107c45780637f51bb1f146107d7575f80fd5b80636908d3df1461071c5780636f307dc3146107445780636f424d761461074c57806370a082311461075f578063743f9c0c14610772575f80fd5b80635c975abb1161032a5780635c975abb146106c45780635d451d39146106db57806361d027b3146106ee578063634e93da146106f6578063649a5ec714610709575f80fd5b80633ea7ddda146106355780633f4ba83a1461065c5780634f1a43e31461066457806357fc90b2146106775780635c60da1b1461068a575f80fd5b80631e2eaeaf116103f1578063313ce567116103b6578063313ce567146105bb57806336568abe146105d5578063389ed267146105e85780633c04b5471461060f5780633d0f963e14610622575f80fd5b80631e2eaeaf1461054957806323b872dd1461055b578063248a9ca31461056e5780632f2ff15d1461058157806330adf81f14610594575f80fd5b8063095ea7b311610437578063095ea7b3146104f55780630aa6220b146105085780631059c5331461051257806316d8887a1461051a57806318160ddd14610541575f80fd5b806301ffc9a714610473578063022d63fb1461049b578063023da9f9146104b757806306fdde03146104d8578063070a9645146104ed575b5f80fd5b610486610481366004614f01565b610ab3565b60405190151581526020015b60405180910390f35b620697805b60405165ffffffffffff9091168152602001610492565b6104ca6104c5366004614f3c565b610add565b604051908152602001610492565b6104e0610b08565b6040516104929190614f79565b6104ca610ba6565b610486610503366004614fab565b610bd8565b610510610bed565b005b6104ca610c02565b6104ca7f5e17fc5225d4a099df75359ce1f405503ca79498a8dc46a7d583235a0ee45c1681565b6104ca610c34565b6104ca610557366004614fd5565b5490565b610486610569366004614fec565b610c95565b6104ca61057c366004614fd5565b610cf1565b61051061058f36600461502a565b610d11565b6104ca7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c981565b6105c3610d3d565b60405160ff9091168152602001610492565b6105106105e336600461502a565b610d58565b6104ca7f139c2898040ef16910dc9f44dc697df79363da767d8bc92f2e310312b816e46d81565b6104ca61061d36600461506d565b610e1f565b610510610630366004614f3c565b610e8b565b6104ca7fc8e63ee95f263967af737f71b1c5d180e676a7f8b91a501b355a526a9a8fe3eb81565b610510610f2e565b610510610672366004614f3c565b610fbb565b6104ca610685366004615086565b6110ef565b7f00000000000000000000000077ca0d4b78d8b4f3c71e20f8c8771c4cb7abe2015b6040516001600160a01b039091168152602001610492565b5f80516020615bc88339815191525460ff16610486565b6104ca6106e9366004614f3c565b61112e565b6106ac611164565b610510610704366004614f3c565b611181565b6105106107173660046150b0565b611194565b61072f61072a36600461506d565b6111a7565b60408051928352602083019190915201610492565b6106ac6112d9565b6104ca61075a366004615086565b6112f3565b6104ca61076d366004614f3c565b61132f565b6105106107803660046150d5565b61137d565b610510610793366004615086565b611406565b6107a06114ad565b604051610492959493929190615121565b6105106107bf366004615205565b611630565b6104ca6107d2366004614f3c565b6117bb565b6105106107e5366004614f3c565b6117e6565b610510611880565b6105106108003660046150d5565b6118bb565b6106ac611958565b6104ca61081b36600461506d565b611973565b6106ac6119ae565b610510610836366004614f3c565b6119bc565b61051061084936600461525d565b611bc8565b61048661085c36600461502a565b611cff565b61051061086f366004615320565b611d35565b6104e0611e4e565b61051061088a366004615401565b611e6a565b61051061089d366004614f3c565b6120b2565b61072f6108b0366004615086565b612111565b6104866108c3366004615469565b61215b565b6108d06121a1565b6040805165ffffffffffff938416815292909116602083015201610492565b6104ca5f81565b610510610904366004615485565b612210565b6104ca612292565b61051061091f36600461549f565b6122a3565b61093761093236600461506d565b61237f565b604080516001600160681b03909316835265ffffffffffff909116602083015201610492565b61048661096b366004614fab565b6123a0565b61051061097e366004614f3c565b6123e2565b610510610991366004615526565b612440565b6104ca612629565b6105106109ac3660046150d5565b612673565b6104ca61279c565b6104a06127b0565b610510612828565b6109d1612867565b604080516001600160a01b03909316835265ffffffffffff909116602083015201610492565b610510610a053660046155f3565b612894565b610510610a1836600461502a565b612a6e565b610510612a96565b610510610a33366004614fab565b612aa8565b6104ca5f80516020615b4883398151915281565b6104ca610a5a366004615469565b612b81565b610510610a6d366004614fd5565b612bbb565b610510610a80366004615485565b612c15565b6106ac610a93366004614fd5565b612c97565b6104ca612cb0565b610510610aae366004614fab565b612cc4565b5f6001600160e01b031982166318a4c3c360e11b1480610ad75750610ad782612d55565b92915050565b5f80610ae7612d89565b6001600160a01b039093165f90815260069093016020525050604090205490565b60605f610b13612d89565b9050806001018054610b249061565c565b80601f0160208091040260200160405190810160405280929190818152602001828054610b509061565c565b8015610b9b5780601f10610b7257610100808354040283529160200191610b9b565b820191905f5260205f20905b815481529060010190602001808311610b7e57829003601f168201915b505050505091505090565b5f80610bb0612d89565b90505f610bbb6114ad565b505050509050808260050154610bd191906156a8565b9250505090565b5f610be4338484612dad565b50600192915050565b5f610bf781612e72565b610bff612e7c565b50565b5f80610c0c612d89565b60048101549091505f819003610c24575f9250505090565b6005820154610bd1908290612e88565b5f80610c3e612d89565b60048101549091505f819003610c56575f9250505090565b5f80610c606114ad565b5050509150915080610c82838660050154610c7b91906156a8565b8590612e88565b610c8c91906156a8565b94505050505090565b5f610ca1843384612e9f565b610cac848484612f14565b826001600160a01b0316846001600160a01b03165f80516020615b8883398151915284604051610cde91815260200190565b60405180910390a35060015b9392505050565b5f9081525f80516020615ba8833981519152602052604090206001015490565b81610d2f57604051631fe1e13d60e11b815260040160405180910390fd5b610d398282613049565b5050565b5f80610d47612d89565b54600160a01b900460ff1692915050565b5f80516020615b6883398151915282158015610d8c5750610d77611958565b6001600160a01b0316826001600160a01b0316145b15610e10575f80610d9b612867565b90925090506001600160a01b038216151580610dbd575065ffffffffffff8116155b80610dd057504265ffffffffffff821610155b15610dfd576040516319ca5ebb60e01b815265ffffffffffff821660048201526024015b60405180910390fd5b5050805465ffffffffffff60a01b191681555b610e1a8383613065565b505050565b5f80610e29613098565b90505f610e358461237f565b506001600160681b0316905080825f018560ff1681548110610e5957610e596156bb565b5f918252602090912060049091020154610e839190600160681b90046001600160681b03166156a8565b949350505050565b5f80516020615b48833981519152610ea281612e72565b6001600160a01b038216610ec957604051635c4ff00360e11b815260040160405180910390fd5b5f610ed2613098565b600c810180546001600160a01b0319166001600160a01b0386169081179091556040519081529091507f86eba8651458cc924e4911e8a0a31258558de0474fdc43da05cea932cf130aad906020015b60405180910390a1505050565b5f80516020615b48833981519152610f4581612e72565b610f4d6130bc565b5f610f56613098565b80549091505f5b81811015610fb55742835f018281548110610f7a57610f7a6156bb565b5f9182526020909120600490910201805465ffffffffffff92909216600160d01b026001600160d01b03909216919091179055600101610f5d565b50505050565b5f80516020615b48833981519152610fd281612e72565b6001600160a01b0382166110045760405163397b518b60e01b81526001600160a01b0383166004820152602401610df4565b5f61100d613098565b9050805f0180549050836001600160a01b03166348d4b4876040518163ffffffff1660e01b8152600401602060405180830381865afa158015611052573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061107691906156cf565b1461109f5760405163397b518b60e01b81526001600160a01b0384166004820152602401610df4565b600b810180546001600160a01b0319166001600160a01b0385169081179091556040519081527fad74a16b1bf6b1857f574482614816fe1f79ae6b578f5374e9ce760a2ede778690602001610f21565b5f806110f9613098565b60ff85165f9081526003909101602090815260408083206001600160a01b038716845290915290206001015491505092915050565b5f80611138612d89565b60058101546001600160a01b0385165f908152600683016020526040902054919250610cea9190612e88565b5f8061116e612d89565b600301546001600160a01b031692915050565b5f61118b81612e72565b610d398261311b565b5f61119e81612e72565b610d398261318d565b5f805f6111b2613098565b90505f6111bd610c02565b90505f825f018660ff16815481106111d7576111d76156bb565b5f918252602082206004909102015484546001600160681b039091169250849060ff891690811061120a5761120a6156bb565b5f91825260208220600490910201546001600160681b03600160681b90910416915061123682846156e6565b600b86015460405163fe4bab4360e01b815260ff8b16600482015260248101839052604481018790529192506001600160a01b03169063fe4bab43906064016040805180830381865afa15801561128f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112b391906156fd565b90975095506112cd676765c793fa10079d601b1b886156a8565b96505050505050915091565b5f806112e3612d89565b546001600160a01b031692915050565b5f806112fd613098565b60ff85165f9081526003909101602090815260408083206001600160a01b038716845290915290205491505092915050565b5f80611339612d89565b90505f6113446114ad565b505050509050610e8381836005015461135d91906156a8565b6001600160a01b0386165f90815260068501602052604090205490612e88565b6113856131fc565b61138d61322c565b506113ad8484845f61139e866133b6565b6113a79061571f565b5f6133e6565b5050816001600160a01b0316836001600160a01b03168560ff167f4363355d2aba118cce1b43c1cae9804f170e1cb6ede1116d421898bffef033a9846040516113f891815260200190565b60405180910390a450505050565b5f80516020615b4883398151915261141d81612e72565b5f611426613098565b905082815f018560ff1681548110611440576114406156bb565b5f9182526020918290206004919091020160010180546001600160a01b0319166001600160a01b03938416179055604051918516825260ff8616917f19df743a62793f3366940d678082fc6bc7926c06b86cd00dced146172870cbd691015b60405180910390a250505050565b5f8060605f60605f6114bd613098565b80549091508067ffffffffffffffff8111156114db576114db6152db565b604051908082528060200260200182016040528015611504578160200160208202803683370190505b5094508067ffffffffffffffff811115611520576115206152db565b604051908082528060200260200182016040528015611549578160200160208202803683370190505b5092505f611555610c02565b90505f5b828160ff161015611625575f805f805f6115738688613974565b945094509450945094505f8165ffffffffffff16111561161557828c8760ff16815181106115a3576115a36156bb565b60200260200101906001600160681b031690816001600160681b031681525050808a8760ff16815181106115d9576115d96156bb565b65ffffffffffff909216602092830291909101909101526115fa828c6156a8565b9a50611606858f6156a8565b9d50611612848e6156a8565b9c505b8560010195505050505050611559565b505050509091929394565b6116386131fc565b838282808060200260200160405190810160405280939291908181526020018383602002808284375f920182905250925061167591506130989050565b600c810154604051631db4866560e01b81529192506001600160a01b031690631db48665906116ac90339087908790600401615772565b602060405180830381865afa1580156116c7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906116eb919061579d565b505f6116f561322c565b90505f611700613098565b905087816008015f82825461171591906156a8565b909155505f90506117278a338b613c02565b600983015490915080611738610c34565b111561176157604051634f453d2760e11b8152600481018b905260248101829052604401610df4565b604080518b815260208101849052808201869052905133916001600160a01b038e16917feeb36d8164983f8a9f179702390cae566b9dfbea2d9df6344a56dbbccb428cf49181900360600190a35050505050505050505050565b5f806117c5612d89565b6001600160a01b039093165f90815260089093016020525050604090205490565b5f80516020615b488339815191526117fd81612e72565b6001600160a01b0382166118245760405163cfe2ea6360e01b815260040160405180910390fd5b5f61182d612d89565b6003810180546001600160a01b0319166001600160a01b0386169081179091556040519081529091507f8a3509a4057c89a5993a4a3140c2ebf7e829d325d8998eaa6c48adcff98b2cef90602001610f21565b7f139c2898040ef16910dc9f44dc697df79363da767d8bc92f2e310312b816e46d6118aa81612e72565b6118b261322c565b50610bff613c9a565b6118c36131fc565b6118cb61322c565b505f806118ed86865f875f6118df896133b6565b6118e89061571f565b6133e6565b604080518681526001600160681b038416602082015290810182905291935091506001600160a01b03808616919087169060ff8916907f406d000a5cb1dc8c35a7c089a430fac3d79fdbb8b3e37ee6a8707ce9d4ff46e69060600160405180910390a4505050505050565b5f80516020615be8833981519152546001600160a01b031690565b5f8061197d613098565b9050805f018360ff1681548110611996576119966156bb565b905f5260205f20906004020160030154915050919050565b5f6119b7611958565b905090565b5f80516020615b488339815191526119d381612e72565b5f6119dc613098565b90506001600160a01b038316611a0557604051633a49766560e01b815260040160405180910390fd5b611a126001820184613ce2565b611a3a5760405163186b96a960e21b81526001600160a01b0384166004820152602401610df4565b8054611a4860ff60016156a8565b8110611a67576040516361d73a8560e01b815260040160405180910390fd5b6040805160c0810182525f8082526020808301828152938301828152606084018381526080850184815260a08601858152895460018082018c558b8852958720885160049092020180549951955165ffffffffffff16600160d01b026001600160d01b036001600160681b03978816600160681b026001600160d01b0319909c1697909316969096179990991716939093178755905192860180546001600160a01b039094166001600160a01b03199094169390931790925590516002850155516003909301929092558354839290859060ff8516908110611b4b57611b4b6156bb565b5f91825260208220600490910201805465ffffffffffff4216600160d01b026001600160681b0390911617676765c793fa10079d60831b1781556040519092506001600160a01b0389169160ff8616917f15a7f70e00454c5cbf91f222531e25be8763187b123c94b14c64fe949726dc459190a350505050505050565b611bd06131fc565b85858383808060200260200160405190810160405280939291908181526020018383602002808284375f9201829052509250611c0e91506130989050565b600c81015460405163b5406b3d60e01b81529192506001600160a01b03169063b5406b3d90611c479087903390889088906004016157bc565b602060405180830381865afa158015611c62573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c86919061579d565b50611c8f61322c565b50611ca08a8a8a5f6113a78c6133b6565b5050876001600160a01b0316896001600160a01b03168b60ff167fc125b447f095d22865ad610ebdc8ae9eff252e7d7011ca37e783c98a53970bc48a604051611ceb91815260200190565b60405180910390a450505050505050505050565b5f9182525f80516020615ba8833981519152602090815260408084206001600160a01b0393909316845291905290205460ff1690565b611d3d6131fc565b8484825f611d49613098565b600c81015460405163b5406b3d60e01b81529192506001600160a01b03169063b5406b3d90611d829087903390889088906004016157bc565b602060405180830381865afa158015611d9d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611dc1919061579d565b50611dca61322c565b505f80611dde8b8b5f8c5f6118e88e6133b6565b604080518b81526001600160681b038416602082015290810182905291935091506001600160a01b03808b1691908c169060ff8e16907fe3e92e977f830d2a0b92c58e8866694b5dc929a35e2b95846f427de0f0bb412f9060600160405180910390a45050505050505050505050565b60605f611e59612d89565b9050806002018054610b249061565c565b611e726131fc565b7f5e17fc5225d4a099df75359ce1f405503ca79498a8dc46a7d583235a0ee45c16611e9c81612e72565b611ea461322c565b505f611eae613098565b60ff89165f81815260038301602090815260408083206001600160a01b038d1684529091528120835493945092909184918110611eed57611eed6156bb565b5f918252602090912060049091020180548354919250600160681b90046001600160681b031690611f1e9088613cf6565b83556001830154611f2f9087613cf6565b60018401558154611f5290611f4d906001600160681b031688613cf6565b613d51565b82546cffffffffffffffffffffffffff19166001600160681b039182161783555f90611f8190889084166157f0565b60ff8d165f90815260048701602090815260408083206001600160a01b038f168452909152902054909150611fb69089613d84565b856004015f8e60ff1681526020019081526020015f205f8c6001600160a01b03166001600160a01b031681526020019081526020015f2081905550612020856005015f8b6001600160a01b03166001600160a01b031681526020019081526020015f205482613d84565b6001600160a01b038a165f908152600587016020526040902055600a8501546120499082613d84565b85600a0181905550886001600160a01b03168b6001600160a01b03168d60ff167f196d7e6690c90edaf3483b0e23c0043895364c7ff093bb21292343c17020a1088d8c8c60405161209c9392919061581f565b60405180910390a4505050505050505050505050565b5f6120bb613098565b335f81815260068301602090815260408083206001600160a01b03881680855292528083206001905551939450927f51778c51d58ce676f156168a160fc5e14ad3c40027f7d6bf7ce613de46dda9a09190a35050565b5f805f61211c613098565b60ff86165f908152600391909101602090815260408083206001600160a01b0388168452909152902080546001909101549093509150505b9250929050565b5f80612165613098565b6001600160a01b038581165f81815260068401602090815260408083209489168084529490915290205492935014600190911417949350505050565b5f80516020615be8833981519152545f90600160d01b900465ffffffffffff165f80516020615b6883398151915281158015906121e657504265ffffffffffff831610155b6121f1575f80612207565b6001810154600160a01b900465ffffffffffff16825b92509250509091565b5f80516020615b4883398151915261222781612e72565b5f612230613098565b905082815f018560ff168154811061224a5761224a6156bb565b905f5260205f209060040201600201819055508360ff167f8867ae66007046a7ea4546c9cbb61f764adf577521a9831db2d82ec3d60bafbc8460405161149f91815260200190565b5f61229b6131fc565b6119b761322c565b7fc8e63ee95f263967af737f71b1c5d180e676a7f8b91a501b355a526a9a8fe3eb6122cd81612e72565b6122d56131fc565b5f6122de613098565b60ff86165f90815260048201602090815260408083206001600160a01b03891684529091529020549091506123139084613cf6565b60ff86165f81815260048401602090815260408083206001600160a01b038a1680855292529182902093909355517fe728fa61c700a3632cfd3973376b45b5f0bfdb3c2ea1946fd6d4fcda49e1d42f906123709087815260200190565b60405180910390a35050505050565b5f806123928361238d610c02565b613974565b919791965090945050505050565b5f6123ac338484612f14565b6040518281526001600160a01b0384169033905f80516020615b888339815191529060200160405180910390a350600192915050565b5f6123eb613098565b335f81815260068301602090815260408083206001600160a01b038816808552925280832083905551939450927fb157cf3e9ae29eb366b3bdda54b41d4738ada5daa73f8d2f1bef6280bb1418e49190a35050565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff16159067ffffffffffffffff165f811580156124855750825b90505f8267ffffffffffffffff1660011480156124a15750303b155b9050811580156124af575080155b156124cd5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff1916600117855583156124f757845460ff60401b1916600160401b1785555b6125015f89613dde565b61250e8d8d8d8d8d613df0565b6125255f80516020615b4883398151915289613f04565b505f61252f613098565b600b810180546001600160a01b038b81166001600160a01b03199283168117909355600c84018054918c16919092161790556040519081529091507fad74a16b1bf6b1857f574482614816fe1f79ae6b578f5374e9ce760a2ede77869060200160405180910390a16040516001600160a01b03881681527f86eba8651458cc924e4911e8a0a31258558de0474fdc43da05cea932cf130aad9060200160405180910390a150831561261a57845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050505050505050565b5f80612633612d89565b90505f8061263f6114ad565b505050915091505f61266183856005015461265a91906156a8565b8390613f70565b9050808460040154610c8c91906156a8565b61267b6131fc565b612685833361215b565b6126bc57604051631dda4a7d60e01b815260ff851660048201526001600160a01b0384166024820152336044820152606401610df4565b5f6126c5613098565b60ff86165f90815260048201602090815260408083206001600160a01b0389168452909152812080549293508492909190612701908490615840565b909155505060ff85165f90815260048201602090815260408083206001600160a01b03871684529091528120805484929061273d9084906156a8565b92505081905550826001600160a01b0316846001600160a01b03168660ff167fd511a95568d89bafbaf4849c74af18618e15f0c4aaeaa0a5212564935063723f8560405161278d91815260200190565b60405180910390a45050505050565b5f806127a6612d89565b6005015492915050565b5f80516020615be8833981519152545f905f80516020615b6883398151915290600160d01b900465ffffffffffff1680158015906127f557504265ffffffffffff8216105b61280f578154600160d01b900465ffffffffffff16610bd1565b5060010154600160a01b900465ffffffffffff16919050565b5f612831612867565b509050336001600160a01b0382161461285f57604051636116401160e11b8152336004820152602401610df4565b610bff613f87565b5f80516020615b68833981519152546001600160a01b03811691600160a01b90910465ffffffffffff1690565b834211156128b85760405163313c898160e11b815260048101859052602401610df4565b5f7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98888886128e68c614020565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090505f7f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f612960610b08565b805160209182012060408051808201825260018152603160f81b90840152805192830193909352918101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260c0016040516020818303038152906040528051906020012090505f612a00828460405161190160f01b8152600281019290925260228201526042902090565b90505f612a0f82888888614053565b90508a6001600160a01b0316816001600160a01b031614612a56576040516325c0072360e11b81526001600160a01b0380831660048301528c166024820152604401610df4565b612a618b8b8b612dad565b5050505050505050505050565b81612a8c57604051631fe1e13d60e11b815260040160405180910390fd5b610d39828261407f565b5f612aa081612e72565b610bff61409b565b612ab06131fc565b5f612ab9613098565b6001600160a01b0384165f908152600582016020526040812080549293508492909190612ae7908490615840565b925050819055508181600a015f828254612b019190615840565b9250508190555081816007015f828254612b1b9190615840565b90915550612b3c905033612b2e846133b6565b612b379061571f565b6140a5565b60405182815233906001600160a01b038516907f88bdc625ef6cf9ddf1e8078b975bd3079c95fa9c9ea2cfc3312e4ad53acb4a6d9060200160405180910390a3505050565b5f80612b8b612d89565b6001600160a01b039485165f90815260079190910160209081526040808320959096168252939093525050205490565b5f80516020615b48833981519152612bd281612e72565b5f612bdb613098565b600981018490556040518481529091507f4e44c8be34d12f1b7f56b13b4bbe97e64ca37a91916f86c73412da80c21748e290602001610f21565b5f80516020615b48833981519152612c2c81612e72565b5f612c35613098565b905082815f018560ff1681548110612c4f57612c4f6156bb565b905f5260205f209060040201600301819055508360ff167ff91e5e89199cb20fefcea995829cab2d6a5afb4a343b4438335f4e5f69173f098460405161149f91815260200190565b5f80612ca1613098565b9050610cea600182018461419c565b5f80612cba612d89565b6004015492915050565b612ccc6131fc565b5f612cd561322c565b90505f612ce0613098565b905082816008015f828254612cf59190615840565b909155505f9050612d073386866141a7565b60408051868152602081018390529081018590529091506001600160a01b0386169033907febff2602b3f468259e1e99f613fed6691f3a6526effe6ef3e768ba7ae7a36c4f90606001612370565b5f6001600160e01b03198216637965db0b60e01b1480610ad757506301ffc9a760e01b6001600160e01b0319831614610ad7565b7fdb3a0d63a7808d7d0422c40bb62354f42bff7602a547c329c1453dbcbeef490090565b6001600160a01b038316612dd65760405163e602df0560e01b81525f6004820152602401610df4565b6001600160a01b038216612dff57604051634a1406b160e11b81525f6004820152602401610df4565b5f612e08612d89565b6001600160a01b038581165f8181526007840160209081526040808320948916808452948252918290208790559051868152939450919290917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a350505050565b610bff8133614230565b612e865f80614269565b565b5f610cea8383676765c793fa10079d601b1b614341565b5f612eaa8484612b81565b905081811015612ed357828183604051637dc7a0d960e11b8152600401610df49392919061581f565b8181035f612edf612d89565b6001600160a01b039687165f908152600790910160209081526040808320979098168252959095525093909220929092555050565b6001600160a01b038316612f3d57604051634b637e8f60e11b81525f6004820152602401610df4565b6001600160a01b038216612f665760405163ec442f0560e01b81525f6004820152602401610df4565b816001600160a01b0316836001600160a01b031603612fa35760405163514ae31560e01b81526001600160a01b0384166004820152602401610df4565b5f612fac612d89565b60058101549091505f612fbf8483613f70565b6001600160a01b0387165f908152600685016020526040902054909150818110156130035786818360405163391434e360e21b8152600401610df49392919061581f565b6001600160a01b038088165f90815260068601602052604080822085850390559188168152908120805484929061303b9084906156a8565b909155505050505050505050565b61305282610cf1565b61305b81612e72565b610fb58383613f04565b6001600160a01b038116331461308e5760405163334bd91960e11b815260040160405180910390fd5b610e1a8282614400565b7fceba3d526b4d5afd91d1b752bf1fd37917c20a6daf576bcb41dd1c57c1f67e0090565b6130c4614457565b5f80516020615bc8833981519152805460ff191681557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a150565b5f6131246127b0565b61312d42614486565b6131379190615853565b905061314382826144b8565b60405165ffffffffffff821681526001600160a01b038316907f3377dc44241e779dd06afab5b788a35ca5f3b778836e2990bdb26a2a4b2e5ed69060200160405180910390a25050565b5f61319782614542565b6131a042614486565b6131aa9190615853565b90506131b68282614269565b6040805165ffffffffffff8085168252831660208201527ff1038c18cf84a56e432fdbfaf746924b7ea511dfe03a6506a0ceba4888788d9b910160405180910390a15050565b5f80516020615bc88339815191525460ff1615612e865760405163d93c066560e01b815260040160405180910390fd5b5f80613236613098565b90505f613241610c02565b82549091505f9081908190815b818160ff16101561336f575f805f805f613268868c613974565b945094509450945094505f8165ffffffffffff16111561335f575f8c5f018760ff168154811061329a5761329a6156bb565b905f5260205f209060040201905083815f01600d8282829054906101000a90046001600160681b03166132cd9190615872565b92506101000a8154816001600160681b0302191690836001600160681b0316021790555081815f01601a8282829054906101000a900465ffffffffffff166133159190615853565b92506101000a81548165ffffffffffff021916908365ffffffffffff160217905550828961334391906156a8565b985061334f868c6156a8565b9a5061335b858b6156a8565b9950505b856001019550505050505061324e565b5081866007015461338091906156a8565b6007870181905596506133a48461339561279c565b61339f91906156a8565b614589565b6133ad8361459c565b50505050505090565b5f6001600160ff1b038211156133e25760405163123baf0360e11b815260048101839052602401610df4565b5090565b5f805f6133f1613098565b9050805f018960ff168154811061340a5761340a6156bb565b5f91825260208220600490910201546001600160681b03600160681b90910416935083900361345157604051637a42d32b60e11b815260ff8a166004820152602401610df4565b60ff89165f90815260038201602090815260408083206001600160a01b038c168452825291829020825180840190935280548084526001909101549183019190915261349d9087613cf6565b815260208101516134ae9086613cf6565b602082015281545f906134f390611f4d90859060ff8f169081106134d4576134d46156bb565b5f9182526020909120600490910201546001600160681b031688613cf6565b90505f8260200151866001600160681b031661350f91906156e6565b90506135615f8813855f018e60ff168154811061352e5761352e6156bb565b905f5260205f20906004020160020154886001600160681b0316856001600160681b031661355c91906156e6565b111690565b156135c75761357c6001600160681b038088169084166156e6565b845f018d60ff1681548110613593576135936156bb565b905f5260205f20906004020160020154604051631604695560e31b8152600401610df4929190918252602082015260400190565b5f845f018d60ff16815481106135df576135df6156bb565b905f5260205f2090600402016001015f9054906101000a90046001600160a01b03166001600160a01b0316632b37269c6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561363c573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061366091906156cf565b90506136856136725f8a135f8c121790565b855161367f9084906156e6565b84111690565b156136b7578351604051631e09d3a360e31b815260048101849052602481019190915260448101829052606401610df4565b6136d66136c75f8a135f8c121790565b6136d18e3361215b565b151690565b1561370e576040516315df6de160e31b815260ff8e1660048201526001600160a01b038d166024820152336044820152606401610df4565b61371e5f8a136136d18d3361215b565b156137565760405163f7c30b4560e01b815260ff8e1660048201526001600160a01b038c166024820152336044820152606401610df4565b6137665f89126136d18c3361215b565b156137955760405163e236d98560e01b81526001600160a01b038b166004820152336024820152604401610df4565b6137cd84602001515f1415865f018f60ff16815481106137b7576137b76156bb565b905f5260205f2090600402016003015484101690565b1561381e5781855f018e60ff16815481106137ea576137ea6156bb565b905f5260205f2090600402016003015460405163e6fe673d60e01b8152600401610df4929190918252602082015260400190565b50505f86613834876001600160681b03166133b6565b61383e91906157f0565b60ff8d165f90815260048601602090815260408083206001600160a01b038f1684529091529020549091506138739089613d84565b846004015f8e60ff1681526020019081526020015f205f8c6001600160a01b03166001600160a01b031681526020019081526020015f208190555082846003015f8e60ff1681526020019081526020015f205f8d6001600160a01b03166001600160a01b031681526020019081526020015f205f820151815f01556020820151816001015590505081845f018d60ff1681548110613913576139136156bb565b905f5260205f2090600402015f015f6101000a8154816001600160681b0302191690836001600160681b03160217905550613952846007015482613cf6565b60078501819055945061396589826140a5565b50505050965096945050505050565b5f805f805f80613982613098565b90505f815f018960ff168154811061399c5761399c6156bb565b5f918252602090912060049091020180549091506001600160681b03168015806139d557508154600160d01b900465ffffffffffff1642145b806139ee57505f80516020615bc88339815191525460ff165b15613a285781545f90819081908190613a1690600160d01b900465ffffffffffff1642615840565b97509750975097509750505050613bf8565b81545f90613a4690600160681b90046001600160681b0316836156e6565b600b85015460405163fe4bab4360e01b815260ff8e16600482015260248101839052604481018d90529192505f9182916001600160a01b03169063fe4bab43906064016040805180830381865afa158015613aa3573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ac791906156fd565b86549193509150613ae790600160d01b900465ffffffffffff1642615892565b9650815f03613b07575f805f809a509a509a509a50505050505050613bf8565b5f613b3a613b20676765c793fa10079d601b1b856156a8565b8965ffffffffffff16676765c793fa10079d601b1b614647565b9050613b6f611f4d613b57676765c793fa10079d601b1b84615840565b8854600160681b90046001600160681b0316906146ff565b9950613b846001600160681b038b16866156e6565b98505f613b8f612cb0565b90508015613bc757613bc2613baf84676765c793fa10079d601b1b615840565b613bba836012614718565b8c9190614341565b613bc9565b5f5b9c50613bed8a84760a70c3c40a64e6c51999090b65f67d9240000000000000614341565b9b5050505050505050505b9295509295909350565b5f80613c0c612d89565b60058101549091505f613c1f8583613f70565b9050805f03613c415760405163199f5a0360e31b815260040160405180910390fd5b613c4b8782614725565b8254613c62906001600160a01b03168730886147a4565b6040518581526001600160a01b038816905f905f80516020615b88833981519152906020015b60405180910390a35095945050505050565b613ca26131fc565b5f80516020615bc8833981519152805460ff191660011781557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258336130fd565b5f610cea836001600160a01b03841661480b565b8181015f82128015613d0757508281115b15613d2557604051630fc12e3560e11b815260040160405180910390fd5b5f82138015613d3357508281105b15610ad757604051630fc12e3560e11b815260040160405180910390fd5b5f6001600160681b038211156133e2576040516306dfcc6560e41b81526068600482015260248101839052604401610df4565b8082035f82138015613d9557508281115b15613db357604051630fc12e3560e11b815260040160405180910390fd5b5f82128015613d33575082811015610ad757604051630fc12e3560e11b815260040160405180910390fd5b613de6614857565b610d3982826148a0565b613df8614857565b6001600160a01b038516613e1f5760405163e9a1cca560e01b815260040160405180910390fd5b6001600160a01b038416613e465760405163cfe2ea6360e01b815260040160405180910390fd5b5f613e4f612d89565b80546003820180546001600160a01b0319166001600160a01b038981169190911790915588166001600160a81b031990911617600160a01b60ff871602178155905060018101613e9f84826158fe565b5060028101613eae83826158fe565b50676765c793fa10079d601b1b60058201556040516001600160a01b03861681527f8a3509a4057c89a5993a4a3140c2ebf7e829d325d8998eaa6c48adcff98b2cef9060200160405180910390a1505050505050565b5f5f80516020615b6883398151915283613f66575f613f21611958565b6001600160a01b031614613f4857604051631fe1e13d60e11b815260040160405180910390fd5b6001810180546001600160a01b0319166001600160a01b0385161790555b610e838484614906565b5f610cea83676765c793fa10079d601b1b84614341565b5f80516020615b688339815191525f80613f9f612867565b91509150613fb48165ffffffffffff16151590565b1580613fc857504265ffffffffffff821610155b15613ff0576040516319ca5ebb60e01b815265ffffffffffff82166004820152602401610df4565b6140015f613ffc611958565b614400565b5061400c5f83613f04565b505081546001600160d01b03191690915550565b5f8061402a612d89565b6001600160a01b039093165f908152600890930160205250506040902080546001810190915590565b5f805f80614063888888886149ae565b9250925092506140738282614a76565b50909695505050505050565b61408882610cf1565b61409181612e72565b610fb58383614400565b612e865f806144b8565b805f036140b0575050565b5f6140b9613098565b90505f82121561414e575f6140cd8361571f565b90505f6140e5676765c793fa10079d601b1b836159ce565b90505f6140fd676765c793fa10079d601b1b846159e1565b111561410f5761410c816159f4565b90505b80836008015f82825461412291906156a8565b9091555061414790508530836141366112d9565b6001600160a01b03169291906147a4565b5050505050565b5f614164676765c793fa10079d601b1b846159ce565b905080826008015f8282546141799190615840565b90915550610fb59050848261418c6112d9565b6001600160a01b03169190614b2e565b5f610cea8383614b5f565b5f806141b1612d89565b60058101549091505f6141c48583614b85565b9050805f036141e6576040516302075cc160e41b815260040160405180910390fd5b6141f08782614b9e565b8254614206906001600160a01b03168787614b2e565b6040518581525f906001600160a01b038916905f80516020615b8883398151915290602001613c88565b61423a8282611cff565b610d395760405163e2517d3f60e01b81526001600160a01b038216600482015260248101839052604401610df4565b5f80516020615be8833981519152545f80516020615b6883398151915290600160d01b900465ffffffffffff168015614303574265ffffffffffff821610156142da57600182015482546001600160d01b0316600160a01b90910465ffffffffffff16600160d01b02178255614303565b6040517f2b1fa2edafe6f7b9e97c1a9e0c3660e645beb2dcaa2d45bdbf9beaf5472e1ec5905f90a15b5060010180546001600160a01b0316600160a01b65ffffffffffff948516026001600160d01b031617600160d01b9290931691909102919091179055565b5f838302815f1985870982811083820303915050805f036143755783828161436b5761436b6159ba565b0492505050610cea565b8084116143955760405163227bc15360e01b815260040160405180910390fd5b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f5f80516020615b68833981519152831580156144355750614420611958565b6001600160a01b0316836001600160a01b0316145b1561444d576001810180546001600160a01b03191690555b610e838484614c50565b5f80516020615bc88339815191525460ff16612e8657604051638dfc202b60e01b815260040160405180910390fd5b5f65ffffffffffff8211156133e2576040516306dfcc6560e41b81526030600482015260248101839052604401610df4565b5f80516020615b688339815191525f6144cf612867565b835465ffffffffffff8616600160a01b026001600160d01b03199091166001600160a01b03881617178455915061450f90508165ffffffffffff16151590565b15610fb5576040517f8886ebfc4259abdbc16601dd8fb5678e54878f47b3c34836cfc51154a9605109905f90a150505050565b5f8061454c6127b0565b90508065ffffffffffff168365ffffffffffff16116145745761456f8382615892565b610cea565b610cea65ffffffffffff841662069780614cc9565b5f614592612d89565b6005019190915550565b805f036145a65750565b5f6145af612d89565b60058101546003820154919250906001600160a01b03166145d9816145d48685613f70565b614725565b6040518481526001600160a01b038216905f905f80516020615b888339815191529060200160405180910390a360408051858152602081018490526001600160a01b038316917f095a1e7fd552d6bba4d4bcc1c4127215dafdd5a52103be432762e64f2e13250a910161149f565b5f8380156146e25760018416801561466157859250614665565b8392505b50600283046002850494505b84156146dc578586028687820414614687575f80fd5b81810181811015614696575f80fd5b85900496505060018516156146d15785830283878204141587151516156146bb575f80fd5b818101818110156146ca575f80fd5b8590049350505b600285049450614671565b506146f7565b8380156146f1575f92506146f5565b8392505b505b509392505050565b5f610cea8383676765c793fa10079d601b1b6001614cde565b5f610cea8383602d614d2d565b6001600160a01b03821661474e57604051639cfea58360e01b81525f6004820152602401610df4565b5f614757612d89565b905081816004015f82825461476c91906156a8565b90915550506001600160a01b0383165f9081526006820160205260408120805484929061479a9084906156a8565b9091555050505050565b6040516001600160a01b038481166024830152838116604483015260648201839052610fb59186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050614d77565b5f81815260018301602052604081205461485057508154600181810184555f848152602080822090930184905584548482528286019093526040902091909155610ad7565b505f610ad7565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff16612e8657604051631afcd79f60e31b815260040160405180910390fd5b6148a8614857565b5f80516020615b688339815191526001600160a01b0382166148df57604051636116401160e11b81525f6004820152602401610df4565b80546001600160d01b0316600160d01b65ffffffffffff851602178155610fb55f83613f04565b5f5f80516020615ba883398151915261491f8484611cff565b61499e575f848152602082815260408083206001600160a01b03871684529091529020805460ff191660011790556149543390565b6001600160a01b0316836001600160a01b0316857f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a46001915050610ad7565b5f915050610ad7565b5092915050565b5f80807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411156149e757505f91506003905082614a6c565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa158015614a38573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b038116614a6357505f925060019150829050614a6c565b92505f91508190505b9450945094915050565b5f826003811115614a8957614a89615a0c565b03614a92575050565b6001826003811115614aa657614aa6615a0c565b03614ac45760405163f645eedf60e01b815260040160405180910390fd5b6002826003811115614ad857614ad8615a0c565b03614af95760405163fce698f760e01b815260048101829052602401610df4565b6003826003811115614b0d57614b0d615a0c565b03610d39576040516335e2f38360e21b815260048101829052602401610df4565b6040516001600160a01b03838116602483015260448201839052610e1a91859182169063a9059cbb906064016147d9565b5f825f018281548110614b7457614b746156bb565b905f5260205f200154905092915050565b5f610cea83676765c793fa10079d601b1b846001614cde565b5f614ba7612d89565b90506001600160a01b038316614bd2576040516313053d9360e21b81525f6004820152602401610df4565b6001600160a01b0383165f90815260068201602052604090205482811015614c135783818460405163db42144d60e01b8152600401610df49392919061581f565b6001600160a01b0384165f90815260068301602052604081208483039055600483018054859290614c45908490615840565b909155505050505050565b5f5f80516020615ba8833981519152614c698484611cff565b1561499e575f848152602082815260408083206001600160a01b0387168085529252808320805460ff1916905551339287917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a46001915050610ad7565b5f818310614cd75781610cea565b5090919050565b5f80614ceb868686614341565b9050614cf683614dd8565b8015614d1157505f8480614d0c57614d0c6159ba565b868809115b15614d2457614d216001826156a8565b90505b95945050505050565b5f818310614d5857604051631a065cf160e01b81526004810184905260248101839052604401610df4565b614d628383615840565b614d6d90600a615b00565b610e8390856156e6565b5f614d8b6001600160a01b03841683614e04565b905080515f14158015614daf575080806020019051810190614dad919061579d565b155b15610e1a57604051635274afe760e01b81526001600160a01b0384166004820152602401610df4565b5f6002826003811115614ded57614ded615a0c565b614df79190615b0b565b60ff166001149050919050565b6060610cea83835f845f80856001600160a01b03168486604051614e289190615b2c565b5f6040518083038185875af1925050503d805f8114614e62576040519150601f19603f3d011682016040523d82523d5f602084013e614e67565b606091505b5091509150614e77868383614e81565b9695505050505050565b606082614e915761456f82614ed8565b8151158015614ea857506001600160a01b0384163b155b15614ed157604051639996b31560e01b81526001600160a01b0385166004820152602401610df4565b5080610cea565b805115614ee85780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b5f60208284031215614f11575f80fd5b81356001600160e01b031981168114610cea575f80fd5b6001600160a01b0381168114610bff575f80fd5b5f60208284031215614f4c575f80fd5b8135610cea81614f28565b5f5b83811015614f71578181015183820152602001614f59565b50505f910152565b602081525f8251806020840152614f97816040850160208701614f57565b601f01601f19169190910160400192915050565b5f8060408385031215614fbc575f80fd5b8235614fc781614f28565b946020939093013593505050565b5f60208284031215614fe5575f80fd5b5035919050565b5f805f60608486031215614ffe575f80fd5b833561500981614f28565b9250602084013561501981614f28565b929592945050506040919091013590565b5f806040838503121561503b575f80fd5b82359150602083013561504d81614f28565b809150509250929050565b803560ff81168114615068575f80fd5b919050565b5f6020828403121561507d575f80fd5b610cea82615058565b5f8060408385031215615097575f80fd5b6150a083615058565b9150602083013561504d81614f28565b5f602082840312156150c0575f80fd5b813565ffffffffffff81168114610cea575f80fd5b5f805f80608085870312156150e8575f80fd5b6150f185615058565b9350602085013561510181614f28565b9250604085013561511181614f28565b9396929550929360600135925050565b5f60a082018783526020878185015260a0604085015281875180845260c08601915082890193505f5b8181101561516f5784516001600160681b03168352938301939183019160010161514a565b505060608501879052848103608086015285518082529082019250818601905f5b818110156151b457825165ffffffffffff1685529383019391830191600101615190565b50929a9950505050505050505050565b5f8083601f8401126151d4575f80fd5b50813567ffffffffffffffff8111156151eb575f80fd5b6020830191508360208260051b8501011115612154575f80fd5b5f805f8060608587031215615218575f80fd5b843561522381614f28565b935060208501359250604085013567ffffffffffffffff811115615245575f80fd5b615251878288016151c4565b95989497509550505050565b5f805f805f8060a08789031215615272575f80fd5b61527b87615058565b9550602087013561528b81614f28565b9450604087013561529b81614f28565b935060608701359250608087013567ffffffffffffffff8111156152bd575f80fd5b6152c989828a016151c4565b979a9699509497509295939492505050565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff81118282101715615318576153186152db565b604052919050565b5f805f805f60a08688031215615334575f80fd5b61533d86615058565b945060208087013561534e81614f28565b9450604087013561535e81614f28565b935060608701359250608087013567ffffffffffffffff80821115615381575f80fd5b818901915089601f830112615394575f80fd5b8135818111156153a6576153a66152db565b8060051b91506153b78483016152ef565b818152918301840191848101908c8411156153d0575f80fd5b938501935b838510156153ee578435825293850193908501906153d5565b8096505050505050509295509295909350565b5f805f805f8060c08789031215615416575f80fd5b61541f87615058565b9550602087013561542f81614f28565b9450604087013561543f81614f28565b9350606087013561544f81614f28565b9598949750929560808101359460a0909101359350915050565b5f806040838503121561547a575f80fd5b82356150a081614f28565b5f8060408385031215615496575f80fd5b614fc783615058565b5f805f606084860312156154b1575f80fd5b61500984615058565b5f82601f8301126154c9575f80fd5b813567ffffffffffffffff8111156154e3576154e36152db565b6154f6601f8201601f19166020016152ef565b81815284602083860101111561550a575f80fd5b816020850160208301375f918101602001919091529392505050565b5f805f805f805f80610100898b03121561553e575f80fd5b883561554981614f28565b9750602089013561555981614f28565b965061556760408a01615058565b9550606089013567ffffffffffffffff80821115615583575f80fd5b61558f8c838d016154ba565b965060808b01359150808211156155a4575f80fd5b506155b18b828c016154ba565b94505060a08901356155c281614f28565b925060c08901356155d281614f28565b915060e08901356155e281614f28565b809150509295985092959890939650565b5f805f805f805f60e0888a031215615609575f80fd5b873561561481614f28565b9650602088013561562481614f28565b9550604088013594506060880135935061564060808901615058565b925060a0880135915060c0880135905092959891949750929550565b600181811c9082168061567057607f821691505b60208210810361568e57634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52601160045260245ffd5b80820180821115610ad757610ad7615694565b634e487b7160e01b5f52603260045260245ffd5b5f602082840312156156df575f80fd5b5051919050565b8082028115828204841417610ad757610ad7615694565b5f806040838503121561570e575f80fd5b505080516020909101519092909150565b5f600160ff1b820161573357615733615694565b505f0390565b5f8151808452602080850194508084015f5b838110156157675781518752958201959082019060010161574b565b509495945050505050565b6001600160a01b038481168252831660208201526060604082018190525f90614d2490830184615739565b5f602082840312156157ad575f80fd5b81518015158114610cea575f80fd5b60ff851681526001600160a01b038481166020830152831660408201526080606082018190525f90614e7790830184615739565b8082025f8212600160ff1b8414161561580b5761580b615694565b8181058314821517610ad757610ad7615694565b6001600160a01b039390931683526020830191909152604082015260600190565b81810381811115610ad757610ad7615694565b65ffffffffffff8181168382160190808211156149a7576149a7615694565b6001600160681b038181168382160190808211156149a7576149a7615694565b65ffffffffffff8281168282160390808211156149a7576149a7615694565b601f821115610e1a575f81815260208120601f850160051c810160208610156158d75750805b601f850160051c820191505b818110156158f6578281556001016158e3565b505050505050565b815167ffffffffffffffff811115615918576159186152db565b61592c81615926845461565c565b846158b1565b602080601f83116001811461595f575f84156159485750858301515b5f19600386901b1c1916600185901b1785556158f6565b5f85815260208120601f198616915b8281101561598d5788860151825594840194600190910190840161596e565b50858210156159aa57878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b634e487b7160e01b5f52601260045260245ffd5b5f826159dc576159dc6159ba565b500490565b5f826159ef576159ef6159ba565b500690565b5f60018201615a0557615a05615694565b5060010190565b634e487b7160e01b5f52602160045260245ffd5b600181815b80851115615a5a57815f1904821115615a4057615a40615694565b80851615615a4d57918102915b93841c9390800290615a25565b509250929050565b5f82615a7057506001610ad7565b81615a7c57505f610ad7565b8160018114615a925760028114615a9c57615ab8565b6001915050610ad7565b60ff841115615aad57615aad615694565b50506001821b610ad7565b5060208310610133831016604e8410600b8410161715615adb575081810a610ad7565b615ae58383615a20565b805f1904821115615af857615af8615694565b029392505050565b5f610cea8383615a62565b5f60ff831680615b1d57615b1d6159ba565b8060ff84160691505092915050565b5f8251615b3d818460208701614f57565b919091019291505056fe5ab1a5ffb29c47d95dec8c5f9ad49a551754822b51a3359ed1c21e2be24beefaeef3dac4538c82c8ace4063ab0acd2d15cdb5883aa1dff7c2673abb3d8698400ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800cd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300eef3dac4538c82c8ace4063ab0acd2d15cdb5883aa1dff7c2673abb3d8698401a264697066735822122015e733dc03be8e0e48b181c40c5cbbdd7355a98c3b19dcf74958e9219194d7d664736f6c63430008150033

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.