ETH Price: $2,603.10 (+0.84%)

Contract

0x335FBFf118829Aa5ef0ac91196C164538A21a45A
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Token Holdings

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Repay Full And W...208835692024-10-03 7:43:1126 days ago1727941391IN
0x335FBFf1...38A21a45A
0 ETH0.002572887.48544304
Repay And Withdr...208831142024-10-03 6:12:1126 days ago1727935931IN
0x335FBFf1...38A21a45A
0 ETH0.001987965.68232693
Repay And Withdr...208830862024-10-03 6:06:1126 days ago1727935571IN
0x335FBFf1...38A21a45A
0 ETH0.001932355.43267824
Repay And Withdr...203902872024-07-26 11:00:2395 days ago1721991623IN
0x335FBFf1...38A21a45A
0 ETH0.000601732.05647517
Repay And Withdr...202056562024-06-30 16:20:23121 days ago1719764423IN
0x335FBFf1...38A21a45A
0 ETH0.001731665.58531291
Repay Full And W...200160582024-06-04 4:25:47147 days ago1717475147IN
0x335FBFf1...38A21a45A
0 ETH0.002105866.48978382
Repay And Withdr...200160402024-06-04 4:22:11147 days ago1717474931IN
0x335FBFf1...38A21a45A
0 ETH0.002336026.77618213
Repay And Withdr...200160252024-06-04 4:19:11147 days ago1717474751IN
0x335FBFf1...38A21a45A
0 ETH0.002297167.24988901
Repay And Withdr...200159702024-06-04 4:08:11147 days ago1717474091IN
0x335FBFf1...38A21a45A
0 ETH0.002179686.87128619
Flashswap And Mi...199998272024-06-01 22:02:11150 days ago1717279331IN
0x335FBFf1...38A21a45A
0 ETH0.004073985.77100973
Repay And Withdr...198647732024-05-14 0:48:11169 days ago1715647691IN
0x335FBFf1...38A21a45A
0 ETH0.001130753.64773104
Flashswap And Mi...198367332024-05-10 2:43:35172 days ago1715309015IN
0x335FBFf1...38A21a45A
0 ETH0.002847733.98525507
Repay And Withdr...198311842024-05-09 8:06:35173 days ago1715241995IN
0x335FBFf1...38A21a45A
0 ETH0.001369634.41346639
Flashswap And Mi...198309482024-05-09 7:19:23173 days ago1715239163IN
0x335FBFf1...38A21a45A
0 ETH0.002957594.37560105
Flashswap And Mi...197939502024-05-04 3:05:47178 days ago1714791947IN
0x335FBFf1...38A21a45A
0 ETH0.004127255.81470252
Deposit And Borr...197449992024-04-27 6:50:59185 days ago1714200659IN
0x335FBFf1...38A21a45A
0 ETH0.001456945.63334116
Flashswap And Mi...197449402024-04-27 6:38:59185 days ago1714199939IN
0x335FBFf1...38A21a45A
0 ETH0.004075834.74412056
Flashswap And Mi...196060032024-04-07 19:50:11205 days ago1712519411IN
0x335FBFf1...38A21a45A
0 ETH0.010680914.91280281
Flashswap And Mi...195866562024-04-05 2:46:35207 days ago1712285195IN
0x335FBFf1...38A21a45A
0 ETH0.0125523614.75724172
Deposit And Borr...195866502024-04-05 2:45:23207 days ago1712285123IN
0x335FBFf1...38A21a45A
0 ETH0.0040495115.23972254
Flashswap And Mi...195855142024-04-04 22:56:47208 days ago1712271407IN
0x335FBFf1...38A21a45A
0 ETH0.0136294216.47147686
Deposit And Borr...195855032024-04-04 22:54:35208 days ago1712271275IN
0x335FBFf1...38A21a45A
0 ETH0.0043289116.30881476
Flashswap And Mi...195755132024-04-03 13:22:35209 days ago1712150555IN
0x335FBFf1...38A21a45A
0 ETH0.0213157829.94260855
Flashswap And Mi...194657902024-03-19 2:20:59224 days ago1710814859IN
0x335FBFf1...38A21a45A
0 ETH0.0231887430.42539422
Flashswap And Mi...194648802024-03-18 23:16:35225 days ago1710803795IN
0x335FBFf1...38A21a45A
0 ETH0.0214224928.19217269
View all transactions

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
199998272024-06-01 22:02:11150 days ago1717279331
0x335FBFf1...38A21a45A
5.44491245 ETH
199998272024-06-01 22:02:11150 days ago1717279331
0x335FBFf1...38A21a45A
5.44491245 ETH
198367332024-05-10 2:43:35172 days ago1715309015
0x335FBFf1...38A21a45A
8.43351991 ETH
198367332024-05-10 2:43:35172 days ago1715309015
0x335FBFf1...38A21a45A
8.43351991 ETH
198309482024-05-09 7:19:23173 days ago1715239163
0x335FBFf1...38A21a45A
0.30515764 ETH
198309482024-05-09 7:19:23173 days ago1715239163
0x335FBFf1...38A21a45A
0.30515764 ETH
197939502024-05-04 3:05:47178 days ago1714791947
0x335FBFf1...38A21a45A
4.7507806 ETH
197939502024-05-04 3:05:47178 days ago1714791947
0x335FBFf1...38A21a45A
4.7507806 ETH
197449402024-04-27 6:38:59185 days ago1714199939
0x335FBFf1...38A21a45A
36.4194034 ETH
197449402024-04-27 6:38:59185 days ago1714199939
0x335FBFf1...38A21a45A
36.4194034 ETH
196060032024-04-07 19:50:11205 days ago1712519411
0x335FBFf1...38A21a45A
9.90195441 ETH
196060032024-04-07 19:50:11205 days ago1712519411
0x335FBFf1...38A21a45A
9.90195441 ETH
195866562024-04-05 2:46:35207 days ago1712285195
0x335FBFf1...38A21a45A
46.97911908 ETH
195866562024-04-05 2:46:35207 days ago1712285195
0x335FBFf1...38A21a45A
46.97911908 ETH
195855142024-04-04 22:56:47208 days ago1712271407
0x335FBFf1...38A21a45A
43.29176625 ETH
195855142024-04-04 22:56:47208 days ago1712271407
0x335FBFf1...38A21a45A
43.29176625 ETH
195755132024-04-03 13:22:35209 days ago1712150555
0x335FBFf1...38A21a45A
36.66872063 ETH
195755132024-04-03 13:22:35209 days ago1712150555
0x335FBFf1...38A21a45A
36.66872063 ETH
194657902024-03-19 2:20:59224 days ago1710814859
0x335FBFf1...38A21a45A
36.84856656 ETH
194657902024-03-19 2:20:59224 days ago1710814859
0x335FBFf1...38A21a45A
36.84856656 ETH
194648802024-03-18 23:16:35225 days ago1710803795
0x335FBFf1...38A21a45A
45.38858061 ETH
194648802024-03-18 23:16:35225 days ago1710803795
0x335FBFf1...38A21a45A
45.38858061 ETH
194645212024-03-18 22:03:47225 days ago1710799427
0x335FBFf1...38A21a45A
232.05182669 ETH
194645212024-03-18 22:03:47225 days ago1710799427
0x335FBFf1...38A21a45A
232.05182669 ETH
193873002024-03-08 1:54:23235 days ago1709862863  Contract Creation0 ETH
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
RsEthHandler

Compiler Version
v0.8.21+commit.d9974bed

Optimization Enabled:
Yes with 300 runs

Other Settings:
shanghai EvmVersion
File 1 of 51 : RsEthHandler.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

import { IonPool } from "../../IonPool.sol";
import { GemJoin } from "../../join/GemJoin.sol";
import { IRsEth } from "../../interfaces/ProviderInterfaces.sol";
import { Whitelist } from "../../Whitelist.sol";
import { UniswapFlashswapDirectMintHandler } from "../UniswapFlashswapDirectMintHandler.sol";
import { IonHandlerBase } from "../IonHandlerBase.sol";
import { RSETH, WETH_ADDRESS } from "../../Constants.sol";
import { KelpDaoLibrary } from "../../libraries/lrt/KelpDaoLibrary.sol";

import { IUniswapV3Pool } from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";

/**
 * @notice Handler for the rsETH/wstETH market.
 *
 * @custom:security-contact [email protected]
 */
contract RsEthHandler is UniswapFlashswapDirectMintHandler {
    using KelpDaoLibrary for IRsEth;

    /**
     * @notice Creates a new `RsEthHandler` instance.
     * @param _ilkIndex Ilk index of the pool.
     * @param _ionPool address.
     * @param _gemJoin address.
     * @param _whitelist address.
     * @param _wstEthUniswapPool address of the wstETH/WETH Uniswap pool (0.01% fee).
     */
    constructor(
        uint8 _ilkIndex,
        IonPool _ionPool,
        GemJoin _gemJoin,
        Whitelist _whitelist,
        IUniswapV3Pool _wstEthUniswapPool
    )
        IonHandlerBase(_ilkIndex, _ionPool, _gemJoin, _whitelist)
        UniswapFlashswapDirectMintHandler(_wstEthUniswapPool, WETH_ADDRESS)
    { }

    /**
     * @inheritdoc UniswapFlashswapDirectMintHandler
     */
    function _mintCollateralAsset(uint256 amountWeth) internal override returns (uint256) {
        WETH.withdraw(amountWeth);
        return RSETH.depositForLrt(amountWeth);
    }

    /**
     * @inheritdoc UniswapFlashswapDirectMintHandler
     */
    function _getAmountInForCollateralAmountOut(uint256 amountOut) internal view override returns (uint256) {
        return RSETH.getEthAmountInForLstAmountOut(amountOut);
    }
}

File 2 of 51 : 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 { RewardModule } from "./reward/RewardModule.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, RewardModule {
    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, msg.sender, user, proof);
        _;
    }

    modifier onlyWhitelistedLenders(address user, bytes32[] memory proof) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        $.whitelist.isWhitelistedLender(msg.sender, 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 weth; // liquidity in pool [WAD]
        uint256 wethSupplyCap; // [WAD]
        uint256 totalUnbackedDebt; // Total Unbacked WETH  [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);
        RewardModule._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();

        $.wethSupplyCap = 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;
        if (_totalNormalizedDebt == 0 || block.timestamp == ilk.lastRateUpdate) {
            // 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);

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

        // Calculates borrowRate ^ (time) and returns the result with RAY precision
        uint256 borrowRateExpT = _rpow(borrowRate + RAY, block.timestamp - ilk.lastRateUpdate, RAY);

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

        // 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();

        $.weth -= 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();

        $.weth += amount;

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

        uint256 _supplyCap = $.wethSupplyCap;
        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;

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

            $.weth -= 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 total amount of collateral in the pool.
     */
    function ilkCount() external view returns (uint256) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return $.ilks.length;
    }

    /**
     * @return The index of the collateral with `ilkAddress`.
     */
    function getIlkIndex(address ilkAddress) external view returns (uint8) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        bytes32 addressInBytes32 = bytes32(uint256(uint160(ilkAddress)));

        // Since there should never be more than 256 collaterals, an unsafe cast
        // should be fine
        return uint8($.ilkAddresses._inner._positions[addressInBytes32] - 1);
    }

    /**
     * @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 Whether or not an address is a supported collateral.
     */
    function addressContains(address ilk) external view returns (bool) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return $.ilkAddresses.contains(ilk);
    }

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

    function rateUnaccrued(uint8 ilkIndex) external view returns (uint256) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return $.ilks[ilkIndex].rate;
    }

    /**
     * @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 The timestamp of the last rate update for collateral with index
     * `ilkIndex`.
     */
    function lastRateUpdate(uint8 ilkIndex) external view returns (uint256) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return $.ilks[ilkIndex].lastRateUpdate;
    }

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

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

    /**
     * @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 Amount of `gem` that `user` has for collateral with index `ilkIndex`.
     */
    function gem(uint8 ilkIndex, address user) external view returns (uint256) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return $.gem[ilkIndex][user];
    }

    /**
     * @return The amount of unbacked debt `user` has.
     */
    function unbackedDebt(address user) external view returns (uint256) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return $.unbackedDebt[user];
    }

    /**
     * @return Whether or not `operator` is an `operator` on `user`'s positions.
     */
    function isOperator(address user, address operator) external view returns (bool) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return $.isOperator[user][operator] == 1;
    }

    /**
     * @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);
    }

    function debtUnaccrued() external view returns (uint256) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return $.debt;
    }

    /**
     * @dev This includes unbacked debt.
     * @return The total amount of debt.
     */
    function debt() external view returns (uint256) {
        IonPoolStorage storage $ = _getIonPoolStorage();

        (,,, uint256 totalDebtIncrease,) = calculateRewardAndDebtDistribution();

        return $.debt + totalDebtIncrease;
    }

    /**
     * @return The total amount of unbacked debt.
     */
    function totalUnbackedDebt() external view returns (uint256) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return $.totalUnbackedDebt;
    }

    /**
     * @return The address of interest rate module.
     */
    function interestRateModule() external view returns (address) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return address($.interestRateModule);
    }

    /**
     * @return The address of the whitelist.
     */
    function whitelist() external view returns (address) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return address($.whitelist);
    }

    /**
     * @return The total amount of ETH liquidity in the pool.
     */
    function weth() external view returns (uint256) {
        IonPoolStorage storage $ = _getIonPoolStorage();
        return $.weth;
    }

    /**
     * @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;
    }

    /**
     * @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 3 of 51 : GemJoin.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.21;

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

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

/**
 * @notice Collateral deposits are held independently from the `IonPool` core
 * contract, but credited to users through `gem` balances.
 *
 * @dev Separating collateral deposits from the core contract allows for
 * handling tokens with non-standard behavior, if needed.
 *
 * This contract implements access control through `Ownable2Step`.
 *
 * This contract implements pausing through OpenZeppelin's `Pausable`.
 *
 * @custom:security-contact [email protected]
 */
contract GemJoin is Ownable2Step, Pausable {
    error Int256Overflow();
    error WrongIlkAddress(uint8 ilkIndex, IERC20 gem);

    using SafeERC20 for IERC20;

    IERC20 public immutable GEM;
    IonPool public immutable POOL;
    uint8 public immutable ILK_INDEX;

    uint256 public totalGem;

    /**
     * @notice Creates a new `GemJoin` instance.
     * @param _pool Address of the `IonPool` contract.
     * @param _gem ERC20 collateral to be associated with this `GemJoin` instance.
     * @param _ilkIndex of the associated collateral.
     * @param owner Admin of the contract.
     */
    constructor(IonPool _pool, IERC20 _gem, uint8 _ilkIndex, address owner) Ownable(owner) {
        GEM = _gem;
        POOL = _pool;
        ILK_INDEX = _ilkIndex;

        // Sanity check
        if (_pool.getIlkAddress(_ilkIndex) != address(_gem)) revert WrongIlkAddress(_ilkIndex, _gem);
    }

    /**
     * @notice Pauses the contract.
     * @dev Pauses the contract.
     */
    function pause() external onlyOwner {
        _pause();
    }

    /**
     * @notice Unpauses the contract.
     * @dev Unpauses the contract.
     */
    function unpause() external onlyOwner {
        _unpause();
    }

    /**
     * @notice Converts ERC20 token into gem (credit inside of the `IonPool`'s internal accounting).
     * @dev Gem will be sourced from `msg.sender` and credited to `user`.
     * @param user to credit the gem to.
     * @param amount of gem to add. [WAD]
     */
    function join(address user, uint256 amount) external whenNotPaused {
        if (int256(amount) < 0) revert Int256Overflow();

        totalGem += amount;

        POOL.mintAndBurnGem(ILK_INDEX, user, int256(amount));
        GEM.safeTransferFrom(msg.sender, address(this), amount);
    }

    /**
     * @notice Debits gem from the `IonPool`'s internal accounting and withdraws it into ERC20 token.
     * @dev Gem will be debited from `msg.sender` and sent to `user`.
     * @param user to send the withdrawn ERC20 tokens to.
     * @param amount of gem to remove. [WAD]
     */
    function exit(address user, uint256 amount) external whenNotPaused {
        if (int256(amount) < 0) revert Int256Overflow();

        totalGem -= amount;

        POOL.mintAndBurnGem(ILK_INDEX, msg.sender, -int256(amount));
        GEM.safeTransfer(user, amount);
    }
}

File 4 of 51 : ProviderInterfaces.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

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

interface IStEth is IERC20 {
    function submit(address _referral) external payable returns (uint256);

    function getTotalPooledEther() external view returns (uint256);

    function getTotalShares() external view returns (uint256);

    function getSharesByPooledEth(uint256 _ethAmount) external view returns (uint256);

    function getCurrentStakeLimit() external view returns (uint256);

    function approve(address spender, uint256 value) external returns (bool);
}

interface IWstEth is IERC20 {
    function wrap(uint256 _stETHAmount) external returns (uint256);

    /**
     * @notice Exchanges wstETH to stETH
     * @param _wstETHAmount amount of wstETH to uwrap in exchange for stETH
     * @dev Requirements:
     *  - `_wstETHAmount` must be non-zero
     *  - msg.sender must have at least `_wstETHAmount` wstETH.
     * @return Amount of stETH user receives after unwrap
     */
    function unwrap(uint256 _wstETHAmount) external returns (uint256);

    function getStETHByWstETH(uint256 _ETHAmount) external view returns (uint256);

    function getWstETHByStETH(uint256 _stETHAmount) external view returns (uint256);

    function stETH() external view returns (address);

    function stEthPerToken() external view returns (uint256);

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

interface IStaderStakePoolsManager {
    function deposit(address _receiver) external payable returns (uint256);

    function previewDeposit(uint256 _assets) external view returns (uint256);

    function previewWithdraw(uint256 _shares) external view returns (uint256);

    function getExchangeRate() external view returns (uint256);

    function staderConfig() external view returns (IStaderConfig);

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

interface IStaderConfig {
    function getMinDepositAmount() external view returns (uint256);

    function getMaxDepositAmount() external view returns (uint256);

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

/// @title ExchangeRate
/// @notice This struct holds data related to the exchange rate between ETH and ETHx.
struct ExchangeRate {
    /// @notice The block number when the exchange rate was last updated.
    uint256 reportingBlockNumber;
    /// @notice The total balance of Ether (ETH) in the system.
    uint256 totalETHBalance;
    /// @notice The total supply of the liquid staking token (ETHx) in the system.
    uint256 totalETHXSupply;
}

interface IStaderOracle {
    function getExchangeRate() external view returns (ExchangeRate memory);
}

interface IETHx is IERC20 { }

interface ISwEth {
    function deposit() external payable;

    function swETHToETHRate() external view returns (uint256);

    function ethToSwETHRate() external view returns (uint256);

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

interface IWeEth is IERC20 {
    function getRate() external view returns (uint256);
    function getEETHByWeETH(uint256) external view returns (uint256);

    // Official function technically returns the interface but we won't type it
    // here
    function eETH() external view returns (address);
    function liquidityPool() external view returns (address);
    function wrap(uint256 _eETHAmount) external returns (uint256);
    function unwrap(uint256 _weETHAmount) external returns (uint256);
}

interface IEEth is IERC20 {
    function totalShares() external view returns (uint256);
}

interface IEtherFiLiquidityPool {
    function totalValueOutOfLp() external view returns (uint128);
    function totalValueInLp() external view returns (uint128);
    function amountForShare(uint256 _share) external view returns (uint256);
    function sharesForAmount(uint256 _amount) external view returns (uint256);
    function deposit() external payable returns (uint256);
    function getTotalPooledEther() external view returns (uint256);
    function getTotalEtherClaimOf(address _user) external view returns (uint256);
}

interface IRsEth is IERC20 { }

interface ILRTOracle {
    function rsETHPrice() external view returns (uint256);
    function updateRSETHPrice() external;
}

interface ILRTDepositPool {
    function getTotalAssetDeposits(address asset) external view returns (uint256);

    function getAssetDistributionData(address asset) external view returns (uint256, uint256, uint256);

    function depositETH(uint256 minRSETHAmountExpected, string calldata referralId) external payable;

    function getRsETHAmountToMint(address asset, uint256 amount) external view returns (uint256);

    function minAmountToDeposit() external view returns (uint256);

    function getAssetCurrentLimit(address asset) external view returns (uint256);
}

interface ILRTConfig {
    function rsETH() external view returns (address);

    function assetStrategy(address asset) external view returns (address);

    function isSupportedAsset(address asset) external view returns (bool);

    function getLSTToken(bytes32 tokenId) external view returns (address);

    function getContract(bytes32 contractId) external view returns (address);

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

    function depositLimitByAsset(address asset) external view returns (uint256);
}

File 5 of 51 : 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 6 of 51 : UniswapFlashswapDirectMintHandler.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

import { IonHandlerBase } from "./IonHandlerBase.sol";
import { IWETH9 } from "../interfaces/IWETH9.sol";

import { IUniswapV3Pool } from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import { IUniswapV3SwapCallback } from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";

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

/**
 * @notice This contract allows for easy creation of leverge positions through a
 * Uniswap flashswap and direct mint of the collateral from the provider. This
 * will be used when the collateral cannot be minted directly with the base
 * asset but can be directly minted by a token that the base asset has a
 * UniswapV3 pool with.
 *
 * This contract is to be used when there exists a UniswapV3 pool between the
 * base asset and the mint asset.
 *
 * @custom:security-contact [email protected]
 */
abstract contract UniswapFlashswapDirectMintHandler is IonHandlerBase, IUniswapV3SwapCallback {
    using SafeERC20 for IERC20;
    using SafeERC20 for IWETH9;
    using SafeCast for uint256;

    error InvalidUniswapPool();
    error InvalidZeroLiquidityRegionSwap();
    error CallbackOnlyCallableByPool(address unauthorizedCaller);
    error OutputAmountNotReceived(uint256 amountReceived, uint256 amountRequired);

    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_RATIO = 4_295_128_739;
    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_RATIO = 1_461_446_703_485_210_103_287_273_052_203_988_822_378_723_970_342;

    IUniswapV3Pool public immutable UNISWAP_POOL;
    IERC20 public immutable MINT_ASSET;
    bool private immutable MINT_IS_TOKEN0;

    /**
     * @notice Creates a new `UniswapFlashswapDirectMintHandler` instance.
     * @param _uniswapPool Pool to perform the flashswap on.
     * @param _mintAsset The asset used to mint the collateral.
     */
    constructor(IUniswapV3Pool _uniswapPool, IERC20 _mintAsset) {
        if (address(_uniswapPool) == address(0)) revert InvalidUniswapPool();

        MINT_ASSET = _mintAsset;

        address token0 = _uniswapPool.token0();
        address token1 = _uniswapPool.token1();

        if (token0 != address(MINT_ASSET) && token1 != address(MINT_ASSET)) {
            revert InvalidUniswapPool();
        }
        if (token0 == address(MINT_ASSET) && token1 == address(MINT_ASSET)) {
            revert InvalidUniswapPool();
        }

        UNISWAP_POOL = _uniswapPool;
        MINT_IS_TOKEN0 = token0 == address(MINT_ASSET) ? true : false;

        address baseAsset = MINT_IS_TOKEN0 ? token1 : token0;

        if (baseAsset != address(BASE)) revert InvalidUniswapPool();
    }

    /**
     * @notice Transfer collateral from user -> Initiate flashswap between from
     * base asset to mint asset -> Use the mint asset to mint the collateral ->
     * Deposit all collateral into `IonPool` -> Borrow the base asset -> Close
     * the flashswap by sending the base asset to the Uniswap pool.
     * @param initialDeposit in collateral terms. [WAD]
     * @param resultingAdditionalCollateral in collateral terms. [WAD]
     * @param maxResultingDebt in base asset terms. [WAD]
     * @param proof used to validate the user is whitelisted.
     */
    function flashswapAndMint(
        uint256 initialDeposit,
        uint256 resultingAdditionalCollateral,
        uint256 maxResultingDebt,
        uint256 deadline,
        bytes32[] memory proof
    )
        external
        onlyWhitelistedBorrowers(proof)
        checkDeadline(deadline)
    {
        LST_TOKEN.safeTransferFrom(msg.sender, address(this), initialDeposit);
        _flashswapAndMint(initialDeposit, resultingAdditionalCollateral, maxResultingDebt);
    }

    function _flashswapAndMint(
        uint256 initialDeposit,
        uint256 resultingAdditionalCollateral,
        uint256 maxResultingDebt
    )
        internal
    {
        uint256 amountLrt = resultingAdditionalCollateral - initialDeposit; // in collateral terms
        uint256 amountWethToFlashloan = _getAmountInForCollateralAmountOut(amountLrt);

        if (amountWethToFlashloan == 0) {
            // AmountToBorrow.IS_MAX because we don't want to create any new debt here
            _depositAndBorrow(msg.sender, address(this), resultingAdditionalCollateral, 0, AmountToBorrow.IS_MAX);
            return;
        }

        // We want to swap for ETH here
        bool zeroForOne = MINT_IS_TOKEN0 ? false : true;
        uint256 baseAssetSwappedIn = _initiateFlashSwap({
            zeroForOne: zeroForOne,
            amountOut: amountWethToFlashloan,
            recipient: address(this),
            data: abi.encode(msg.sender, resultingAdditionalCollateral, initialDeposit)
        });

        if (baseAssetSwappedIn > maxResultingDebt) {
            revert FlashloanRepaymentTooExpensive(amountWethToFlashloan, maxResultingDebt);
        }
    }

    /**
     * @notice Handles swap initiation logic. This function can only initiate
     * exact output swaps.
     * @param zeroForOne Direction of the swap.
     * @param amountOut Desired amount of output.
     * @param recipient of output tokens.
     * @param data Arbitrary data to be passed through swap callback.
     */
    function _initiateFlashSwap(
        bool zeroForOne,
        uint256 amountOut,
        address recipient,
        bytes memory data
    )
        private
        returns (uint256 amountIn)
    {
        (int256 amount0Delta, int256 amount1Delta) = UNISWAP_POOL.swap(
            recipient, zeroForOne, -amountOut.toInt256(), zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1, data
        );

        uint256 amountOutReceived;
        (amountIn, amountOutReceived) = zeroForOne
            ? (uint256(amount0Delta), uint256(-amount1Delta))
            : (uint256(amount1Delta), uint256(-amount0Delta));

        // it's technically possible to not receive the full output amount,
        if (amountOutReceived != amountOut) revert OutputAmountNotReceived(amountOutReceived, amountOut);
    }

    /**
     * @notice From the perspective of the pool i.e. Negative amount means pool is
     * sending. This function is intended to never be called directly. It should
     * only be called by the Uniswap pool during a swap initiated by this
     * contract.
     *
     * @dev One thing to note from a security perspective is that the pool only calls
     * the callback on `msg.sender`. So a theoretical attacker cannot call this
     * function by directing where to call the callback.
     *
     * @param amount0Delta change in token0
     * @param amount1Delta change in token1
     * @param _data arbitrary data
     */
    function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata _data) external override {
        if (msg.sender != address(UNISWAP_POOL)) revert CallbackOnlyCallableByPool(msg.sender);

        // swaps entirely within 0-liquidity regions are not supported
        if (amount0Delta == 0 && amount1Delta == 0) revert InvalidZeroLiquidityRegionSwap();
        (address user, uint256 resultingAdditionalCollateral, uint256 initialDeposit) =
            abi.decode(_data, (address, uint256, uint256));

        // Code below this if statement will always assume token0 is MINT_ASSET. If it
        // is not actually the case, we will flip the vars
        if (!MINT_IS_TOKEN0) {
            (amount0Delta, amount1Delta) = (amount1Delta, amount0Delta);
        }

        address tokenIn = address(BASE);

        // Sanity check that Uniswap is sending MINT_ASSET
        assert(amount0Delta < 0 && amount1Delta > 0);

        // MINT_ASSET needs to be converted into collateral asset
        uint256 collateralFromDeposit = _mintCollateralAsset(uint256(-amount0Delta));

        // Sanity check
        assert(collateralFromDeposit + initialDeposit == resultingAdditionalCollateral);

        // AmountToBorrow.IS_MIN because we want to make sure enough is borrowed
        // to cover the amount owed back to Uniswap
        _depositAndBorrow(
            user, address(this), resultingAdditionalCollateral, uint256(amount1Delta), AmountToBorrow.IS_MIN
        );

        IERC20(tokenIn).safeTransfer(msg.sender, uint256(amount1Delta));
    }

    /**
     * @notice Deposits the mint asset into the provider's collateral-asset
     * deposit contract.
     * @param amountMintAsset amount of "mint asset" to deposit. [WAD]
     */
    function _mintCollateralAsset(uint256 amountMintAsset) internal virtual returns (uint256);

    /**
     * @notice Calculates the amount of mint asset required to receive
     * `amountLrt`.
     * @dev Calculates the amount of mint asset required to receive `amountLrt`.
     * @param amountLrt Desired output amount. [WAD]
     * @return Amount mint asset required for desired output. [WAD]
     */
    function _getAmountInForCollateralAmountOut(uint256 amountLrt) internal view virtual returns (uint256);
}

File 7 of 51 : IonHandlerBase.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.21;

import { IonPool } from "../IonPool.sol";
import { IWETH9 } from "../interfaces/IWETH9.sol";
import { GemJoin } from "../join/GemJoin.sol";
import { WadRayMath, RAY } from "../libraries/math/WadRayMath.sol";
import { Whitelist } from "../Whitelist.sol";
import { WETH_ADDRESS } from "../Constants.sol";

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

/**
 * @notice The base handler contract for simpler interactions with the `IonPool`
 * core contract. It combines various individual interactions into one compound
 * interaction to facilitate reaching user end-goals in atomic fashion.
 *
 * @dev To actually borrow from `IonPool`, a user must submit a "normalized" borrow
 * amount. This contract is designed to be user-intuitive and, thus, allows a user
 * to submit a standard desired borrow amount, which this contract will then
 * convert into to the appropriate "normalized" borrow amount.
 *
 * @custom:security-contact [email protected]
 */
abstract contract IonHandlerBase {
    using SafeERC20 for IERC20;
    using SafeERC20 for IWETH9;
    using WadRayMath for uint256;

    error CannotSendEthToContract();
    error FlashloanRepaymentTooExpensive(uint256 repaymentAmount, uint256 maxRepaymentAmount);
    error TransactionDeadlineReached(uint256 deadline);

    /**
     * @notice Checks if the tx is being executed before the designated deadline
     * for execution.
     * @dev This is used to prevent txs that have sat in the mempool for too
     * long from executing at unintended prices.
     */
    modifier checkDeadline(uint256 deadline) {
        if (deadline <= block.timestamp) revert TransactionDeadlineReached(deadline);
        _;
    }

    /**
     * @notice Checks if `msg.sender` is on the whitelist.
     * @dev This contract will be on the `protocolControlledWhitelist`. As such,
     * it will validate that users are on the whitelist itself and be able to
     * bypass the whitelist check on `IonPool`.
     * @param proof to validate the whitelist check.
     */
    modifier onlyWhitelistedBorrowers(bytes32[] memory proof) {
        WHITELIST.isWhitelistedBorrower(ILK_INDEX, msg.sender, msg.sender, proof);
        _;
    }

    /**
     * @dev During conversion from borrow amount -> "normalized" borrow amount,"
     * there is division required. In certain scenarios, it may be desirable to
     * round up during division, in others, to round down. This enum allows a
     * developer to indicate the rounding direction by describing the
     * `amountToBorrow`. If it `IS_MIN`, then the final borrowed amount should
     * be larger than `amountToBorrow` (round up), and vice versa for `IS_MAX`
     * (round down).
     */
    enum AmountToBorrow {
        IS_MIN,
        IS_MAX
    }

    IERC20 public immutable BASE;
    // Will keep WETH for compatibility with other strategies. But this should
    // be removed eventually to remove dependence on WETH as a base asset.
    IWETH9 public immutable WETH;
    uint8 public immutable ILK_INDEX;
    IonPool public immutable POOL;
    GemJoin public immutable JOIN;
    IERC20 public immutable LST_TOKEN;
    Whitelist public immutable WHITELIST;

    /**
     * @notice Creates a new instance of `IonHandlerBase`
     * @param _ilkIndex of the ilk for which this instance is associated with.
     * @param _ionPool address of `IonPool` core contract.
     * @param _gemJoin the `GemJoin` associated with the `ilkIndex` of this
     * contract.
     * @param _whitelist the `Whitelist` module address.
     */
    constructor(uint8 _ilkIndex, IonPool _ionPool, GemJoin _gemJoin, Whitelist _whitelist) {
        POOL = _ionPool;
        ILK_INDEX = _ilkIndex;

        BASE = IERC20(_ionPool.underlying());

        IWETH9 _weth = WETH_ADDRESS;
        WETH = _weth;

        address ilkAddress = POOL.getIlkAddress(_ilkIndex);
        LST_TOKEN = IERC20(ilkAddress);

        JOIN = _gemJoin;

        WHITELIST = _whitelist;

        BASE.approve(address(_ionPool), type(uint256).max);
        IERC20(ilkAddress).approve(address(_gemJoin), type(uint256).max);
    }

    /**
     * @notice Combines gem-joining and depositing collateral and then borrowing
     * into one compound action.
     * @param amountCollateral Amount of collateral to deposit. [WAD]
     * @param amountToBorrow Amount of WETH to borrow. Due to rounding, true
     * borrow amount might be slightly less. [WAD]
     * @param proof that the user is whitelisted.
     */
    function depositAndBorrow(
        uint256 amountCollateral,
        uint256 amountToBorrow,
        bytes32[] calldata proof
    )
        external
        onlyWhitelistedBorrowers(proof)
    {
        LST_TOKEN.safeTransferFrom(msg.sender, address(this), amountCollateral);
        _depositAndBorrow(msg.sender, msg.sender, amountCollateral, amountToBorrow, AmountToBorrow.IS_MAX);
    }

    /**
     * @notice Handles all logic to gem-join and deposit collateral, followed by
     * a borrow. It is also possible to use this function simply to gem-join and
     * deposit collateral atomically by setting `amountToBorrow` to 0.
     * @param vaultHolder The user who will be responsible for repaying debt.
     * @param receiver The user who receives the borrowed funds.
     * @param amountCollateral to move into vault. [WAD]
     * @param amountToBorrow out of the vault. [WAD]
     * @param amountToBorrowType Whether the `amountToBorrow` is a min or max.
     * This will dictate the rounding direction when converting to normalized
     * amount. If it is a minimum, then the rounding will be rounded up. If it
     * is a maximum, then the rounding will be rounded down.
     */
    function _depositAndBorrow(
        address vaultHolder,
        address receiver,
        uint256 amountCollateral,
        uint256 amountToBorrow,
        AmountToBorrow amountToBorrowType
    )
        internal
    {
        JOIN.join(address(this), amountCollateral);

        POOL.depositCollateral(ILK_INDEX, vaultHolder, address(this), amountCollateral, new bytes32[](0));

        if (amountToBorrow == 0) return;

        uint256 rate = POOL.rate(ILK_INDEX);

        uint256 normalizedAmountToBorrow;
        if (amountToBorrowType == AmountToBorrow.IS_MIN) {
            normalizedAmountToBorrow = amountToBorrow.rayDivUp(rate);
        } else {
            normalizedAmountToBorrow = amountToBorrow.rayDivDown(rate);
        }

        POOL.borrow(ILK_INDEX, vaultHolder, receiver, normalizedAmountToBorrow, new bytes32[](0));
    }

    /**
     * @notice Will repay all debt and withdraw desired collateral amount. This
     * function can also simply be used for a full repayment (which may be
     * difficult through a direct tx to the `IonPool`) by setting
     * `collateralToWithdraw` to 0.
     * @dev Will repay the debt belonging to `msg.sender`. This function is
     * necessary because with `rate` updating every single block, it may be
     * difficult to repay a full amount if a user uses the total debt from a
     * previous block. If a user ends up repaying all but dust amounts of debt
     * (due to a slight `rate` change), then they repayment will likely fail due
     * to the `dust` parameter.
     * @param collateralToWithdraw in collateral terms. [WAD]
     */
    function repayFullAndWithdraw(uint256 collateralToWithdraw) external {
        (uint256 repayAmount, uint256 normalizedDebtToRepay) = _getFullRepayAmount(msg.sender);

        BASE.safeTransferFrom(msg.sender, address(this), repayAmount);

        POOL.repay(ILK_INDEX, msg.sender, address(this), normalizedDebtToRepay);

        POOL.withdrawCollateral(ILK_INDEX, msg.sender, address(this), collateralToWithdraw);

        JOIN.exit(msg.sender, collateralToWithdraw);
    }

    /**
     * @notice Helper function to get the repayment amount for all the debt of a
     * `user`.
     * @dev This simply emulates the rounding behaviour of the `IonPool` to
     * arrive at an accurate value.
     * @param user Address of the user.
     * @return repayAmount Amount of base asset required to repay all debt (this
     * mimics IonPool's behavior). [WAD]
     * @return normalizedDebt Total normalized debt held by `user`'s vault.
     * [WAD]
     */
    function _getFullRepayAmount(address user) internal view returns (uint256 repayAmount, uint256 normalizedDebt) {
        uint256 currentRate = POOL.rate(ILK_INDEX);

        normalizedDebt = POOL.normalizedDebt(ILK_INDEX, user);

        // This is exactly how IonPool calculates the amount of base asset
        // required
        uint256 amountRad = normalizedDebt * currentRate;
        repayAmount = amountRad / RAY;
        if (amountRad % RAY > 0) ++repayAmount;
    }

    /**
     * @notice Combines repaying debt and then withdrawing and gem-exitting
     * collateral into one compound action.
     *
     * If repaying **all** is the intention, use `repayFullAndWithdraw()`
     * instead to prevent tx revert from dust amounts of debt in vault.
     * @param debtToRepay In ETH terms. [WAD]
     * @param collateralToWithdraw In collateral terms. [WAD]
     */
    function repayAndWithdraw(uint256 debtToRepay, uint256 collateralToWithdraw) external {
        BASE.safeTransferFrom(msg.sender, address(this), debtToRepay);
        _repayAndWithdraw(msg.sender, msg.sender, collateralToWithdraw, debtToRepay);
    }

    /**
     * @notice Handles all logic to repay debt, followed by a collateral
     * withdrawal and gem-exit. This function can also be used to just withdraw
     * and gem-exit in atomic fashion by setting the `debtToRepay` to 0.
     * @param vaultHolder The user whose debt will be repaid.
     * @param receiver The user who receives the the withdrawn collateral.
     * @param collateralToWithdraw to move into vault. [WAD]
     * @param debtToRepay out of the vault. [WAD]
     */
    function _repayAndWithdraw(
        address vaultHolder,
        address receiver,
        uint256 collateralToWithdraw,
        uint256 debtToRepay
    )
        internal
    {
        uint256 currentRate = POOL.rate(ILK_INDEX);

        uint256 normalizedDebtToRepay = debtToRepay.rayDivDown(currentRate);

        POOL.repay(ILK_INDEX, vaultHolder, address(this), normalizedDebtToRepay);

        POOL.withdrawCollateral(ILK_INDEX, vaultHolder, address(this), collateralToWithdraw);

        JOIN.exit(receiver, collateralToWithdraw);
    }

    /**
     * @notice ETH cannot be directly sent to this contract.
     * @dev To allow unwrapping of WETH into ETH.
     */
    receive() external payable {
        if (msg.sender != address(WETH_ADDRESS)) revert CannotSendEthToContract();
    }
}

File 8 of 51 : Constants.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.21;

import { IWETH9 } from "./interfaces/IWETH9.sol";
import {
    IWstEth,
    IStEth,
    IStaderStakePoolsManager,
    IETHx,
    ISwEth,
    IEEth,
    IWeEth,
    IRsEth,
    ILRTOracle,
    ILRTConfig,
    IEtherFiLiquidityPool,
    ILRTDepositPool
} from "./interfaces/ProviderInterfaces.sol";
import { IRedstonePriceFeed } from "./interfaces/IRedstone.sol";
import { IChainlink } from "./interfaces/IChainlink.sol";
import { ICreateX } from "./interfaces/ICreateX.sol";
import { IUniswapV3Pool } from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";

uint8 constant REDSTONE_DECIMALS = 8;

address constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

IWETH9 constant WETH_ADDRESS = IWETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);

// StETH
IWstEth constant WSTETH_ADDRESS = IWstEth(0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0);
IStEth constant STETH_ADDRESS = IStEth(0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84);

// ETHx
IETHx constant ETHX_ADDRESS = IETHx(0xA35b1B31Ce002FBF2058D22F30f95D405200A15b);
IStaderStakePoolsManager constant STADER_STAKE_POOLS_MANAGER_ADDRESS =
    IStaderStakePoolsManager(0xcf5EA1b38380f6aF39068375516Daf40Ed70D299);

// swETH
ISwEth constant SWETH_ADDRESS = ISwEth(0xf951E335afb289353dc249e82926178EaC7DEd78);

// eETH
IEEth constant EETH_ADDRESS = IEEth(0x35fA164735182de50811E8e2E824cFb9B6118ac2);
IEtherFiLiquidityPool constant ETHER_FI_LIQUIDITY_POOL_ADDRESS =
    IEtherFiLiquidityPool(0x308861A430be4cce5502d0A12724771Fc6DaF216);
IWeEth constant WEETH_ADDRESS = IWeEth(0xCd5fE23C85820F7B72D0926FC9b05b43E359b7ee);
IRedstonePriceFeed constant REDSTONE_WEETH_ETH_PRICE_FEED =
    IRedstonePriceFeed(0x8751F736E94F6CD167e8C5B97E245680FbD9CC36);

// rsETH
IRedstonePriceFeed constant REDSTONE_RSETH_ETH_PRICE_FEED =
    IRedstonePriceFeed(0xA736eAe8805dDeFFba40cAB8c99bCB309dEaBd9B);
IRsEth constant RSETH = IRsEth(0xA1290d69c65A6Fe4DF752f95823fae25cB99e5A7);
ILRTOracle constant RSETH_LRT_ORACLE = ILRTOracle(0x349A73444b1a310BAe67ef67973022020d70020d);
ILRTConfig constant RSETH_LRT_CONFIG = ILRTConfig(0x947Cb49334e6571ccBFEF1f1f1178d8469D65ec7);
ILRTDepositPool constant RSETH_LRT_DEPOSIT_POOL = ILRTDepositPool(0x036676389e48133B63a802f8635AD39E752D375D);

// ezETH
IRedstonePriceFeed constant REDSTONE_EZETH_ETH_PRICE_FEED =
    IRedstonePriceFeed(0xF4a3e183F59D2599ee3DF213ff78b1B3b1923696);

// Chainlink
IChainlink constant ETH_PER_STETH_CHAINLINK = IChainlink(0x86392dC19c0b719886221c78AB11eb8Cf5c52812);
IChainlink constant MAINNET_USD_PER_ETH_CHAINLINK = IChainlink(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);

// Redstone
IRedstonePriceFeed constant MAINNET_USD_PER_ETHX_REDSTONE =
    IRedstonePriceFeed(0xFaBEb1474C2Ab34838081BFdDcE4132f640E7D2d);

// Uniswap
IUniswapV3Pool constant MAINNET_SWETH_ETH_UNISWAP_01 = IUniswapV3Pool(0x30eA22C879628514f1494d4BBFEF79D21A6B49A2);
IUniswapV3Pool constant MAINNET_WSTETH_WETH_UNISWAP = IUniswapV3Pool(0x109830a1AAaD605BbF02a9dFA7B0B92EC2FB7dAa);

// CreateX
ICreateX constant CREATEX = ICreateX(0xba5Ed099633D3B313e4D5F7bdc1305d3c28ba5Ed);

File 9 of 51 : KelpDaoLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

import { IRsEth } from "../../interfaces/ProviderInterfaces.sol";
import { RSETH_LRT_DEPOSIT_POOL, RSETH_LRT_ORACLE, ETH_ADDRESS } from "../../Constants.sol";
import { WadRayMath, WAD } from "../math/WadRayMath.sol";

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

using WadRayMath for uint256;
using Math for uint256;

library KelpDaoLibrary {
    /**
     * @notice Deposits a given amount of ETH into the rsETH Deposit Pool.
     * @param ethAmount Amount of ETH to deposit. [WAD]
     * @return rsEthAmountToMint Amount of rsETH that was obtained. [WAD]
     */
    function depositForLrt(IRsEth, uint256 ethAmount) internal returns (uint256 rsEthAmountToMint) {
        rsEthAmountToMint = RSETH_LRT_DEPOSIT_POOL.getRsETHAmountToMint(ETH_ADDRESS, ethAmount);
        RSETH_LRT_DEPOSIT_POOL.depositETH{ value: ethAmount }(0, ""); // TODO: slippage tolerance on mint
    }

    function getEthAmountInForLstAmountOut(IRsEth, uint256 amountOut) internal view returns (uint256) {
        // getRsEthAmountToMint
        // rsEthAmountToMint = floor(amount * assetPrice / rsETHPrice)
        // assetPrice for ETH is always 1e18 on the contract
        // rsEthAmountToMint * rsETHPrice / assetPrice = amount
        // round up the amount to ensure that the user has enough to mint the rsETH

        return amountOut.mulDiv(RSETH_LRT_ORACLE.rsETHPrice(), WAD, Math.Rounding.Ceil);
    }

    function getLstAmountOutForEthAmountIn(IRsEth, uint256 ethAmount) internal view returns (uint256) {
        return RSETH_LRT_DEPOSIT_POOL.getRsETHAmountToMint(ETH_ADDRESS, ethAmount);
    }
}

File 10 of 51 : IUniswapV3Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';

/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
    IUniswapV3PoolImmutables,
    IUniswapV3PoolState,
    IUniswapV3PoolDerivedState,
    IUniswapV3PoolActions,
    IUniswapV3PoolOwnerActions,
    IUniswapV3PoolEvents
{

}

File 11 of 51 : 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 12 of 51 : RewardModule.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.21;

import { WadRayMath, RAY } from "../libraries/math/WadRayMath.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";

/**
 * @title RewardModule
 * @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 RewardModule is ContextUpgradeable, AccessControlDefaultAdminRulesUpgradeable {
    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 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);

    /**
     * @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);

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

    event TreasuryUpdate(address treasury);

    /// @custom:storage-location erc7201:ion.storage.RewardModule
    struct RewardModuleStorage {
        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]
    }

    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 RewardModuleStorageLocation =
        0xdb3a0d63a7808d7d0422c40bb62354f42bff7602a547c329c1453dbcbeef4900;

    function _getRewardModuleStorage() private pure returns (RewardModuleStorage storage $) {
        assembly {
            $.slot := RewardModuleStorageLocation
        }
    }

    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();

        RewardModuleStorage storage $ = _getRewardModuleStorage();

        $.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) {
        RewardModuleStorage storage $ = _getRewardModuleStorage();

        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 {
        RewardModuleStorage storage $ = _getRewardModuleStorage();

        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) {
        RewardModuleStorage storage $ = _getRewardModuleStorage();

        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));

        RewardModuleStorage storage $ = _getRewardModuleStorage();

        $.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;

        RewardModuleStorage storage $ = _getRewardModuleStorage();

        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);
    }

    function _setSupplyFactor(uint256 newSupplyFactor) internal {
        RewardModuleStorage storage $ = _getRewardModuleStorage();
        $.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();

        RewardModuleStorage storage $ = _getRewardModuleStorage();
        $.treasury = newTreasury;

        emit TreasuryUpdate(newTreasury);
    }

    // --- Getters ---

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

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

    /**
     * @dev Current token balance
     * @param user to get balance of
     */
    function balanceOf(address user) public view returns (uint256) {
        RewardModuleStorage storage $ = _getRewardModuleStorage();

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

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

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

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

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

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

    function totalSupplyUnaccrued() public view returns (uint256) {
        RewardModuleStorage storage $ = _getRewardModuleStorage();

        uint256 _normalizedTotalSupply = $.normalizedTotalSupply;

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

        return _normalizedTotalSupply.rayMulDown($.supplyFactor);
    }

    /**
     * @dev Current total supply
     */
    function totalSupply() public view returns (uint256) {
        RewardModuleStorage storage $ = _getRewardModuleStorage();

        uint256 _normalizedTotalSupply = $.normalizedTotalSupply;

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

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

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

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

    /**
     * @dev Current normalized total supply
     */
    function normalizedTotalSupply() public view returns (uint256) {
        RewardModuleStorage storage $ = _getRewardModuleStorage();

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

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

        return $.normalizedTotalSupply + normalizedTreasuryMintAmount;
    }

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

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

        (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 13 of 51 : 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));
        }
        // [RAD] / [WAD] = [RAY]
        uint256 utilizationRate =
            totalEthSupply == 0 ? 0 : totalIlkDebt / (totalEthSupply.wadMulDown(distributionFactor.scaleUpToWad(4)));

        // 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 14 of 51 : 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 15 of 51 : 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 16 of 51 : 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 17 of 51 : 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 18 of 51 : 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 19 of 51 : 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 20 of 51 : 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 21 of 51 : Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.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 Pausable is Context {
    bool private _paused;

    /**
     * @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.
     */
    constructor() {
        _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) {
        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 {
        _paused = true;
        emit Paused(_msgSender());
    }

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

File 22 of 51 : 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 23 of 51 : 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 24 of 51 : 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 25 of 51 : IWETH9.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

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

/**
 * @dev WETH9 interface
 */
interface IWETH9 is IERC20 {
    /**
     * @dev Deposit ether to get wrapped ether
     */
    function deposit() external payable;

    /**
     * @dev Withdraw wrapped ether to get ether
     * @param amount Amount of wrapped ether to withdraw
     */
    function withdraw(uint256 amount) external;
}

File 26 of 51 : IUniswapV3SwapCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
    /// @dev In the implementation you must pay the pool tokens owed for the swap.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

File 27 of 51 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

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

File 28 of 51 : IRedstone.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

interface IRedstonePriceFeed {
    /**
     * @notice Returns details of the latest successful update round
     * @dev It uses few helpful functions to abstract logic of getting
     * latest round id and value
     * @return roundId The number of the latest round
     * @return answer The latest reported value
     * @return startedAt Block timestamp when the latest successful round started
     * @return updatedAt Block timestamp of the latest successful round
     * @return answeredInRound The number of the latest round
     */
    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

File 29 of 51 : IChainlink.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

interface IChainlink {
    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

File 30 of 51 : ICreateX.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.4;

/**
 * @title CreateX Factory Interface Definition
 * @author pcaversaccio (https://web.archive.org/web/20230921103111/https://pcaversaccio.com/)
 * @custom:coauthor Matt Solomon (https://web.archive.org/web/20230921103335/https://mattsolomon.dev/)
 */
interface ICreateX {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                            TYPES                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    struct Values {
        uint256 constructorAmount;
        uint256 initCallAmount;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    event ContractCreation(address indexed newContract, bytes32 indexed salt);
    event ContractCreation(address indexed newContract);
    event Create3ProxyContractCreation(address indexed newContract, bytes32 indexed salt);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                        CUSTOM ERRORS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    error FailedContractCreation(address emitter);
    error FailedContractInitialisation(address emitter, bytes revertData);
    error InvalidSalt(address emitter);
    error InvalidNonceValue(address emitter);
    error FailedEtherTransfer(address emitter, bytes revertData);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           CREATE                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function deployCreate(bytes memory initCode) external payable returns (address newContract);

    function deployCreateAndInit(
        bytes memory initCode,
        bytes memory data,
        Values memory values,
        address refundAddress
    )
        external
        payable
        returns (address newContract);

    function deployCreateAndInit(
        bytes memory initCode,
        bytes memory data,
        Values memory values
    )
        external
        payable
        returns (address newContract);

    function deployCreateClone(address implementation, bytes memory data) external payable returns (address proxy);

    function computeCreateAddress(address deployer, uint256 nonce) external view returns (address computedAddress);

    function computeCreateAddress(uint256 nonce) external view returns (address computedAddress);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           CREATE2                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function deployCreate2(bytes32 salt, bytes memory initCode) external payable returns (address newContract);

    function deployCreate2(bytes memory initCode) external payable returns (address newContract);

    function deployCreate2AndInit(
        bytes32 salt,
        bytes memory initCode,
        bytes memory data,
        Values memory values,
        address refundAddress
    )
        external
        payable
        returns (address newContract);

    function deployCreate2AndInit(
        bytes32 salt,
        bytes memory initCode,
        bytes memory data,
        Values memory values
    )
        external
        payable
        returns (address newContract);

    function deployCreate2AndInit(
        bytes memory initCode,
        bytes memory data,
        Values memory values,
        address refundAddress
    )
        external
        payable
        returns (address newContract);

    function deployCreate2AndInit(
        bytes memory initCode,
        bytes memory data,
        Values memory values
    )
        external
        payable
        returns (address newContract);

    function deployCreate2Clone(
        bytes32 salt,
        address implementation,
        bytes memory data
    )
        external
        payable
        returns (address proxy);

    function deployCreate2Clone(address implementation, bytes memory data) external payable returns (address proxy);

    function computeCreate2Address(
        bytes32 salt,
        bytes32 initCodeHash,
        address deployer
    )
        external
        pure
        returns (address computedAddress);

    function computeCreate2Address(
        bytes32 salt,
        bytes32 initCodeHash
    )
        external
        view
        returns (address computedAddress);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           CREATE3                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function deployCreate3(bytes32 salt, bytes memory initCode) external payable returns (address newContract);

    function deployCreate3(bytes memory initCode) external payable returns (address newContract);

    function deployCreate3AndInit(
        bytes32 salt,
        bytes memory initCode,
        bytes memory data,
        Values memory values,
        address refundAddress
    )
        external
        payable
        returns (address newContract);

    function deployCreate3AndInit(
        bytes32 salt,
        bytes memory initCode,
        bytes memory data,
        Values memory values
    )
        external
        payable
        returns (address newContract);

    function deployCreate3AndInit(
        bytes memory initCode,
        bytes memory data,
        Values memory values,
        address refundAddress
    )
        external
        payable
        returns (address newContract);

    function deployCreate3AndInit(
        bytes memory initCode,
        bytes memory data,
        Values memory values
    )
        external
        payable
        returns (address newContract);

    function computeCreate3Address(bytes32 salt, address deployer) external pure returns (address computedAddress);

    function computeCreate3Address(bytes32 salt) external view returns (address computedAddress);
}

File 31 of 51 : IUniswapV3PoolImmutables.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token1() external view returns (address);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The pool tick spacing
    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
    /// This value is an int24 to avoid casting even though it is always positive.
    /// @return The tick spacing
    function tickSpacing() external view returns (int24);

    /// @notice The maximum amount of position liquidity that can use any tick in the range
    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
    /// @return The max amount of liquidity per tick
    function maxLiquidityPerTick() external view returns (uint128);
}

File 32 of 51 : IUniswapV3PoolState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
    /// when accessed externally.
    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
    /// tick The current tick of the pool, i.e. according to the last tick transition that was run.
    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
    /// boundary.
    /// observationIndex The index of the last oracle observation that was written,
    /// observationCardinality The current maximum number of observations stored in the pool,
    /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
    /// feeProtocol The protocol fee for both tokens of the pool.
    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
    /// unlocked Whether the pool is currently locked to reentrancy
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal0X128() external view returns (uint256);

    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal1X128() external view returns (uint256);

    /// @notice The amounts of token0 and token1 that are owed to the protocol
    /// @dev Protocol fees will never exceed uint128 max in either token
    function protocolFees() external view returns (uint128 token0, uint128 token1);

    /// @notice The currently in range liquidity available to the pool
    /// @dev This value has no relationship to the total liquidity across all ticks
    function liquidity() external view returns (uint128);

    /// @notice Look up information about a specific tick in the pool
    /// @param tick The tick to look up
    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
    /// tick upper,
    /// liquidityNet how much liquidity changes when the pool price crosses the tick,
    /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
    /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
    /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
    /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
    /// secondsOutside the seconds spent on the other side of the tick from the current tick,
    /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
    /// a specific position.
    function ticks(int24 tick)
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
    function tickBitmap(int16 wordPosition) external view returns (uint256);

    /// @notice Returns the information about a position by the position's key
    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
    /// @return _liquidity The amount of liquidity in the position,
    /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
    /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
    /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
    /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
    function positions(bytes32 key)
        external
        view
        returns (
            uint128 _liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    /// @notice Returns data about a specific observation index
    /// @param index The element of the observations array to fetch
    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
    /// ago, rather than at a specific index in the array.
    /// @return blockTimestamp The timestamp of the observation,
    /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
    /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
    /// Returns initialized whether the observation has been initialized and the values are safe to use
    function observations(uint256 index)
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );
}

File 33 of 51 : IUniswapV3PoolDerivedState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
    /// you must call it with secondsAgos = [3600, 0].
    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
    /// timestamp
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
    /// snapshot is taken and the second snapshot is taken.
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
        external
        view
        returns (
            int56 tickCumulativeInside,
            uint160 secondsPerLiquidityInsideX128,
            uint32 secondsInside
        );
}

File 34 of 51 : IUniswapV3PoolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;

    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
    /// on tickLower, tickUpper, the amount of liquidity, and the current price.
    /// @param recipient The address for which the liquidity will be created
    /// @param tickLower The lower tick of the position in which to add liquidity
    /// @param tickUpper The upper tick of the position in which to add liquidity
    /// @param amount The amount of liquidity to mint
    /// @param data Any data that should be passed through to the callback
    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
    function mint(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Collects tokens owed to a position
    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
    /// @param recipient The address which should receive the fees collected
    /// @param tickLower The lower tick of the position for which to collect fees
    /// @param tickUpper The upper tick of the position for which to collect fees
    /// @param amount0Requested How much token0 should be withdrawn from the fees owed
    /// @param amount1Requested How much token1 should be withdrawn from the fees owed
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
    /// @dev Fees must be collected separately via a call to #collect
    /// @param tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
    /// with 0 amount{0,1} and sending the donation amount(s) from the callback
    /// @param recipient The address which will receive the token0 and token1 amounts
    /// @param amount0 The amount of token0 to send
    /// @param amount1 The amount of token1 to send
    /// @param data Any data to be passed through to the callback
    function flash(
        address recipient,
        uint256 amount0,
        uint256 amount1,
        bytes calldata data
    ) external;

    /// @notice Increase the maximum number of price and liquidity observations that this pool will store
    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
    /// the input observationCardinalityNext.
    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}

File 35 of 51 : IUniswapV3PoolOwnerActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    /// @param feeProtocol0 new protocol fee for token0 of the pool
    /// @param feeProtocol1 new protocol fee for token1 of the pool
    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;

    /// @notice Collect the protocol fee accrued to the pool
    /// @param recipient The address to which collected protocol fees should be sent
    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
    /// @return amount0 The protocol fee collected in token0
    /// @return amount1 The protocol fee collected in token1
    function collectProtocol(
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);
}

File 36 of 51 : IUniswapV3PoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
    event Initialize(uint160 sqrtPriceX96, int24 tick);

    /// @notice Emitted when liquidity is minted for a given position
    /// @param sender The address that minted the liquidity
    /// @param owner The owner of the position and recipient of any minted liquidity
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity minted to the position range
    /// @param amount0 How much token0 was required for the minted liquidity
    /// @param amount1 How much token1 was required for the minted liquidity
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted when fees are collected by the owner of a position
    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
    /// @param owner The owner of the position for which fees are collected
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount0 The amount of token0 fees collected
    /// @param amount1 The amount of token1 fees collected
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );

    /// @notice Emitted when a position's liquidity is removed
    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
    /// @param owner The owner of the position for which liquidity is removed
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity to remove
    /// @param amount0 The amount of token0 withdrawn
    /// @param amount1 The amount of token1 withdrawn
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted by the pool for any swaps between token0 and token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the output of the swap
    /// @param amount0 The delta of the token0 balance of the pool
    /// @param amount1 The delta of the token1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of price of the pool after the swap
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick
    );

    /// @notice Emitted by the pool for any flashes of token0/token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the tokens from flash
    /// @param amount0 The amount of token0 that was flashed
    /// @param amount1 The amount of token1 that was flashed
    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );

    /// @notice Emitted by the pool for increases to the number of observations that can be stored
    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
    /// just before a mint/swap/burn.
    /// @param observationCardinalityNextOld The previous value of the next observation cardinality
    /// @param observationCardinalityNextNew The updated value of the next observation cardinality
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld,
        uint16 observationCardinalityNextNew
    );

    /// @notice Emitted when the protocol fee is changed by the pool
    /// @param feeProtocol0Old The previous value of the token0 protocol fee
    /// @param feeProtocol1Old The previous value of the token1 protocol fee
    /// @param feeProtocol0New The updated value of the token0 protocol fee
    /// @param feeProtocol1New The updated value of the token1 protocol fee
    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);

    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
    /// @param sender The address that collects the protocol fees
    /// @param recipient The address that receives the collected protocol fees
    /// @param amount0 The amount of token0 protocol fees that is withdrawn
    /// @param amount0 The amount of token1 protocol fees that is withdrawn
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}

File 37 of 51 : 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 38 of 51 : 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 39 of 51 : 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 40 of 51 : IYieldOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

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

File 41 of 51 : 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 42 of 51 : 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 43 of 51 : 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 44 of 51 : 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 45 of 51 : 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 46 of 51 : 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 47 of 51 : 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 48 of 51 : 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 49 of 51 : 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 50 of 51 : 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 51 of 51 : 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/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 300
  },
  "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":[{"internalType":"uint8","name":"_ilkIndex","type":"uint8"},{"internalType":"contract IonPool","name":"_ionPool","type":"address"},{"internalType":"contract GemJoin","name":"_gemJoin","type":"address"},{"internalType":"contract Whitelist","name":"_whitelist","type":"address"},{"internalType":"contract IUniswapV3Pool","name":"_wstEthUniswapPool","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"unauthorizedCaller","type":"address"}],"name":"CallbackOnlyCallableByPool","type":"error"},{"inputs":[],"name":"CannotSendEthToContract","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[{"internalType":"uint256","name":"repaymentAmount","type":"uint256"},{"internalType":"uint256","name":"maxRepaymentAmount","type":"uint256"}],"name":"FlashloanRepaymentTooExpensive","type":"error"},{"inputs":[],"name":"InvalidUniswapPool","type":"error"},{"inputs":[],"name":"InvalidZeroLiquidityRegionSwap","type":"error"},{"inputs":[],"name":"MathOverflowedMulDiv","type":"error"},{"inputs":[{"internalType":"uint256","name":"amountReceived","type":"uint256"},{"internalType":"uint256","name":"amountRequired","type":"uint256"}],"name":"OutputAmountNotReceived","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":"uint256","name":"deadline","type":"uint256"}],"name":"TransactionDeadlineReached","type":"error"},{"inputs":[],"name":"BASE","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ILK_INDEX","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"JOIN","outputs":[{"internalType":"contract GemJoin","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LST_TOKEN","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MINT_ASSET","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"POOL","outputs":[{"internalType":"contract IonPool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UNISWAP_POOL","outputs":[{"internalType":"contract IUniswapV3Pool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WETH","outputs":[{"internalType":"contract IWETH9","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WHITELIST","outputs":[{"internalType":"contract Whitelist","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountCollateral","type":"uint256"},{"internalType":"uint256","name":"amountToBorrow","type":"uint256"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"}],"name":"depositAndBorrow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"initialDeposit","type":"uint256"},{"internalType":"uint256","name":"resultingAdditionalCollateral","type":"uint256"},{"internalType":"uint256","name":"maxResultingDebt","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"}],"name":"flashswapAndMint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"debtToRepay","type":"uint256"},{"internalType":"uint256","name":"collateralToWithdraw","type":"uint256"}],"name":"repayAndWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"collateralToWithdraw","type":"uint256"}],"name":"repayFullAndWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"int256","name":"amount0Delta","type":"int256"},{"internalType":"int256","name":"amount1Delta","type":"int256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"uniswapV3SwapCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

6101c060405234801562000011575f80fd5b5060405162002597380380620025978339810160408190526200003491620004c7565b6001600160a01b03841660e081905260ff861660c05260408051636f307dc360e01b81529051839273c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2928992899289928992636f307dc3916004808201926020929091908290030181865afa158015620000a4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620000ca919062000547565b6001600160a01b0390811660805273c02aaa39b223fe8d0a0e5c4f27ead9083c756cc260a081905260e05160405163efff005f60e01b815260ff8816600482015291925f9291169063efff005f90602401602060405180830381865afa15801562000137573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200015d919062000547565b6001600160a01b0381811661012052858116610100528481166101405260805160405163095ea7b360e01b815288831660048201525f196024820152929350169063095ea7b3906044016020604051808303815f875af1158015620001c4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620001ea91906200056c565b5060405163095ea7b360e01b81526001600160a01b0385811660048301525f19602483015282169063095ea7b3906044016020604051808303815f875af115801562000238573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200025e91906200056c565b5050506001600160a01b03861693506200028f92505050576040516312a5c13d60e31b815260040160405180910390fd5b806001600160a01b0316610180816001600160a01b0316815250505f826001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa158015620002e8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200030e919062000547565b90505f836001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa1580156200034e573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000374919062000547565b9050610180516001600160a01b0316826001600160a01b031614158015620003b15750610180516001600160a01b0316816001600160a01b031614155b15620003d0576040516312a5c13d60e31b815260040160405180910390fd5b610180516001600160a01b0316826001600160a01b0316148015620004095750610180516001600160a01b0316816001600160a01b0316145b1562000428576040516312a5c13d60e31b815260040160405180910390fd5b6001600160a01b0380851661016052610180518382169116146200044d575f62000450565b60015b15156101a08190525f9062000466578262000468565b815b90506080516001600160a01b0316816001600160a01b0316146200049f576040516312a5c13d60e31b815260040160405180910390fd5b505050505050505050506200058d565b6001600160a01b0381168114620004c4575f80fd5b50565b5f805f805f60a08688031215620004dc575f80fd5b855160ff81168114620004ed575f80fd5b60208701519095506200050081620004af565b60408701519094506200051381620004af565b60608701519093506200052681620004af565b60808701519092506200053981620004af565b809150509295509295909350565b5f6020828403121562000558575f80fd5b81516200056581620004af565b9392505050565b5f602082840312156200057d575f80fd5b8151801515811462000565575f80fd5b60805160a05160c05160e05161010051610120516101405161016051610180516101a051611e9e620006f95f395f81816108e50152610a3d01525f61028601525f818161017c01528181610864015261138a01525f818161012c015281816103c9015261051d01525f81816101ce0152818161049a01526105c701525f8181610234015281816107b701528181610aef01526111d001525f8181610201015281816106940152818161073c01528181610b5601528181610c5d01528181610d1101528181610e2101528181610ed501528181610fd1015281816110a7015261115301525f818161035d015281816103f60152818161054c0152818161065a0152818161070201528181610b8101528181610c3401528181610d3801528181610dec01528181610e9b01528181610fa801528181611060015261110f01525f81816102b9015261124901525f818161032a0152818161062101528181610821015261090e0152611e9e5ff3fe6080604052600436106100dc575f3560e01c8063a424bf771161007c578063ebc9b94d11610057578063ebc9b94d146102fa578063ec342ad014610319578063ed0cee971461034c578063fa461e3314610391575f80fd5b8063a424bf7714610275578063ad5c4648146102a8578063e54a55b6146102db575f80fd5b806350c6cf88116100b757806350c6cf88146101bd5780637535d246146101f05780637f9681481461022357806396c7525914610256575f80fd5b80631bb7cc991461011b5780631d6105771461016b5780634f4f58d61461019e575f80fd5b36610117573373c02aaa39b223fe8d0a0e5c4f27ead9083c756cc21461011557604051637c56635360e01b815260040160405180910390fd5b005b5f80fd5b348015610126575f80fd5b5061014e7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020015b60405180910390f35b348015610176575f80fd5b5061014e7f000000000000000000000000000000000000000000000000000000000000000081565b3480156101a9575f80fd5b506101156101b836600461193d565b6103b0565b3480156101c8575f80fd5b5061014e7f000000000000000000000000000000000000000000000000000000000000000081565b3480156101fb575f80fd5b5061014e7f000000000000000000000000000000000000000000000000000000000000000081565b34801561022e575f80fd5b5061014e7f000000000000000000000000000000000000000000000000000000000000000081565b348015610261575f80fd5b50610115610270366004611a1d565b6104d6565b348015610280575f80fd5b5061014e7f000000000000000000000000000000000000000000000000000000000000000081565b3480156102b3575f80fd5b5061014e7f000000000000000000000000000000000000000000000000000000000000000081565b3480156102e6575f80fd5b506101156102f5366004611a99565b610604565b348015610305575f80fd5b50610115610314366004611ab0565b610814565b348015610324575f80fd5b5061014e7f000000000000000000000000000000000000000000000000000000000000000081565b348015610357575f80fd5b5061037f7f000000000000000000000000000000000000000000000000000000000000000081565b60405160ff9091168152602001610162565b34801561039c575f80fd5b506101156103ab366004611ad0565b610859565b60405163b5406b3d60e01b815281906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063b5406b3d90610424907f000000000000000000000000000000000000000000000000000000000000000090339081908790600401611b73565b602060405180830381865afa15801561043f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104639190611ba7565b508242811161048d5760405163356dfb6f60e01b8152600481018290526024015b60405180910390fd5b6104c26001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001633308a61099f565b6104cd878787610a0c565b50505050505050565b8181808060200260200160405190810160405280939291908181526020018383602002808284375f920191909152505060405163b5406b3d60e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016925063b5406b3d915061057a907f000000000000000000000000000000000000000000000000000000000000000090339081908790600401611b73565b602060405180830381865afa158015610595573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105b99190611ba7565b506105ef6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001633308861099f565b6105fd333387876001610ad3565b5050505050565b5f8061060f33610ddb565b90925090506106496001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001633308561099f565b604051638459b43760e01b815260ff7f0000000000000000000000000000000000000000000000000000000000000000166004820152336024820152306044820152606481018290527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690638459b437906084015f604051808303815f87803b1580156106dd575f80fd5b505af11580156106ef573d5f803e3d5ffd5b5050604051631d0fe70360e21b815260ff7f0000000000000000000000000000000000000000000000000000000000000000166004820152336024820152306044820152606481018690527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316925063743f9c0c91506084015f604051808303815f87803b158015610787575f80fd5b505af1158015610799573d5f803e3d5ffd5b505060405163ef693bed60e01b8152336004820152602481018690527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316925063ef693bed91506044015f604051808303815f87803b158015610802575f80fd5b505af11580156104cd573d5f803e3d5ffd5b6108496001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001633308561099f565b61085533338385610f97565b5050565b336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146108a4576040516390d9465960e01b8152336004820152602401610484565b831580156108b0575082155b156108ce57604051631306fb0560e21b815260040160405180910390fd5b5f80806108dd84860186611bc6565b9250925092507f000000000000000000000000000000000000000000000000000000000000000061090c579495945b7f00000000000000000000000000000000000000000000000000000000000000005f8812801561093b57505f87135b61094757610947611c03565b5f6109596109548a611c2b565b611231565b9050836109668483611c45565b1461097357610973611c03565b6109808530868b5f610ad3565b6109946001600160a01b038316338a6112cf565b505050505050505050565b6040516001600160a01b038481166024830152838116604483015260648201839052610a069186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050611305565b50505050565b5f610a178484611c58565b90505f610a2382611366565b9050805f03610a3a576105fd3330865f6001610ad3565b5f7f0000000000000000000000000000000000000000000000000000000000000000610a67576001610a69565b5f5b60408051336020820152908101879052606081018890529091505f90610aa690839085903090608001604051602081830303815290604052611385565b9050848111156104cd57604051634245776b60e11b81526004810184905260248101869052604401610484565b604051633b4da69f60e01b8152306004820152602481018490527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690633b4da69f906044015f604051808303815f87803b158015610b38575f80fd5b505af1158015610b4a573d5f803e3d5ffd5b50506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016915063918a2f4290507f00000000000000000000000000000000000000000000000000000000000000008730875f604051908082528060200260200182016040528015610bcd578160200160208202803683370190505b506040518663ffffffff1660e01b8152600401610bee959493929190611c6b565b5f604051808303815f87803b158015610c05575f80fd5b505af1158015610c17573d5f803e3d5ffd5b50505050815f03156105fd57604051633c04b54760e01b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690633c04b54790602401602060405180830381865afa158015610caa573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cce9190611cb0565b90505f80836001811115610ce457610ce4611cc7565b03610cfa57610cf384836114c1565b9050610d07565b610d0484836114e2565b90505b6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016639306f2f87f00000000000000000000000000000000000000000000000000000000000000008989855f604051908082528060200260200182016040528015610d84578160200160208202803683370190505b506040518663ffffffff1660e01b8152600401610da5959493929190611c6b565b5f604051808303815f87803b158015610dbc575f80fd5b505af1158015610dce573d5f803e3d5ffd5b5050505050505050505050565b604051633c04b54760e01b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201525f90819081906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690633c04b54790602401602060405180830381865afa158015610e66573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e8a9190611cb0565b604051632bfe485960e11b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201526001600160a01b0386811660248301529192507f0000000000000000000000000000000000000000000000000000000000000000909116906357fc90b290604401602060405180830381865afa158015610f1c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f409190611cb0565b91505f610f4d8284611cdb565b9050610f656b033b2e3c9fd0803ce800000082611d06565b93505f610f7e6b033b2e3c9fd0803ce800000083611d19565b1115610f9057610f8d84611d2c565b93505b5050915091565b604051633c04b54760e01b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690633c04b54790602401602060405180830381865afa15801561101e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110429190611cb0565b90505f61104f83836114e2565b604051638459b43760e01b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201526001600160a01b038881166024830152306044830152606482018390529192507f000000000000000000000000000000000000000000000000000000000000000090911690638459b437906084015f604051808303815f87803b1580156110ea575f80fd5b505af11580156110fc573d5f803e3d5ffd5b5050604051631d0fe70360e21b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201526001600160a01b038981166024830152306044830152606482018890527f000000000000000000000000000000000000000000000000000000000000000016925063743f9c0c91506084015f604051808303815f87803b158015611196575f80fd5b505af11580156111a8573d5f803e3d5ffd5b505060405163ef693bed60e01b81526001600160a01b038881166004830152602482018890527f000000000000000000000000000000000000000000000000000000000000000016925063ef693bed91506044015f604051808303815f87803b158015611213575f80fd5b505af1158015611225573d5f803e3d5ffd5b50505050505050505050565b604051632e1a7d4d60e01b8152600481018290525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690632e1a7d4d906024015f604051808303815f87803b158015611292575f80fd5b505af11580156112a4573d5f803e3d5ffd5b506112c9925073a1290d69c65a6fe4df752f95823fae25cb99e5a791508490506114fa565b92915050565b6040516001600160a01b0383811660248301526044820183905261130091859182169063a9059cbb906064016109d4565b505050565b5f6113196001600160a01b0384168361160a565b905080515f1415801561133d57508080602001905181019061133b9190611ba7565b155b1561130057604051635274afe760e01b81526001600160a01b0384166004820152602401610484565b5f6112c973a1290d69c65a6fe4df752f95823fae25cb99e5a783611617565b5f805f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663128acb0886896113c28a6116a1565b6113cb90611c2b565b8b6113f4576113ef600173fffd8963efd1fc6a506488495d951d5263988d26611d44565b611404565b6114046401000276a36001611d6b565b896040518663ffffffff1660e01b8152600401611425959493929190611dad565b60408051808303815f875af1158015611440573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114649190611e0a565b915091505f8761147d578161147884611c2b565b611487565b8261148783611c2b565b90945090508681146114b65760405163c6b1474760e01b81526004810182905260248101889052604401610484565b505050949350505050565b5f6114db836b033b2e3c9fd0803ce80000008460016116d1565b9392505050565b5f6114db836b033b2e3c9fd0803ce800000084611720565b604051635d2dda2160e11b815273eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6004820152602481018290525f9073036676389e48133b63a802f8635ad39e752d375d9063ba5bb44290604401602060405180830381865afa158015611564573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115889190611cb0565b6040516372c51c0b60e01b815290915073036676389e48133b63a802f8635ad39e752d375d906372c51c0b9084906115d6905f906004019081526040602082018190525f9082015260600190565b5f604051808303818588803b1580156115ed575f80fd5b505af11580156115ff573d5f803e3d5ffd5b505050505092915050565b60606114db83835f6117df565b5f6114db73349a73444b1a310bae67ef67973022020d70020d6001600160a01b031663b4b464346040518163ffffffff1660e01b8152600401602060405180830381865afa15801561166b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061168f9190611cb0565b8390670de0b6b3a764000060016116d1565b5f6001600160ff1b038211156116cd5760405163123baf0360e11b815260048101839052602401610484565b5090565b5f806116de868686611720565b90506116e983611878565b801561170457505f84806116ff576116ff611cf2565b868809115b1561171757611714600182611c45565b90505b95945050505050565b5f838302815f1985870982811083820303915050805f036117545783828161174a5761174a611cf2565b04925050506114db565b8084116117745760405163227bc15360e01b815260040160405180910390fd5b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b6060814710156118045760405163cd78605960e01b8152306004820152602401610484565b5f80856001600160a01b0316848660405161181f9190611e2c565b5f6040518083038185875af1925050503d805f8114611859576040519150601f19603f3d011682016040523d82523d5f602084013e61185e565b606091505b509150915061186e8683836118a4565b9695505050505050565b5f600282600381111561188d5761188d611cc7565b6118979190611e47565b60ff166001149050919050565b6060826118b9576118b482611900565b6114db565b81511580156118d057506001600160a01b0384163b155b156118f957604051639996b31560e01b81526001600160a01b0385166004820152602401610484565b50806114db565b8051156119105780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b634e487b7160e01b5f52604160045260245ffd5b5f805f805f60a08688031215611951575f80fd5b8535945060208087013594506040870135935060608701359250608087013567ffffffffffffffff80821115611985575f80fd5b818901915089601f830112611998575f80fd5b8135818111156119aa576119aa611929565b8060051b604051601f19603f830116810181811085821117156119cf576119cf611929565b60405291825284820192508381018501918c8311156119ec575f80fd5b938501935b82851015611a0a578435845293850193928501926119f1565b8096505050505050509295509295909350565b5f805f8060608587031215611a30575f80fd5b8435935060208501359250604085013567ffffffffffffffff80821115611a55575f80fd5b818701915087601f830112611a68575f80fd5b813581811115611a76575f80fd5b8860208260051b8501011115611a8a575f80fd5b95989497505060200194505050565b5f60208284031215611aa9575f80fd5b5035919050565b5f8060408385031215611ac1575f80fd5b50508035926020909101359150565b5f805f8060608587031215611ae3575f80fd5b8435935060208501359250604085013567ffffffffffffffff80821115611b08575f80fd5b818701915087601f830112611b1b575f80fd5b813581811115611b29575f80fd5b886020828501011115611a8a575f80fd5b5f8151808452602080850194508084015f5b83811015611b6857815187529582019590820190600101611b4c565b509495945050505050565b60ff851681525f6001600160a01b0380861660208401528085166040840152506080606083015261186e6080830184611b3a565b5f60208284031215611bb7575f80fd5b815180151581146114db575f80fd5b5f805f60608486031215611bd8575f80fd5b83356001600160a01b0381168114611bee575f80fd5b95602085013595506040909401359392505050565b634e487b7160e01b5f52600160045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b5f600160ff1b8201611c3f57611c3f611c17565b505f0390565b808201808211156112c9576112c9611c17565b818103818111156112c9576112c9611c17565b60ff861681525f6001600160a01b03808716602084015280861660408401525083606083015260a06080830152611ca560a0830184611b3a565b979650505050505050565b5f60208284031215611cc0575f80fd5b5051919050565b634e487b7160e01b5f52602160045260245ffd5b80820281158282048414176112c9576112c9611c17565b634e487b7160e01b5f52601260045260245ffd5b5f82611d1457611d14611cf2565b500490565b5f82611d2757611d27611cf2565b500690565b5f60018201611d3d57611d3d611c17565b5060010190565b6001600160a01b03828116828216039080821115611d6457611d64611c17565b5092915050565b6001600160a01b03818116838216019080821115611d6457611d64611c17565b5f5b83811015611da5578181015183820152602001611d8d565b50505f910152565b5f6001600160a01b038088168352861515602084015285604084015280851660608401525060a0608083015282518060a0840152611df28160c0850160208701611d8b565b601f01601f19169190910160c0019695505050505050565b5f8060408385031215611e1b575f80fd5b505080516020909101519092909150565b5f8251611e3d818460208701611d8b565b9190910192915050565b5f60ff831680611e5957611e59611cf2565b8060ff8416069150509291505056fea2646970667358221220e7d462d153202b82b7949143fc986b1aed8d88f3296888c9b603017d53210dfe64736f6c6343000815003300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e33e35ee6052fae87bfcfac61b1da90000000000000000000000003bc3ac09d1ee05393f2848d82cb420f3479544320000000000000000000000007e317f99aa313669aacdd8db3927ff3acb562dad000000000000000000000000109830a1aaad605bbf02a9dfa7b0b92ec2fb7daa

Deployed Bytecode

0x6080604052600436106100dc575f3560e01c8063a424bf771161007c578063ebc9b94d11610057578063ebc9b94d146102fa578063ec342ad014610319578063ed0cee971461034c578063fa461e3314610391575f80fd5b8063a424bf7714610275578063ad5c4648146102a8578063e54a55b6146102db575f80fd5b806350c6cf88116100b757806350c6cf88146101bd5780637535d246146101f05780637f9681481461022357806396c7525914610256575f80fd5b80631bb7cc991461011b5780631d6105771461016b5780634f4f58d61461019e575f80fd5b36610117573373c02aaa39b223fe8d0a0e5c4f27ead9083c756cc21461011557604051637c56635360e01b815260040160405180910390fd5b005b5f80fd5b348015610126575f80fd5b5061014e7f0000000000000000000000007e317f99aa313669aacdd8db3927ff3acb562dad81565b6040516001600160a01b0390911681526020015b60405180910390f35b348015610176575f80fd5b5061014e7f000000000000000000000000109830a1aaad605bbf02a9dfa7b0b92ec2fb7daa81565b3480156101a9575f80fd5b506101156101b836600461193d565b6103b0565b3480156101c8575f80fd5b5061014e7f000000000000000000000000a1290d69c65a6fe4df752f95823fae25cb99e5a781565b3480156101fb575f80fd5b5061014e7f0000000000000000000000000000000000e33e35ee6052fae87bfcfac61b1da981565b34801561022e575f80fd5b5061014e7f0000000000000000000000003bc3ac09d1ee05393f2848d82cb420f34795443281565b348015610261575f80fd5b50610115610270366004611a1d565b6104d6565b348015610280575f80fd5b5061014e7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b3480156102b3575f80fd5b5061014e7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b3480156102e6575f80fd5b506101156102f5366004611a99565b610604565b348015610305575f80fd5b50610115610314366004611ab0565b610814565b348015610324575f80fd5b5061014e7f0000000000000000000000007f39c581f595b53c5cb19bd0b3f8da6c935e2ca081565b348015610357575f80fd5b5061037f7f000000000000000000000000000000000000000000000000000000000000000081565b60405160ff9091168152602001610162565b34801561039c575f80fd5b506101156103ab366004611ad0565b610859565b60405163b5406b3d60e01b815281906001600160a01b037f0000000000000000000000007e317f99aa313669aacdd8db3927ff3acb562dad169063b5406b3d90610424907f000000000000000000000000000000000000000000000000000000000000000090339081908790600401611b73565b602060405180830381865afa15801561043f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104639190611ba7565b508242811161048d5760405163356dfb6f60e01b8152600481018290526024015b60405180910390fd5b6104c26001600160a01b037f000000000000000000000000a1290d69c65a6fe4df752f95823fae25cb99e5a71633308a61099f565b6104cd878787610a0c565b50505050505050565b8181808060200260200160405190810160405280939291908181526020018383602002808284375f920191909152505060405163b5406b3d60e01b81526001600160a01b037f0000000000000000000000007e317f99aa313669aacdd8db3927ff3acb562dad16925063b5406b3d915061057a907f000000000000000000000000000000000000000000000000000000000000000090339081908790600401611b73565b602060405180830381865afa158015610595573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105b99190611ba7565b506105ef6001600160a01b037f000000000000000000000000a1290d69c65a6fe4df752f95823fae25cb99e5a71633308861099f565b6105fd333387876001610ad3565b5050505050565b5f8061060f33610ddb565b90925090506106496001600160a01b037f0000000000000000000000007f39c581f595b53c5cb19bd0b3f8da6c935e2ca01633308561099f565b604051638459b43760e01b815260ff7f0000000000000000000000000000000000000000000000000000000000000000166004820152336024820152306044820152606481018290527f0000000000000000000000000000000000e33e35ee6052fae87bfcfac61b1da96001600160a01b031690638459b437906084015f604051808303815f87803b1580156106dd575f80fd5b505af11580156106ef573d5f803e3d5ffd5b5050604051631d0fe70360e21b815260ff7f0000000000000000000000000000000000000000000000000000000000000000166004820152336024820152306044820152606481018690527f0000000000000000000000000000000000e33e35ee6052fae87bfcfac61b1da96001600160a01b0316925063743f9c0c91506084015f604051808303815f87803b158015610787575f80fd5b505af1158015610799573d5f803e3d5ffd5b505060405163ef693bed60e01b8152336004820152602481018690527f0000000000000000000000003bc3ac09d1ee05393f2848d82cb420f3479544326001600160a01b0316925063ef693bed91506044015f604051808303815f87803b158015610802575f80fd5b505af11580156104cd573d5f803e3d5ffd5b6108496001600160a01b037f0000000000000000000000007f39c581f595b53c5cb19bd0b3f8da6c935e2ca01633308561099f565b61085533338385610f97565b5050565b336001600160a01b037f000000000000000000000000109830a1aaad605bbf02a9dfa7b0b92ec2fb7daa16146108a4576040516390d9465960e01b8152336004820152602401610484565b831580156108b0575082155b156108ce57604051631306fb0560e21b815260040160405180910390fd5b5f80806108dd84860186611bc6565b9250925092507f000000000000000000000000000000000000000000000000000000000000000061090c579495945b7f0000000000000000000000007f39c581f595b53c5cb19bd0b3f8da6c935e2ca05f8812801561093b57505f87135b61094757610947611c03565b5f6109596109548a611c2b565b611231565b9050836109668483611c45565b1461097357610973611c03565b6109808530868b5f610ad3565b6109946001600160a01b038316338a6112cf565b505050505050505050565b6040516001600160a01b038481166024830152838116604483015260648201839052610a069186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050611305565b50505050565b5f610a178484611c58565b90505f610a2382611366565b9050805f03610a3a576105fd3330865f6001610ad3565b5f7f0000000000000000000000000000000000000000000000000000000000000000610a67576001610a69565b5f5b60408051336020820152908101879052606081018890529091505f90610aa690839085903090608001604051602081830303815290604052611385565b9050848111156104cd57604051634245776b60e11b81526004810184905260248101869052604401610484565b604051633b4da69f60e01b8152306004820152602481018490527f0000000000000000000000003bc3ac09d1ee05393f2848d82cb420f3479544326001600160a01b031690633b4da69f906044015f604051808303815f87803b158015610b38575f80fd5b505af1158015610b4a573d5f803e3d5ffd5b50506001600160a01b037f0000000000000000000000000000000000e33e35ee6052fae87bfcfac61b1da916915063918a2f4290507f00000000000000000000000000000000000000000000000000000000000000008730875f604051908082528060200260200182016040528015610bcd578160200160208202803683370190505b506040518663ffffffff1660e01b8152600401610bee959493929190611c6b565b5f604051808303815f87803b158015610c05575f80fd5b505af1158015610c17573d5f803e3d5ffd5b50505050815f03156105fd57604051633c04b54760e01b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201525f907f0000000000000000000000000000000000e33e35ee6052fae87bfcfac61b1da96001600160a01b031690633c04b54790602401602060405180830381865afa158015610caa573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cce9190611cb0565b90505f80836001811115610ce457610ce4611cc7565b03610cfa57610cf384836114c1565b9050610d07565b610d0484836114e2565b90505b6001600160a01b037f0000000000000000000000000000000000e33e35ee6052fae87bfcfac61b1da916639306f2f87f00000000000000000000000000000000000000000000000000000000000000008989855f604051908082528060200260200182016040528015610d84578160200160208202803683370190505b506040518663ffffffff1660e01b8152600401610da5959493929190611c6b565b5f604051808303815f87803b158015610dbc575f80fd5b505af1158015610dce573d5f803e3d5ffd5b5050505050505050505050565b604051633c04b54760e01b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201525f90819081906001600160a01b037f0000000000000000000000000000000000e33e35ee6052fae87bfcfac61b1da91690633c04b54790602401602060405180830381865afa158015610e66573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e8a9190611cb0565b604051632bfe485960e11b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201526001600160a01b0386811660248301529192507f0000000000000000000000000000000000e33e35ee6052fae87bfcfac61b1da9909116906357fc90b290604401602060405180830381865afa158015610f1c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f409190611cb0565b91505f610f4d8284611cdb565b9050610f656b033b2e3c9fd0803ce800000082611d06565b93505f610f7e6b033b2e3c9fd0803ce800000083611d19565b1115610f9057610f8d84611d2c565b93505b5050915091565b604051633c04b54760e01b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201525f907f0000000000000000000000000000000000e33e35ee6052fae87bfcfac61b1da96001600160a01b031690633c04b54790602401602060405180830381865afa15801561101e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110429190611cb0565b90505f61104f83836114e2565b604051638459b43760e01b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201526001600160a01b038881166024830152306044830152606482018390529192507f0000000000000000000000000000000000e33e35ee6052fae87bfcfac61b1da990911690638459b437906084015f604051808303815f87803b1580156110ea575f80fd5b505af11580156110fc573d5f803e3d5ffd5b5050604051631d0fe70360e21b815260ff7f00000000000000000000000000000000000000000000000000000000000000001660048201526001600160a01b038981166024830152306044830152606482018890527f0000000000000000000000000000000000e33e35ee6052fae87bfcfac61b1da916925063743f9c0c91506084015f604051808303815f87803b158015611196575f80fd5b505af11580156111a8573d5f803e3d5ffd5b505060405163ef693bed60e01b81526001600160a01b038881166004830152602482018890527f0000000000000000000000003bc3ac09d1ee05393f2848d82cb420f34795443216925063ef693bed91506044015f604051808303815f87803b158015611213575f80fd5b505af1158015611225573d5f803e3d5ffd5b50505050505050505050565b604051632e1a7d4d60e01b8152600481018290525f907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031690632e1a7d4d906024015f604051808303815f87803b158015611292575f80fd5b505af11580156112a4573d5f803e3d5ffd5b506112c9925073a1290d69c65a6fe4df752f95823fae25cb99e5a791508490506114fa565b92915050565b6040516001600160a01b0383811660248301526044820183905261130091859182169063a9059cbb906064016109d4565b505050565b5f6113196001600160a01b0384168361160a565b905080515f1415801561133d57508080602001905181019061133b9190611ba7565b155b1561130057604051635274afe760e01b81526001600160a01b0384166004820152602401610484565b5f6112c973a1290d69c65a6fe4df752f95823fae25cb99e5a783611617565b5f805f7f000000000000000000000000109830a1aaad605bbf02a9dfa7b0b92ec2fb7daa6001600160a01b031663128acb0886896113c28a6116a1565b6113cb90611c2b565b8b6113f4576113ef600173fffd8963efd1fc6a506488495d951d5263988d26611d44565b611404565b6114046401000276a36001611d6b565b896040518663ffffffff1660e01b8152600401611425959493929190611dad565b60408051808303815f875af1158015611440573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114649190611e0a565b915091505f8761147d578161147884611c2b565b611487565b8261148783611c2b565b90945090508681146114b65760405163c6b1474760e01b81526004810182905260248101889052604401610484565b505050949350505050565b5f6114db836b033b2e3c9fd0803ce80000008460016116d1565b9392505050565b5f6114db836b033b2e3c9fd0803ce800000084611720565b604051635d2dda2160e11b815273eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6004820152602481018290525f9073036676389e48133b63a802f8635ad39e752d375d9063ba5bb44290604401602060405180830381865afa158015611564573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115889190611cb0565b6040516372c51c0b60e01b815290915073036676389e48133b63a802f8635ad39e752d375d906372c51c0b9084906115d6905f906004019081526040602082018190525f9082015260600190565b5f604051808303818588803b1580156115ed575f80fd5b505af11580156115ff573d5f803e3d5ffd5b505050505092915050565b60606114db83835f6117df565b5f6114db73349a73444b1a310bae67ef67973022020d70020d6001600160a01b031663b4b464346040518163ffffffff1660e01b8152600401602060405180830381865afa15801561166b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061168f9190611cb0565b8390670de0b6b3a764000060016116d1565b5f6001600160ff1b038211156116cd5760405163123baf0360e11b815260048101839052602401610484565b5090565b5f806116de868686611720565b90506116e983611878565b801561170457505f84806116ff576116ff611cf2565b868809115b1561171757611714600182611c45565b90505b95945050505050565b5f838302815f1985870982811083820303915050805f036117545783828161174a5761174a611cf2565b04925050506114db565b8084116117745760405163227bc15360e01b815260040160405180910390fd5b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b6060814710156118045760405163cd78605960e01b8152306004820152602401610484565b5f80856001600160a01b0316848660405161181f9190611e2c565b5f6040518083038185875af1925050503d805f8114611859576040519150601f19603f3d011682016040523d82523d5f602084013e61185e565b606091505b509150915061186e8683836118a4565b9695505050505050565b5f600282600381111561188d5761188d611cc7565b6118979190611e47565b60ff166001149050919050565b6060826118b9576118b482611900565b6114db565b81511580156118d057506001600160a01b0384163b155b156118f957604051639996b31560e01b81526001600160a01b0385166004820152602401610484565b50806114db565b8051156119105780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b634e487b7160e01b5f52604160045260245ffd5b5f805f805f60a08688031215611951575f80fd5b8535945060208087013594506040870135935060608701359250608087013567ffffffffffffffff80821115611985575f80fd5b818901915089601f830112611998575f80fd5b8135818111156119aa576119aa611929565b8060051b604051601f19603f830116810181811085821117156119cf576119cf611929565b60405291825284820192508381018501918c8311156119ec575f80fd5b938501935b82851015611a0a578435845293850193928501926119f1565b8096505050505050509295509295909350565b5f805f8060608587031215611a30575f80fd5b8435935060208501359250604085013567ffffffffffffffff80821115611a55575f80fd5b818701915087601f830112611a68575f80fd5b813581811115611a76575f80fd5b8860208260051b8501011115611a8a575f80fd5b95989497505060200194505050565b5f60208284031215611aa9575f80fd5b5035919050565b5f8060408385031215611ac1575f80fd5b50508035926020909101359150565b5f805f8060608587031215611ae3575f80fd5b8435935060208501359250604085013567ffffffffffffffff80821115611b08575f80fd5b818701915087601f830112611b1b575f80fd5b813581811115611b29575f80fd5b886020828501011115611a8a575f80fd5b5f8151808452602080850194508084015f5b83811015611b6857815187529582019590820190600101611b4c565b509495945050505050565b60ff851681525f6001600160a01b0380861660208401528085166040840152506080606083015261186e6080830184611b3a565b5f60208284031215611bb7575f80fd5b815180151581146114db575f80fd5b5f805f60608486031215611bd8575f80fd5b83356001600160a01b0381168114611bee575f80fd5b95602085013595506040909401359392505050565b634e487b7160e01b5f52600160045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b5f600160ff1b8201611c3f57611c3f611c17565b505f0390565b808201808211156112c9576112c9611c17565b818103818111156112c9576112c9611c17565b60ff861681525f6001600160a01b03808716602084015280861660408401525083606083015260a06080830152611ca560a0830184611b3a565b979650505050505050565b5f60208284031215611cc0575f80fd5b5051919050565b634e487b7160e01b5f52602160045260245ffd5b80820281158282048414176112c9576112c9611c17565b634e487b7160e01b5f52601260045260245ffd5b5f82611d1457611d14611cf2565b500490565b5f82611d2757611d27611cf2565b500690565b5f60018201611d3d57611d3d611c17565b5060010190565b6001600160a01b03828116828216039080821115611d6457611d64611c17565b5092915050565b6001600160a01b03818116838216019080821115611d6457611d64611c17565b5f5b83811015611da5578181015183820152602001611d8d565b50505f910152565b5f6001600160a01b038088168352861515602084015285604084015280851660608401525060a0608083015282518060a0840152611df28160c0850160208701611d8b565b601f01601f19169190910160c0019695505050505050565b5f8060408385031215611e1b575f80fd5b505080516020909101519092909150565b5f8251611e3d818460208701611d8b565b9190910192915050565b5f60ff831680611e5957611e59611cf2565b8060ff8416069150509291505056fea2646970667358221220e7d462d153202b82b7949143fc986b1aed8d88f3296888c9b603017d53210dfe64736f6c63430008150033

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

00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e33e35ee6052fae87bfcfac61b1da90000000000000000000000003bc3ac09d1ee05393f2848d82cb420f3479544320000000000000000000000007e317f99aa313669aacdd8db3927ff3acb562dad000000000000000000000000109830a1aaad605bbf02a9dfa7b0b92ec2fb7daa

-----Decoded View---------------
Arg [0] : _ilkIndex (uint8): 0
Arg [1] : _ionPool (address): 0x0000000000E33e35EE6052fae87bfcFac61b1da9
Arg [2] : _gemJoin (address): 0x3bC3AC09d1ee05393F2848d82cb420f347954432
Arg [3] : _whitelist (address): 0x7E317f99aA313669AaCDd8dB3927ff3aCB562dAD
Arg [4] : _wstEthUniswapPool (address): 0x109830a1AAaD605BbF02a9dFA7B0B92EC2FB7dAa

-----Encoded View---------------
5 Constructor Arguments found :
Arg [0] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [1] : 0000000000000000000000000000000000e33e35ee6052fae87bfcfac61b1da9
Arg [2] : 0000000000000000000000003bc3ac09d1ee05393f2848d82cb420f347954432
Arg [3] : 0000000000000000000000007e317f99aa313669aacdd8db3927ff3acb562dad
Arg [4] : 000000000000000000000000109830a1aaad605bbf02a9dfa7b0b92ec2fb7daa


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  ]
[ 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.