ETH Price: $2,823.15 (+2.60%)

Contract

0xD9069E3F3EEb45d4E05b765142ba28f3BeB96F7a

Overview

ETH Balance

0 ETH

ETH Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

Advanced mode:
Parent Transaction Hash Block From To
View All Internal Transactions

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
PriceFeed

Compiler Version
v0.8.26+commit.8a97fa7a

Optimization Enabled:
Yes with 1 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;
import "../interfaces/utils/integrations/IAggregatorV3Interface.sol";
import "../dependencies/PropMath.sol";
import "../dependencies/PropOwnable.sol";
import {IInfraredCollateralVault} from "../interfaces/core/vaults/IInfraredCollateralVault.sol";
import {ISpotOracle} from "../interfaces/core/spotOracles/ISpotOracle.sol";

/**
    @title Multi Token Price Feed
    @notice Based on Gravita's PriceFeed:
            https://github.com/Gravita-Protocol/Gravita-SmartContracts/blob/9b69d555f3567622b0f84df8c7f1bb5cd9323573/contracts/PriceFeed.sol
 */
contract PriceFeed is PropOwnable {
    uint public constant MAX_ORACLE_HEARTBEAT = 2 days;

    struct OracleRecord {
        IAggregatorV3Interface chainLinkOracle;
        uint8 decimals;
        uint32 heartbeat;
        // Responses are considered stale this many seconds after the oracle's heartbeat
        uint16 staleThreshold;
        address underlyingDerivative;
    }

    struct FeedResponse {
        uint80 roundId;
        int256 answer;
        uint256 timestamp;
        bool success;
    }

    struct FeedType {
        ISpotOracle spotOracle;
        bool isCollVault;
    }

    // Custom Errors --------------------------------------------------------------------------------------------------

    error PriceFeed__PotentialDos();
    error PriceFeed__InvalidFeedResponseError(address token);
    error PriceFeed__FeedFrozenError(address token);
    error PriceFeed__HeartbeatOutOfBoundsError();
    error PriceFeed__InvalidResponse(address _token);

    // Events ---------------------------------------------------------------------------------------------------------

    event NewOracleRegistered(address token, address chainlinkAggregator, address underlyingDerivative);
    event NewCollVaultRegistered(address collVault, bool enable);
    event NewSpotOracleRegistered(address token, address spotOracle);

    /** Constants ---------------------------------------------------------------------------------------------------- */

    // Used to convert a chainlink price answer to an 18-digit precision uint
    uint256 public constant TARGET_DIGITS = 18;

    // Maximum deviation allowed between two consecutive Chainlink oracle prices. 18-digit precision.
    uint256 public constant MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND = 5e17; // 50%

    // State ------------------------------------------------------------------------------------------------------------

    mapping(address => OracleRecord) public oracleRecords;
    mapping(address => FeedType) public feedType;

    constructor(address _metaCore) PropOwnable(_metaCore) {
        if (_metaCore == address(0)) {
            revert("PriceFeed: 0 address");
        }
    }

    // Admin routines ---------------------------------------------------------------------------------------------------

    /**
        @notice Set the oracle for a specific token
        @dev IMPORTANT: When the collateral whitelisted is a reward token in any InfraredCollateralVault, `internalizeDonations` should be called for the rewards taken meanwhile the feed was not set.
        @param _token Address of the token to set the oracle for
        @param _chainlinkOracle Address of the chainlink oracle for this token
        @param _heartbeat Oracle heartbeat, in seconds
        @param _staleThreshold Time in seconds after which the price is considered stale
        @param underlyingDerivative Address of the underlying derivative token, if any
     */
    function setOracle(
        address _token,
        address _chainlinkOracle,
        uint32 _heartbeat,
        uint16 _staleThreshold,
        address underlyingDerivative
    ) public onlyOwner {
        require(_token != underlyingDerivative, "PriceFeed: token cannot point to itself");
        require(oracleRecords[underlyingDerivative].underlyingDerivative == address(0), "PriceFeed: only to USD pairs");
        require(_isSpotOracleNotSet(_token) && !isCollVault(_token), "PriceFeed: token already whitelisted");
        if (_heartbeat > MAX_ORACLE_HEARTBEAT) revert PriceFeed__HeartbeatOutOfBoundsError();
        IAggregatorV3Interface newFeed = IAggregatorV3Interface(_chainlinkOracle);
        (FeedResponse memory currResponse, FeedResponse memory prevResponse) = _fetchFeedResponses(newFeed);
        
        if (_token == address(0)) revert PriceFeed__PotentialDos();

        if (!_isFeedWorking(currResponse, prevResponse)) {
            revert PriceFeed__InvalidFeedResponseError(_token);
        }
        if (_isPriceStale(currResponse.timestamp, _heartbeat, _staleThreshold)) {
            revert PriceFeed__FeedFrozenError(_token);
        }

        OracleRecord memory record = OracleRecord({
            chainLinkOracle: newFeed,
            decimals: newFeed.decimals(),
            heartbeat: _heartbeat,
            staleThreshold: _staleThreshold,
            underlyingDerivative: underlyingDerivative
        });

        oracleRecords[_token] = record;

        _processFeedResponses(_token, record, currResponse, prevResponse);
        emit NewOracleRegistered(_token, _chainlinkOracle, underlyingDerivative);
    }

    function whitelistCollateralVault(address _token, bool _enable) external onlyOwner {
        require(_token != address(0), "PriceFeed: token 0 address");
        require(!_enable || _isClOracleNotSet(_token) && _isSpotOracleNotSet(_token), "PriceFeed: token already whitelisted");

        feedType[_token].isCollVault = _enable;

        emit NewCollVaultRegistered(_token, _enable);
    }

    function setSpotOracle(address _token, address _spotOracle) external onlyOwner {
        require(_token != address(0), "PriceFeed: token 0 address");
        require(_spotOracle == address(0) || _isClOracleNotSet(_token) && !isCollVault(_token), "PriceFeed: token already whitelisted");

        feedType[_token].spotOracle = ISpotOracle(_spotOracle);

        emit NewSpotOracleRegistered(_token, _spotOracle);
    }

    // Public functions -------------------------------------------------------------------------------------------------

    /**
        @notice Get the latest price returned from the oracle
        @dev You can obtain these values by calling `PositionManager.fetchPrice()`
             rather than directly interacting with this contract.
        @param _token Token to fetch the price for
        @return The latest valid price for the requested token
     */
    function fetchPrice(address _token) public view returns (uint256) {
        if (feedType[_token].isCollVault) {
            return IInfraredCollateralVault(_token).fetchPrice();
        }

        ISpotOracle spotOracle = feedType[_token].spotOracle;
        if (address(spotOracle) != address(0)) {
            return spotOracle.fetchPrice();
        }

        OracleRecord memory oracle = oracleRecords[_token];

        require(address(oracle.chainLinkOracle) != address(0), "PriceFeed: token not supported");

        (FeedResponse memory currResponse, FeedResponse memory prevResponse) = _fetchFeedResponses(
            oracle.chainLinkOracle
        );

        return _processFeedResponses(_token, oracle, currResponse, prevResponse);
    }

    // Internal functions -----------------------------------------------------------------------------------------------

    function _processFeedResponses(
        address _token,
        OracleRecord memory oracle,
        FeedResponse memory _currResponse,
        FeedResponse memory _prevResponse
    ) internal view returns (uint256) {
        uint8 decimals = oracle.decimals;
        bool isValidResponse = _isFeedWorking(_currResponse, _prevResponse) &&
            !_isPriceStale(_currResponse.timestamp, oracle.heartbeat, oracle.staleThreshold) &&
            !_isPriceChangeAboveMaxDeviation(_currResponse, _prevResponse, decimals);

        if (isValidResponse) {
            uint256 scaledPrice = _scalePriceByDigits(uint256(_currResponse.answer), decimals);
            if (oracle.underlyingDerivative != address(0)) {
                uint256 underlyingPrice = fetchPrice(oracle.underlyingDerivative);
                scaledPrice = (scaledPrice * underlyingPrice) / 1 ether;
            }
            return scaledPrice;
        } else {
            revert PriceFeed__InvalidResponse(_token);
        }
    }

    function _fetchFeedResponses(
        IAggregatorV3Interface oracle
    ) internal view returns (FeedResponse memory currResponse, FeedResponse memory prevResponse) {
        currResponse = _fetchCurrentFeedResponse(oracle);
        prevResponse = _fetchPrevFeedResponse(oracle, currResponse.roundId);
    }

    function _isPriceStale(uint256 _priceTimestamp, uint256 _heartbeat, uint16 _staleThreshold) internal view returns (bool) {
        return block.timestamp - _priceTimestamp > _heartbeat + _staleThreshold;
    }

    function _isFeedWorking(
        FeedResponse memory _currentResponse,
        FeedResponse memory _prevResponse
    ) internal view returns (bool) {
        return _isValidResponse(_currentResponse) && _isValidResponse(_prevResponse);
    }

    function _isValidResponse(FeedResponse memory _response) internal view returns (bool) {
        return
            (_response.success) &&
            (_response.roundId != 0) &&
            (_response.timestamp != 0) &&
            (_response.timestamp <= block.timestamp) &&
            (_response.answer > 0);
    }

    function _isPriceChangeAboveMaxDeviation(
        FeedResponse memory _currResponse,
        FeedResponse memory _prevResponse,
        uint8 decimals
    ) internal pure returns (bool) {
        uint256 currentScaledPrice = _scalePriceByDigits(uint256(_currResponse.answer), decimals);
        uint256 prevScaledPrice = _scalePriceByDigits(uint256(_prevResponse.answer), decimals);
        
        uint256 minPrice = PropMath._min(currentScaledPrice, prevScaledPrice);
        uint256 maxPrice = PropMath._max(currentScaledPrice, prevScaledPrice);

        uint256 percentDeviation = ((maxPrice - minPrice) * PropMath.DECIMAL_PRECISION) / prevScaledPrice;
        
        return percentDeviation > MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND;
    }

    function _scalePriceByDigits(uint256 _price, uint256 _answerDigits) internal pure returns (uint256) {
        if (_answerDigits == TARGET_DIGITS) {
            return _price;
        } else if (_answerDigits < TARGET_DIGITS) {
            // Scale the returned price value up to target precision
            return _price * (10 ** (TARGET_DIGITS - _answerDigits));
        } else {
            // Scale the returned price value down to target precision
            return _price / (10 ** (_answerDigits - TARGET_DIGITS));
        }
    }

    function _fetchCurrentFeedResponse(
        IAggregatorV3Interface _priceAggregator
    ) internal view returns (FeedResponse memory response) {
        try _priceAggregator.latestRoundData() returns (
            uint80 roundId,
            int256 answer,
            uint256 /* startedAt */,
            uint256 timestamp,
            uint80 /* answeredInRound */
        ) {
            // If call to Chainlink succeeds, return the response and success = true
            response.roundId = roundId;
            response.answer = answer;
            response.timestamp = timestamp;
            response.success = true;
        } catch {
            // If call to Chainlink aggregator reverts, return a zero response with success = false
            return response;
        }
    }

    function _fetchPrevFeedResponse(
        IAggregatorV3Interface _priceAggregator,
        uint80 _currentRoundId
    ) internal view returns (FeedResponse memory prevResponse) {
        if (_currentRoundId == 0) {
            return prevResponse;
        }
        unchecked {
            try _priceAggregator.getRoundData(_currentRoundId - 1) returns (
                uint80 roundId,
                int256 answer,
                uint256 /* startedAt */,
                uint256 timestamp,
                uint80 /* answeredInRound */
            ) {
                prevResponse.roundId = roundId;
                prevResponse.answer = answer;
                prevResponse.timestamp = timestamp;
                prevResponse.success = true;
            } catch {}
        }
    }

    function isCollVault(address _token) public view returns (bool) {
        return feedType[_token].isCollVault;
    }

    function getSpotOracle(address _token) public view returns (address) {
        return address(feedType[_token].spotOracle);
    }

    function getMultiplePrices(address[] memory _tokens) external view returns (uint256[] memory prices) {
        uint length = _tokens.length;
        prices = new uint256[](length);
        for (uint256 i; i < length; i++) {
            prices[i] = fetchPrice(_tokens[i]);
        }
    }

    function _isClOracleNotSet(address token) private view returns (bool) {
        return oracleRecords[token].chainLinkOracle == IAggregatorV3Interface(address(0));
    }

    function _isSpotOracleNotSet(address token) private view returns (bool) {
        return feedType[token].spotOracle == ISpotOracle(address(0));
    }
}

// SPDX-License-Identifier: MIT
// Code from https://github.com/smartcontractkit/chainlink/blob/master/evm-contracts/src/v0.6/interfaces/AggregatorV3Interface.sol

pragma solidity 0.8.26;

interface IAggregatorV3Interface {
    function decimals() external view returns (uint8);

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

    function version() external view returns (uint256);

    // getRoundData and latestRoundData should both raise "No data present"
    // if they do not have data to report, instead of returning unset values
    // which could be misinterpreted as actual reported values.
    function getRoundData(
        uint80 _roundId
    )
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

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

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

library PropMath {
    uint256 internal constant DECIMAL_PRECISION = 1e18;

    /* Precision for Nominal ICR (independent of price). Rationale for the value:
     *
     * - Making it “too high” could lead to overflows.
     * - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division.
     *
     * This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39,
     * and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator.
     *
     */
    uint256 internal constant NICR_PRECISION = 1e20;

    function _min(uint256 _a, uint256 _b) internal pure returns (uint256) {
        return (_a < _b) ? _a : _b;
    }

    function _max(uint256 _a, uint256 _b) internal pure returns (uint256) {
        return (_a >= _b) ? _a : _b;
    }

    /*
     * Multiply two decimal numbers and use normal rounding rules:
     * -round product up if 19'th mantissa digit >= 5
     * -round product down if 19'th mantissa digit < 5
     *
     * Used only inside the exponentiation, _decPow().
     */
    function decMul(uint256 x, uint256 y) internal pure returns (uint256 decProd) {
        uint256 prod_xy = x * y;

        decProd = (prod_xy + (DECIMAL_PRECISION / 2)) / DECIMAL_PRECISION;
    }

    /*
     * _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.
     *
     * Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity.
     *
     * Called by two functions that represent time in units of minutes:
     * 1) PositionManager._calcDecayedBaseRate
     * 2) CommunityIssuance._getCumulativeIssuanceFraction
     *
     * The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals
     * "minutes in 1000 years": 60 * 24 * 365 * 1000
     *
     * If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be
     * negligibly different from just passing the cap, since:
     *
     * In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years
     * In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible
     */
    function _decPow(uint256 _base, uint256 _minutes) internal pure returns (uint256) {
        if (_minutes > 525600000) {
            _minutes = 525600000;
        } // cap to avoid overflow

        if (_minutes == 0) {
            return DECIMAL_PRECISION;
        }

        uint256 y = DECIMAL_PRECISION;
        uint256 x = _base;
        uint256 n = _minutes;

        // Exponentiation-by-squaring
        while (n > 1) {
            if (n % 2 == 0) {
                x = decMul(x, x);
                n = n / 2;
            } else {
                // if (n % 2 != 0)
                y = decMul(x, y);
                x = decMul(x, x);
                n = (n - 1) / 2;
            }
        }

        return decMul(x, y);
    }

    function _getAbsoluteDifference(uint256 _a, uint256 _b) internal pure returns (uint256) {
        return (_a >= _b) ? _a - _b : _b - _a;
    }

    function _computeNominalCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {
        if (_debt > 0) {
            return (_coll * NICR_PRECISION) / _debt;
        }
        // Return the maximal value for uint256 if the Position has a debt of 0. Represents "infinite" CR.
        else {
            // if (_debt == 0)
            return 2 ** 256 - 1;
        }
    }

    function _computeCR(uint256 _coll, uint256 _debt, uint256 _price) internal pure returns (uint256) {
        if (_debt > 0) {
            uint256 newCollRatio = (_coll * _price) / _debt;

            return newCollRatio;
        }
        // Return the maximal value for uint256 if the Position has a debt of 0. Represents "infinite" CR.
        else {
            // if (_debt == 0)
            return 2 ** 256 - 1;
        }
    }

    function _computeCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {
        if (_debt > 0) {
            uint256 newCollRatio = (_coll) / _debt;

            return newCollRatio;
        }
        // Return the maximal value for uint256 if the Position has a debt of 0. Represents "infinite" CR.
        else {
            // if (_debt == 0)
            return 2 ** 256 - 1;
        }
    }

    function _isApproxEqAbs(uint256 a, uint256 b, uint256 tolerance) internal pure returns (bool) {
        return a > b ? (a - b) <= tolerance : (b - a) <= tolerance;
    }

    function _isWithinToleranceAbove(
        uint256 a,
        uint256 b,
        uint256 tolerance
    ) internal pure returns (bool) {
        if (a < b) return false;
        return (a - b) <= tolerance;
    }

    function _isWithinToleranceBelow(
        uint256 a,
        uint256 b,
        uint256 tolerance
    ) internal pure returns (bool) {
        if (a > b) return false;
        return (b - a) <= tolerance;
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

import "../interfaces/core/ICore.sol";

/**
    @title Prop Ownable
    @notice Contracts inheriting `PropOwnable` have the same owner as `PropCore`.
            The ownership cannot be independently modified or renounced.
    @dev In the contracts that use CORE to interact with protocol instance specific parameters,
            the immutable will be instanced with PropCore.sol, eitherway, it will be MetaCore.sol
 */
contract PropOwnable {
    ICore public immutable CORE;

    constructor(address _core) {
        CORE = ICore(_core);
    }

    modifier onlyOwner() {
        require(msg.sender == CORE.owner(), "Only owner");
        _;
    }

    function owner() public view returns (address) {
        return CORE.owner();
    }

    function guardian() public view returns (address) {
        return CORE.guardian();
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {IBaseCollateralVault} from "./IBaseCollateralVault.sol";
import {IInfraredWrapper} from "./IInfraredWrapper.sol";
import {IPositionManager} from "../IPositionManager.sol";
import {ICore} from "../ICore.sol";
import {IInfraredVault} from "../../utils/integrations/IInfraredVault.sol";
import {EmissionsLib} from "src/libraries/EmissionsLib.sol";

interface IInfraredCollateralVault is IBaseCollateralVault {
    struct InfraredCollVaultStorage {
        uint16 minPerformanceFee;
        uint16 maxPerformanceFee;
        uint16 performanceFee; // over yield, in basis points
        address iRedToken;
        /// @dev We currently don't know the infraredVault implementation, but if it were to be possible for them to remove tokens from the rewardTokens
        /// There would be no need to remove it from here since the amounts should continue being accounted for in the virtual balance
        EnumerableSet.AddressSet rewardedTokens;

        IInfraredVault _infraredVault;
        address ibgtVault;
        address ibgt;
        IInfraredWrapper infraredWrapper;
        uint96 lastUpdate;

        mapping(address tokenIn => uint) threshold;
    }

    struct InfraredInitParams {
        BaseInitParams _baseParams;
        uint16 _minPerformanceFee;
        uint16 _maxPerformanceFee;
        uint16 _performanceFee; // over yield, in basis points
        address _iRedToken;
        IInfraredVault _infraredVault;
        address _ibgtVault;
        address _infraredWrapper;
    }

    struct RebalanceParams {
        address sentCurrency; 
        uint sentAmount; 
        address swapper;
        bytes payload;
    }

    function rebalance(RebalanceParams calldata p) external;

    function pullRewards() external;

    function setUnlockRatePerSecond(address token, uint64 _unlockRatePerSecond) external;

    function internalizeDonations(address[] memory tokens, uint128[] memory amounts) external;

    function setPairThreshold(address tokenIn, uint thresholdInBP) external;

    function setPerformanceFee(uint16 _performanceFee) external;
    function setWithdrawFee(uint16 _withdrawFee) external;

    function getBalance(address token) external view returns (uint);

    function getBalanceOfWithFutureEmissions(address token) external view returns (uint);

    function getFullProfitUnlockTimestamp(address token) external view returns (uint);

    function unlockRatePerSecond(address token) external view returns (uint);

    function getLockedEmissions(address token) external view returns (uint);

    function getPerformanceFee() external view returns (uint16);


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

    function iRedToken() external view returns (address);

    function infraredVault() external view returns (IInfraredVault);

    function ibgt() external view returns (address);

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

File 6 of 25 : ISpotOracle.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

interface ISpotOracle {
    function fetchPrice() external view returns (uint);
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

import {IMetaCore} from "src/interfaces/core/IMetaCore.sol";

interface ICore {

    // --- Public variables ---
    function metaCore() external view returns (IMetaCore);
    function startTime() external view returns (uint256);
    function CCR() external view returns (uint256);
    function dmBootstrapPeriod() external view returns (uint64);
    function isPeriphery(address peripheryContract) external view returns (bool);

    // --- External functions ---

    function setPeripheryEnabled(address _periphery, bool _enabled) external;
    function setPMBootstrapPeriod(address dm, uint64 _bootstrapPeriod) external;
    function setNewCCR(uint256 _CCR) external;

    function priceFeed() external view returns (address);
    function owner() external view returns (address);
    function pendingOwner() external view returns (address);
    function guardian() external view returns (address);
    function feeReceiver() external view returns (address);
    function paused() external view returns (bool);
    function lspBootstrapPeriod() external view returns (uint64);
    function getLspEntryFee(address rebalancer) external view returns (uint16);
    function getLspExitFee(address rebalancer) external view returns (uint16);
    function interestProtocolShare() external view returns (uint16);
    function defaultInterestReceiver() external view returns (address);

    // --- Events ---
    event CCRSet(uint256 initialCCR);
    event PMBootstrapPeriodSet(address dm, uint64 bootstrapPeriod);
    event PeripheryEnabled(address indexed periphery, bool enabled);
}

File 8 of 25 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/IERC20.sol";

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.0;

/**
 * @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.
 *
 * ```
 * 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 of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }

    /**
     * @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._indexes[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 read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 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 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

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

                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastValue;
                // Update the index for the moved value
                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }

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

            // Delete the index for the deleted slot
            delete set._indexes[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._indexes[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;
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

import {IERC4626, IERC20} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {IPositionManager} from "../IPositionManager.sol";
import {IMetaCore} from "../IMetaCore.sol";
import {IPriceFeed} from "../IPriceFeed.sol";
import {EmissionsLib} from "src/libraries/EmissionsLib.sol";

interface IBaseCollateralVault is IERC4626, IERC1822Proxiable {
    struct BaseInitParams {
        uint16 _minWithdrawFee;
        uint16 _maxWithdrawFee;
        uint16 _withdrawFee;
        IMetaCore _metaCore;
        // ERC4626
        IERC20 _asset;
        // ERC20
        string _sharesName;
        string _sharesSymbol;
    }

    struct BaseCollVaultStorage {
        uint16 minWithdrawFee;
        uint16 maxWithdrawFee;
        uint16 withdrawFee; // over rewarded tokens, in basis points
        uint8 assetDecimals;

        IMetaCore _metaCore;

        // Second mapping of this struct is usless, but it's for retrocompatibility with InfraredCollateralVault
        EmissionsLib.BalanceData balanceData;
    }

    function totalAssets() external view returns (uint);

    function fetchPrice() external view returns (uint);

    function getPrice(address token) external view returns (uint);

    function receiveDonations(address[] memory tokens, uint[] memory amounts, address receiver) external;

    function setWithdrawFee(uint16 _withdrawFee) external;

    function getBalance(address token) external view returns (uint);

    function getWithdrawFee() external view returns (uint16);

    function getMetaCore() external view returns (IMetaCore);

    function getPriceFeed() external view returns (IPriceFeed);

    function assetDecimals() external view returns (uint8);
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

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

interface IInfraredWrapper is IERC20 {
    function metaCore() external view returns (address);
    function infraredCollVault() external view returns (address);
    function decimals() external view returns (uint8);
    function depositFor(address account, uint256 amount) external returns (bool);
    function withdrawTo(address account, uint256 amount) external returns (bool);
    function recover(address account) external returns (uint256);
}

File 12 of 25 : IPositionManager.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

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

interface IPositionManager {
    event BaseRateUpdated(uint256 _baseRate);
    event CollateralSent(address _to, uint256 _amount);
    event LTermsUpdated(uint256 _L_collateral, uint256 _L_debt);
    event LastFeeOpTimeUpdated(uint256 _lastFeeOpTime);
    event Redemption(
        address indexed _redeemer,
        uint256 _attemptedDebtAmount,
        uint256 _actualDebtAmount,
        uint256 _collateralSent,
        uint256 _collateralFee
    );
    event SystemSnapshotsUpdated(uint256 _totalStakesSnapshot, uint256 _totalCollateralSnapshot);
    event TotalStakesUpdated(uint256 _newTotalStakes);
    event PositionIndexUpdated(address _borrower, uint256 _newIndex);
    event PositionSnapshotsUpdated(uint256 _L_collateral, uint256 _L_debt);
    event PositionUpdated(address indexed _borrower, uint256 _debt, uint256 _coll, uint256 _stake, uint8 _operation);

    function addCollateralSurplus(address borrower, uint256 collSurplus) external;

    function applyPendingRewards(address _borrower) external returns (uint256 coll, uint256 debt);

    function claimCollateral(address borrower, address _receiver) external;

    function closePosition(address _borrower, address _receiver, uint256 collAmount, uint256 debtAmount) external;

    function closePositionByLiquidation(address _borrower) external;

    function setCollVaultRouter(address _collVaultRouter) external;

    function collectInterests() external;

    function decayBaseRateAndGetBorrowingFee(uint256 _debt) external returns (uint256);

    function decreaseDebtAndSendCollateral(address account, uint256 debt, uint256 coll) external;

    function fetchPrice() external view returns (uint256);

    function finalizeLiquidation(
        address _liquidator,
        uint256 _debt,
        uint256 _coll,
        uint256 _collSurplus,
        uint256 _debtGasComp,
        uint256 _collGasComp
    ) external;

    function getEntireSystemBalances() external view returns (uint256, uint256, uint256);

    function movePendingPositionRewardsToActiveBalances(uint256 _debt, uint256 _collateral) external;

    function openPosition(
        address _borrower,
        uint256 _collateralAmount,
        uint256 _compositeDebt,
        uint256 NICR,
        address _upperHint,
        address _lowerHint
    ) external returns (uint256 stake, uint256 arrayIndex);

    function redeemCollateral(
        uint256 _debtAmount,
        address _firstRedemptionHint,
        address _upperPartialRedemptionHint,
        address _lowerPartialRedemptionHint,
        uint256 _partialRedemptionHintNICR,
        uint256 _maxIterations,
        uint256 _maxFeePercentage
    ) external;

    function setAddresses(address _priceFeedAddress, address _sortedPositionsAddress, address _collateralToken) external;

    function setParameters(
        IFactory.DeploymentParams calldata _params
    ) external;

    function setPaused(bool _paused) external;

    function setPriceFeed(address _priceFeedAddress) external;

    function startSunset() external;

    function updateBalances() external;

    function updatePositionFromAdjustment(
        bool _isDebtIncrease,
        uint256 _debtChange,
        uint256 _netDebtChange,
        bool _isCollIncrease,
        uint256 _collChange,
        address _upperHint,
        address _lowerHint,
        address _borrower,
        address _receiver
    ) external returns (uint256, uint256, uint256);

    function DEBT_GAS_COMPENSATION() external view returns (uint256);

    function DECIMAL_PRECISION() external view returns (uint256);

    function L_collateral() external view returns (uint256);

    function L_debt() external view returns (uint256);

    function MCR() external view returns (uint256);

    function PERCENT_DIVISOR() external view returns (uint256);

    function CORE() external view returns (address);

    function SUNSETTING_INTEREST_RATE() external view returns (uint256);

    function Positions(
        address
    )
        external
        view
        returns (
            uint256 debt,
            uint256 coll,
            uint256 stake,
            uint8 status,
            uint128 arrayIndex,
            uint256 activeInterestIndex
        );

    function activeInterestIndex() external view returns (uint256);

    function baseRate() external view returns (uint256);

    function borrowerOperations() external view returns (address);

    function borrowingFeeFloor() external view returns (uint256);

    function collateralToken() external view returns (address);

    function debtToken() external view returns (address);

    function collVaultRouter() external view returns (address);

    function defaultedCollateral() external view returns (uint256);

    function defaultedDebt() external view returns (uint256);

    function getBorrowingFee(uint256 _debt) external view returns (uint256);

    function getBorrowingFeeWithDecay(uint256 _debt) external view returns (uint256);

    function getBorrowingRate() external view returns (uint256);

    function getBorrowingRateWithDecay() external view returns (uint256);

    function getCurrentICR(address _borrower, uint256 _price) external view returns (uint256);

    function getEntireDebtAndColl(
        address _borrower
    ) external view returns (uint256 debt, uint256 coll, uint256 pendingDebtReward, uint256 pendingCollateralReward);

    function getEntireSystemColl() external view returns (uint256);

    function getEntireSystemDebt() external view returns (uint256);

    function getNominalICR(address _borrower) external view returns (uint256);

    function getPendingCollAndDebtRewards(address _borrower) external view returns (uint256, uint256);

    function getRedemptionFeeWithDecay(uint256 _collateralDrawn) external view returns (uint256);

    function getRedemptionRate() external view returns (uint256);

    function getRedemptionRateWithDecay() external view returns (uint256);

    function getTotalActiveCollateral() external view returns (uint256);

    function getTotalActiveDebt() external view returns (uint256);

    function getPositionCollAndDebt(address _borrower) external view returns (uint256 coll, uint256 debt);

    function getPositionFromPositionOwnersArray(uint256 _index) external view returns (address);

    function getPositionOwnersCount() external view returns (uint256);

    function getPositionStake(address _borrower) external view returns (uint256);

    function getPositionStatus(address _borrower) external view returns (uint256);

    function guardian() external view returns (address);

    function hasPendingRewards(address _borrower) external view returns (bool);

    function interestPayable() external view returns (uint256);

    function interestRate() external view returns (uint256);

    function lastActiveIndexUpdate() external view returns (uint256);

    function lastCollateralError_Redistribution() external view returns (uint256);

    function lastDebtError_Redistribution() external view returns (uint256);

    function lastFeeOperationTime() external view returns (uint256);

    function liquidationManager() external view returns (address);

    function maxBorrowingFee() external view returns (uint256);

    function maxRedemptionFee() external view returns (uint256);

    function maxSystemDebt() external view returns (uint256);

    function minuteDecayFactor() external view returns (uint256);

    function owner() external view returns (address);

    function paused() external view returns (bool);

    function priceFeed() external view returns (address);

    function redemptionFeeFloor() external view returns (uint256);

    function rewardSnapshots(address) external view returns (uint256 collateral, uint256 debt);

    function sortedPositions() external view returns (address);

    function sunsetting() external view returns (bool);

    function surplusBalances(address) external view returns (uint256);

    function systemDeploymentTime() external view returns (uint256);

    function totalCollateralSnapshot() external view returns (uint256);

    function totalStakes() external view returns (uint256);

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

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

interface IInfraredVault {
    function stakingToken() external view returns (address);
    function stake(uint256 amount) external;
    function withdraw(uint256 amount) external;
    function getReward() external;
    function getRewardForUser(address account) external;
    function rewardTokens(uint) external view returns (address);
    function getAllRewardTokens() external view returns (address[] memory);
    function earned(address account, address _rewardsToken) external view returns (uint256);
    function registerVault(address stakingToken) external returns (address);
    function balanceOf(address account) external view returns (uint256);
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {ILiquidStabilityPool} from "../interfaces/core/ILiquidStabilityPool.sol";

library EmissionsLib {
    using SafeCast for uint256;
    uint64 constant internal DEFAULT_UNLOCK_RATE = 1e11; // 10% per second
    uint64 constant internal MAX_UNLOCK_RATE = 1e12; // 100%

    struct BalanceData {
        mapping(address token => uint) balance;
        mapping(address token => EmissionSchedule) emissionSchedule;
    }

    struct EmissionSchedule {
        uint128 emissions;
        uint64 lockTimestamp;
        uint64 _unlockRatePerSecond; // rate points
    }

    error AmountCannotBeZero();
    error EmissionRateExceedsMax();
    // error UnsupportedEmissionConfig();

    event EmissionsAdded(address indexed token, uint128 amount);
    event EmissionsSub(address indexed token, uint128 amount);
    event NewUnlockRatePerSecond(address indexed token, uint64 unlockRatePerSecond);

    /// @dev zero _unlockRatePerSecond parameter resets rate back to DEFAULT_UNLOCK_RATE
    function setUnlockRatePerSecond(BalanceData storage $, address token, uint64 _unlockRatePerSecond) internal {
        if (_unlockRatePerSecond > MAX_UNLOCK_RATE) revert EmissionRateExceedsMax();
        _addEmissions($, token, 0); // update lockTimestamp and emissions
        $.emissionSchedule[token]._unlockRatePerSecond = _unlockRatePerSecond;

        emit NewUnlockRatePerSecond(token, _unlockRatePerSecond);
    }

    function addEmissions(BalanceData storage $, address token, uint128 amount) internal {
        if (amount == 0) revert AmountCannotBeZero();
        _addEmissions($, token, amount);

        emit EmissionsAdded(token, amount);
    }

    function _addEmissions(BalanceData storage $, address token, uint128 amount) private {        
        EmissionSchedule memory schedule = $.emissionSchedule[token];

        uint256 _unlockTimestamp = unlockTimestamp(schedule);
        uint128 nextEmissions = (lockedEmissions(schedule, _unlockTimestamp) + amount).toUint128();

        schedule.emissions = nextEmissions;
        schedule.lockTimestamp = block.timestamp.toUint64();
        $.balance[token] += amount;

        $.emissionSchedule[token] = schedule;
    }

    function subEmissions(BalanceData storage $, address token, uint128 amount) internal {
        if (amount == 0) revert AmountCannotBeZero();
        _subEmissions($, token, amount);

        emit EmissionsSub(token, amount);
    }

    function _subEmissions(BalanceData storage $, address token, uint128 amount) private {
        EmissionSchedule memory schedule = $.emissionSchedule[token];

        uint256 _unlockTimestamp = unlockTimestamp(schedule);
        uint128 nextEmissions = (lockedEmissions(schedule, _unlockTimestamp) - amount).toUint128();

        schedule.emissions = nextEmissions;
        schedule.lockTimestamp = block.timestamp.toUint64();
        $.balance[token] -= amount;

        $.emissionSchedule[token] = schedule;
    }

    /// @dev Doesn't include locked emissions
    function unlockedEmissions(EmissionSchedule memory schedule) internal view returns (uint256) {
        return schedule.emissions - lockedEmissions(schedule, unlockTimestamp(schedule));
    }

    function balanceOfWithFutureEmissions(BalanceData storage $, address token) internal view returns (uint256) {
        return $.balance[token];
    }

    /**
     * @notice Returns the unlocked token emissions
     */
    function balanceOf(BalanceData storage $, address token) internal view returns (uint256) {
        EmissionSchedule memory schedule = $.emissionSchedule[token];
        return $.balance[token] - lockedEmissions(schedule, unlockTimestamp(schedule));
    }

    /**
     * @notice Returns locked emissions
     */
    function lockedEmissions(EmissionSchedule memory schedule, uint256 _unlockTimestamp) internal view returns (uint256) {
        if (block.timestamp >= _unlockTimestamp) {
            // all emissions were unlocked 
            return 0;
        } else {
            // emissions are still unlocking, calculate the amount of already unlocked emissions
            uint256 secondsSinceLockup = block.timestamp - schedule.lockTimestamp;
            // design decision - use dimensionless 'unlock rate units' to unlock emissions over a fixed time window 
            uint256 ratePointsUnlocked = unlockRatePerSecond(schedule) * secondsSinceLockup;
            // emissions remainder is designed to be added to balance in unlockTimestamp
            return schedule.emissions - ratePointsUnlocked * schedule.emissions / MAX_UNLOCK_RATE;
        }
    } 

    // timestamp at which all emissions are fully unlocked
    function unlockTimestamp(EmissionSchedule memory schedule) internal pure returns (uint256) {
        // ceil to account for remainder seconds left after integer division
        return divRoundUp(MAX_UNLOCK_RATE, unlockRatePerSecond(schedule)) + schedule.lockTimestamp; 
    }

    function unlockRatePerSecond(EmissionSchedule memory schedule) internal pure returns (uint256) {
        return schedule._unlockRatePerSecond == 0 ? DEFAULT_UNLOCK_RATE : schedule._unlockRatePerSecond;
    }

    function divRoundUp(uint256 dividend, uint256 divisor) internal pure returns (uint256) {
        return (dividend + divisor - 1) / divisor;
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

interface IMetaCore {
    // ---------------------------------
    // Structures
    // ---------------------------------
    struct FeeInfo {
        bool existsForDebtToken;
        uint16 debtTokenFee;
    }

    struct RebalancerFeeInfo {
        bool exists;
        uint16 entryFee;
        uint16 exitFee;
    }

    // ---------------------------------
    // Public constants
    // ---------------------------------
    function OWNERSHIP_TRANSFER_DELAY() external view returns (uint256);
    function DEFAULT_FLASH_LOAN_FEE() external view returns (uint16);

    // ---------------------------------
    // Public state variables
    // ---------------------------------
    function debtToken() external view returns (address);
    function lspEntryFee() external view returns (uint16);
    function lspExitFee() external view returns (uint16);
    function interestProtocolShare() external view returns (uint16);
    /// @dev Default interest receiver for all PositionManagers, unless overriden in the respective PM
    function defaultInterestReceiver() external view returns (address);

    function feeReceiver() external view returns (address);
    function priceFeed() external view returns (address);
    function owner() external view returns (address);
    function pendingOwner() external view returns (address);
    function ownershipTransferDeadline() external view returns (uint256);
    function guardian() external view returns (address);
    function paused() external view returns (bool);
    function lspBootstrapPeriod() external view returns (uint64);

    // ---------------------------------
    // External functions
    // ---------------------------------
    function setFeeReceiver(address _feeReceiver) external;
    function setPriceFeed(address _priceFeed) external;
    function setGuardian(address _guardian) external;

    /**
     * @notice Global pause/unpause
     *         Pausing halts new deposits/borrowing across the protocol
     */
    function setPaused(bool _paused) external;

    /**
     * @notice Extend or change the LSP bootstrap period,
     *         after which certain protocol mechanics change
     */
    function setLspBootstrapPeriod(uint64 _bootstrapPeriod) external;

    /**
     * @notice Set a custom flash-loan fee for a given periphery contract
     * @param _periphery Target contract that will get this custom fee
     * @param _debtTokenFee Fee in basis points (bp)
     * @param _existsForDebtToken Whether this custom fee is used when the caller = `debtToken`
     */
    function setPeripheryFlashLoanFee(address _periphery, uint16 _debtTokenFee, bool _existsForDebtToken) external;

    /**
     * @notice Begin the ownership transfer process
     * @param newOwner The address proposed to be the new owner
     */
    function commitTransferOwnership(address newOwner) external;

    /**
     * @notice Finish the ownership transfer, after the mandatory delay
     */
    function acceptTransferOwnership() external;

    /**
     * @notice Revoke a pending ownership transfer
     */
    function revokeTransferOwnership() external;

    /**
     * @notice Look up a custom flash-loan fee for a specific periphery contract
     * @param peripheryContract The contract that might have a custom fee
     * @return The flash-loan fee in basis points
     */
    function getPeripheryFlashLoanFee(address peripheryContract) external view returns (uint16);

    /**
     * @notice Set / override entry & exit fees for a special rebalancer contract
     */
    function setRebalancerFee(address _rebalancer, uint16 _entryFee, uint16 _exitFee) external;

    /**
     * @notice Set the LSP entry fee globally
     * @param _fee Fee in basis points
     */
    function setEntryFee(uint16 _fee) external;

    /**
     * @notice Set the LSP exit fee globally
     * @param _fee Fee in basis points
     */
    function setExitFee(uint16 _fee) external;

    /**
     * @notice Set the interest protocol share globally to all PositionManagers
     * @param _interestProtocolShare Share in basis points
     */
    function setInterestProtocolShare(uint16 _interestProtocolShare) external;

    /**
     * @notice Look up the LSP entry fee for a rebalancer
     * @param rebalancer Possibly has a special fee
     * @return The entry fee in basis points
     */
    function getLspEntryFee(address rebalancer) external view returns (uint16);

    /**
     * @notice Look up the LSP exit fee for a rebalancer
     * @param rebalancer Possibly has a special fee
     * @return The exit fee in basis points
     */
    function getLspExitFee(address rebalancer) external view returns (uint16);

    // ---------------------------------
    // Events
    // ---------------------------------
    event NewOwnerCommitted(address indexed owner, address indexed pendingOwner, uint256 deadline);
    event NewOwnerAccepted(address indexed oldOwner, address indexed newOwner);
    event NewOwnerRevoked(address indexed owner, address indexed revokedOwner);

    event FeeReceiverSet(address indexed feeReceiver);
    event PriceFeedSet(address indexed priceFeed);
    event GuardianSet(address indexed guardian);
    event PeripheryFlashLoanFee(address indexed periphery, uint16 debtTokenFee);
    event LSPBootstrapPeriodSet(uint64 bootstrapPeriod);
    event RebalancerFees(address indexed rebalancer, uint16 entryFee, uint16 exitFee);
    event EntryFeeSet(uint16 fee);
    event ExitFeeSet(uint16 fee);
    event InterestProtocolShareSet(uint16 interestProtocolShare);
    event DefaultInterestReceiverSet(address indexed defaultInterestReceiver);
    event Paused();
    event Unpaused();
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @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 amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (interfaces/IERC4626.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/IERC20.sol";
import "../token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 *
 * _Available since v4.7._
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(
        uint256 assets,
        address receiver,
        address owner
    ) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(
        uint256 shares,
        address receiver,
        address owner
    ) external returns (uint256 assets);
}

File 18 of 25 : draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.0;

/**
 * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IPriceFeed {
    struct FeedType {
        address spotOracle;
        bool isCollVault;
    }

    event NewOracleRegistered(address token, address chainlinkAggregator, address underlyingDerivative);
    event PriceFeedStatusUpdated(address token, address oracle, bool isWorking);
    event PriceRecordUpdated(address indexed token, uint256 _price);
    event NewCollVaultRegistered(address collVault, bool enable);
    event NewSpotOracleRegistered(address token, address spotOracle);

    function fetchPrice(address _token) external view returns (uint256);

    function getMultiplePrices(address[] memory _tokens) external view returns (uint256[] memory prices);

    function setOracle(
        address _token,
        address _chainlinkOracle,
        uint32 _heartbeat,
        uint16 _staleThreshold,
        address underlyingDerivative
    ) external;

    function whitelistCollateralVault(address _collateralVaultShareToken, bool enable) external;
    
    function setSpotOracle(address _token, address _spotOracle) external;
    
    function MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND() external view returns (uint256);

    function CORE() external view returns (address);

    function RESPONSE_TIMEOUT() external view returns (uint256);

    function TARGET_DIGITS() external view returns (uint256);

    function guardian() external view returns (address);

    function oracleRecords(
        address
    )
        external
        view
        returns (
        address chainLinkOracle,
        uint8 decimals,
        uint32 heartbeat,
        uint16 staleThreshold,
        address underlyingDerivative
    );

    function isCollVault(address _collateralVaultShareToken) external view returns (bool);

    function isStableBPT(address _oracle) external view returns (bool);

    function isWeightedBPT(address _oracle) external view returns (bool);

    function getSpotOracle(address _token) external view returns (address);

    function feedType(address _token) external view returns (FeedType memory);

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

File 20 of 25 : IERC3156FlashBorrower.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (interfaces/IERC3156FlashBorrower.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC3156 FlashBorrower, as defined in
 * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
 *
 * _Available since v4.1._
 */
interface IERC3156FlashBorrower {
    /**
     * @dev Receive a flash loan.
     * @param initiator The initiator of the loan.
     * @param token The loan currency.
     * @param amount The amount of tokens lent.
     * @param fee The additional amount of tokens to repay.
     * @param data Arbitrary data structure, intended to contain user-defined parameters.
     * @return The keccak256 hash of "IERC3156FlashBorrower.onFlashLoan"
     */
    function onFlashLoan(
        address initiator,
        address token,
        uint256 amount,
        uint256 fee,
        bytes calldata data
    ) external returns (bytes32);
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

interface IFactory {
    // commented values are suggested default parameters
    struct DeploymentParams {
        uint256 minuteDecayFactor; // 999037758833783000  (half life of 12 hours)
        uint256 redemptionFeeFloor; // 1e18 / 1000 * 5  (0.5%)
        uint256 maxRedemptionFee; // 1e18  (100%)
        uint256 borrowingFeeFloor; // 1e18 / 1000 * 5  (0.5%)
        uint256 maxBorrowingFee; // 1e18 / 100 * 5  (5%)
        uint256 interestRateInBps; // 100 (1%)
        uint256 maxDebt;
        uint256 MCR; // 12 * 1e17  (120%)
        address collVaultRouter; // set to address(0) if PositionManager coll is not CollateralVault
    }

    event NewDeployment(address collateral, address priceFeed, address positionManager, address sortedPositions);

    function deployNewInstance(
        address collateral,
        address priceFeed,
        address customPositionManagerImpl,
        address customSortedPositionsImpl,
        DeploymentParams calldata params,
        uint64 unlockRatePerSecond,
        bool forceThroughLspBalanceCheck
    ) external;

    function setImplementations(address _positionManagerImpl, address _sortedPositionsImpl) external;

    function CORE() external view returns (address);

    function borrowerOperations() external view returns (address);

    function debtToken() external view returns (address);

    function guardian() external view returns (address);

    function liquidationManager() external view returns (address);

    function owner() external view returns (address);

    function sortedPositionsImpl() external view returns (address);

    function liquidStabilityPool() external view returns (address);

    function positionManagerCount() external view returns (uint256);

    function positionManagerImpl() external view returns (address);

    function positionManagers(uint256) external view returns (address);
}

File 22 of 25 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.0;

/**
 * @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.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
        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
     *
     * _Available since v4.2._
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
        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
     *
     * _Available since v4.2._
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     *
     * _Available since v3.0._
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        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
     *
     * _Available since v4.7._
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
    }

    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
    }

    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
    }

    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
    }

    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
    }

    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     *
     * _Available since v3.0._
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {IMetaCore} from "./IMetaCore.sol";
import {IDebtToken} from "./IDebtToken.sol";
import {IDebtToken} from "./IDebtToken.sol";
import {EmissionsLib} from "src/libraries/EmissionsLib.sol";

interface ILiquidStabilityPool is IERC4626, IERC1822Proxiable {
    struct LSPStorage {
        IMetaCore metaCore;
        address feeReceiver;
        /// @notice Array of tokens that have been emitted to the LiquidStabilityPool
        /// @notice Used to track which tokens can be withdrawn to LSP share holders
        /// @dev Doesn't include tokens that are already collaterals
        EnumerableSet.AddressSet extraAssets;
        Queue queue;
        address[] collateralTokens;
        mapping(uint16 => SunsetIndex) _sunsetIndexes;
        mapping(address collateral => uint256 index) indexByCollateral;
        mapping(bytes32 => uint) threshold;
        EmissionsLib.BalanceData balanceData;
        mapping(address => bool) factoryProtocol;
        mapping(address => bool) liquidationManagerProtocol;
        mapping(address => bool) privilegedDebtRedeemers;
    }

    struct InitParams {
        IERC20 _asset;
        string _sharesName;
        string _sharesSymbol;
        IMetaCore _metaCore;
        address _liquidationManager;
        address _factory;
        address _feeReceiver;
    }

    struct RebalanceParams {
        address sentCurrency;
        uint sentAmount;
        address receivedCurrency;
        address swapper;
        bytes payload;
    }

    struct SunsetIndex {
        uint128 idx;
        uint128 expiry;
    }

    struct Queue {
        uint16 firstSunsetIndexKey;
        uint16 nextSunsetIndexKey;
    }

    event CollAndEmissionsWithdraw(
        address indexed receiver,
        uint shares,
        uint[] amounts
    );

    struct Arrays {
        uint length;
        address[] collaterals;
        uint collateralsLength;
        uint[] amounts;
    }

    event EmissionTokenAdded(address token);
    event EmissionTokenRemoved(address token);
    event StabilityPoolDebtBalanceUpdated(uint256 newBalance);
    event UserDepositChanged(address indexed depositor, uint256 newDeposit);
    event CollateralOverwritten(address oldCollateral, address newCollateral);

    // PROXY
    function upgradeToAndCall(address newImplementation, bytes calldata data) external;
    function getCurrentImplementation() external view returns (address);

    function SUNSET_DURATION() external view returns (uint128);
    function totalDebtTokenDeposits() external view returns (uint256);
    function enableCollateral(address _collateral, uint64 _unlockRatePerSecond, bool forceThroughBalanceCheck) external;
    function startCollateralSunset(address collateral) external;
    function getTotalDebtTokenDeposits() external view returns (uint256);
    function getCollateralTokens() external view returns (address[] memory);
    function offset(address collateral, uint256 _debtToOffset, uint256 _collToAdd) external;
    function initialize(InitParams calldata params) external;
    function rebalance(RebalanceParams calldata p) external;
    function linearVestingExtraAssets(address token, int amount, address recipient) external;
    function withdraw(
        uint assets,
        address[] calldata preferredUnderlyingTokens,
        address receiver,
        address _owner
    ) external returns (uint shares);
    function redeem(
        uint shares,
        address[] calldata preferredUnderlyingTokens,
        address receiver,
        address _owner
    ) external returns (uint assets);
    function updateProtocol(
        address _liquidationManager, 
        address _factory,
        bool _register
    ) external;

    function redeem(
        uint assets,
        address receiver
    ) external returns (uint shares);
    function addNewExtraAsset(address token, uint64 _unlockRatePerSecond) external;
    function removeEmitedTokens(address token) external;
    function setPairThreshold(address tokenIn, address tokenOut, uint thresholdInBP) external;
    function setUnlockRatePerSecond(address token, uint64 _unlockRatePerSecond) external;
    function getPrice(address token) external view returns (uint);
    function getLockedEmissions(address token) external view returns (uint);
    function extSloads(bytes32[] calldata slots) external view returns (bytes32[] memory res);
    function unlockRatePerSecond(address token) external view returns (uint);
    function removeExtraAsset(address token) external;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

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

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

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

File 25 of 25 : IDebtToken.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.26;

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

interface IDebtToken is IERC20 {
    // --- Events ---
    event FlashLoanFeeUpdated(uint256 newFee);

    // --- Public constants ---
    function version() external view returns (string memory);
    function permitTypeHash() external view returns (bytes32);

    // --- Public immutables ---
    function gasPool() external view returns (address);
    function DEBT_GAS_COMPENSATION() external view returns (uint256);

    // --- Public mappings ---
    function liquidStabilityPools(address) external view returns (bool);
    function borrowerOperations(address) external view returns (bool);
    function factories(address) external view returns (bool);
    function peripheries(address) external view returns (bool);
    function positionManagers(address) external view returns (bool);

    // --- External functions ---

    function enablePositionManager(address _positionManager) external;
    function mintWithGasCompensation(address _account, uint256 _amount) external returns (bool);
    function burnWithGasCompensation(address _account, uint256 _amount) external returns (bool);
    function mint(address _account, uint256 _amount) external;
    function burn(address _account, uint256 _amount) external;
    function decimals() external view returns (uint8);
    function sendToPeriphery(address _sender, uint256 _amount) external;
    function sendToSP(address _sender, uint256 _amount) external;
    function returnFromPool(address _poolAddress, address _receiver, uint256 _amount) external;
    function transfer(address recipient, uint256 amount) external returns (bool);
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
    function maxFlashLoan(address token) external view returns (uint256);
    function flashFee(address token, uint256 amount) external view returns (uint256);
    function flashLoan(
        IERC3156FlashBorrower receiver,
        address token,
        uint256 amount,
        bytes calldata data
    ) external returns (bool);
    function whitelistLiquidStabilityPoolAddress(address _liquidStabilityPool, bool active) external;
    function whitelistBorrowerOperationsAddress(address _borrowerOperations, bool active) external;
    function whitelistFactoryAddress(address _factory, bool active) external;
    function whitelistPeripheryAddress(address _periphery, bool active) external;
    function whitelistPSM(address, bool) external;
    function setDebtGasCompensation(uint256 _gasCompensation, bool _isFinalValue) external;
    function setFlashLoanFee(uint256 _fee) external;
    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function permit(
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;
    function nonces(address owner) external view returns (uint256);
}

Settings
{
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin-upgradeable/contracts/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "solady/=lib/solady/src/",
    "@solmate/=lib/solmate/src/",
    "@chimera/=lib/chimera/src/",
    "forge-std/=lib/forge-std/src/",
    "@uniswap/v3-core/=lib/v3-core/",
    "@uniswap/v3-periphery/=lib/v3-periphery/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "chimera/=lib/chimera/src/",
    "ds-test/=lib/solmate/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "rewards/=lib/rewards/",
    "solmate/=lib/solmate/src/",
    "uniswap/=lib/uniswap/",
    "v3-core/=lib/v3-core/contracts/",
    "v3-periphery/=lib/v3-periphery/contracts/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 1
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": false
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_metaCore","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"PriceFeed__FeedFrozenError","type":"error"},{"inputs":[],"name":"PriceFeed__HeartbeatOutOfBoundsError","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"PriceFeed__InvalidFeedResponseError","type":"error"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"PriceFeed__InvalidResponse","type":"error"},{"inputs":[],"name":"PriceFeed__PotentialDos","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"collVault","type":"address"},{"indexed":false,"internalType":"bool","name":"enable","type":"bool"}],"name":"NewCollVaultRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"address","name":"chainlinkAggregator","type":"address"},{"indexed":false,"internalType":"address","name":"underlyingDerivative","type":"address"}],"name":"NewOracleRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"address","name":"spotOracle","type":"address"}],"name":"NewSpotOracleRegistered","type":"event"},{"inputs":[],"name":"CORE","outputs":[{"internalType":"contract ICore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_ORACLE_HEARTBEAT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TARGET_DIGITS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"feedType","outputs":[{"internalType":"contract ISpotOracle","name":"spotOracle","type":"address"},{"internalType":"bool","name":"isCollVault","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"fetchPrice","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"_tokens","type":"address[]"}],"name":"getMultiplePrices","outputs":[{"internalType":"uint256[]","name":"prices","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"getSpotOracle","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"guardian","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"isCollVault","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"oracleRecords","outputs":[{"internalType":"contract IAggregatorV3Interface","name":"chainLinkOracle","type":"address"},{"internalType":"uint8","name":"decimals","type":"uint8"},{"internalType":"uint32","name":"heartbeat","type":"uint32"},{"internalType":"uint16","name":"staleThreshold","type":"uint16"},{"internalType":"address","name":"underlyingDerivative","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_chainlinkOracle","type":"address"},{"internalType":"uint32","name":"_heartbeat","type":"uint32"},{"internalType":"uint16","name":"_staleThreshold","type":"uint16"},{"internalType":"address","name":"underlyingDerivative","type":"address"}],"name":"setOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_spotOracle","type":"address"}],"name":"setSpotOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"bool","name":"_enable","type":"bool"}],"name":"whitelistCollateralVault","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60a060405234801561000f575f80fd5b5060405161189638038061189683398101604081905261002e91610093565b6001600160a01b038116608081905261008d5760405162461bcd60e51b815260206004820152601460248201527f5072696365466565643a20302061646472657373000000000000000000000000604482015260640160405180910390fd5b506100c0565b5f602082840312156100a3575f80fd5b81516001600160a01b03811681146100b9575f80fd5b9392505050565b60805161179b6100fb5f395f818161014f015281816102e00152818161075a015281816107e001528181610ad20152610c73015261179b5ff3fe608060405234801561000f575f80fd5b50600436106100c3575f3560e01c8063068d4664146100c757806315fb33ba146100dc5780631be5c92f1461011d578063452a93201461013357806358a6aa881461013b5780636b6c07741461014a578063771bc577146101715780637cdde506146101b35780638da5cb5b14610250578063a1c7ffb314610258578063a8a0c62f14610278578063ace1798e14610282578063b13d368914610295578063e1bdd0a6146102a8578063fafa76b3146102cb575b5f80fd5b6100da6100d5366004611255565b6102de565b005b6101076100ea3660046112d0565b6001600160a01b039081165f908152600160205260409020541690565b60405161011491906112eb565b60405180910390f35b610125601281565b604051908152602001610114565b610107610757565b6101256706f05b59d3b2000081565b6101077f000000000000000000000000000000000000000000000000000000000000000081565b6101a561017f3660046112d0565b60016020525f90815260409020546001600160a01b03811690600160a01b900460ff1682565b6040516101149291906112ff565b61020c6101c13660046112d0565b5f60208190529081526040902080546001909101546001600160a01b0380831692600160a01b810460ff1692600160a81b820463ffffffff1692600160c81b90920461ffff16911685565b604080516001600160a01b03968716815260ff909516602086015263ffffffff9093169284019290925261ffff16606083015291909116608082015260a001610114565b6101076107dd565b61026b61026636600461132e565b61083a565b60405161011491906113f8565b6101256202a30081565b6101256102903660046112d0565b6108db565b6100da6102a336600461143a565b610ad0565b6102bb6102b63660046112d0565b610c4d565b6040519015158152602001610114565b6100da6102d9366004611475565b610c71565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561033a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061035e91906114a1565b6001600160a01b0316336001600160a01b0316146103975760405162461bcd60e51b815260040161038e906114bc565b60405180910390fd5b806001600160a01b0316856001600160a01b0316036104085760405162461bcd60e51b815260206004820152602760248201527f5072696365466565643a20746f6b656e2063616e6e6f7420706f696e7420746f6044820152661034ba39b2b63360c91b606482015260840161038e565b6001600160a01b038181165f9081526020819052604090206001015416156104715760405162461bcd60e51b815260206004820152601c60248201527b5072696365466565643a206f6e6c7920746f2055534420706169727360201b604482015260640161038e565b61047a85610df2565b801561048c575061048a85610c4d565b155b6104a85760405162461bcd60e51b815260040161038e906114e0565b6202a3008363ffffffff1611156104d257604051632280d48b60e21b815260040160405180910390fd5b835f806104de83610e10565b90925090506001600160a01b03881661050a5760405163286be11f60e21b815260040160405180910390fd5b6105148282610e3f565b61053357876040516312b2728d60e21b815260040161038e91906112eb565b61054882604001518763ffffffff1687610e59565b156105685787604051633beb416d60e11b815260040161038e91906112eb565b5f6040518060a00160405280856001600160a01b03168152602001856001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156105bf573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105e39190611524565b60ff1681526020018863ffffffff1681526020018761ffff168152602001866001600160a01b03168152509050805f808b6001600160a01b03166001600160a01b031681526020019081526020015f205f820151815f015f6101000a8154816001600160a01b0302191690836001600160a01b031602179055506020820151815f0160146101000a81548160ff021916908360ff1602179055506040820151815f0160156101000a81548163ffffffff021916908363ffffffff1602179055506060820151815f0160196101000a81548161ffff021916908361ffff1602179055506080820151816001015f6101000a8154816001600160a01b0302191690836001600160a01b0316021790555090505061070089828585610e7b565b50604080516001600160a01b038b811682528a8116602083015287168183015290517f1c25fa8a4ce2bfaf59b4c787f30bec3ec45c2e795b27864b088c2ba52cde99ca9181900360600190a1505050505050505050565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663452a93206040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107b4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107d891906114a1565b905090565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107b4573d5f803e3d5ffd5b8051606090806001600160401b038111156108575761085761131a565b604051908082528060200260200182016040528015610880578160200160208202803683370190505b5091505f5b818110156108d4576108af8482815181106108a2576108a2611544565b60200260200101516108db565b8382815181106108c1576108c1611544565b6020908102919091010152600101610885565b5050919050565b6001600160a01b0381165f90815260016020526040812054600160a01b900460ff161561096857816001600160a01b0316630fdb11cf6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561093e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109629190611558565b92915050565b6001600160a01b038083165f908152600160205260409020541680156109ef57806001600160a01b0316630fdb11cf6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156109c4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109e89190611558565b9392505050565b6001600160a01b038381165f9081526020818152604091829020825160a0810184528154808616808352600160a01b820460ff1694830194909452600160a81b810463ffffffff1694820194909452600160c81b90930461ffff16606084015260010154909216608082015290610aa85760405162461bcd60e51b815260206004820152601e60248201527f5072696365466565643a20746f6b656e206e6f7420737570706f727465640000604482015260640161038e565b5f80610ab6835f0151610e10565b91509150610ac686848484610e7b565b9695505050505050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b2c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b5091906114a1565b6001600160a01b0316336001600160a01b031614610b805760405162461bcd60e51b815260040161038e906114bc565b6001600160a01b038216610ba65760405162461bcd60e51b815260040161038e9061156f565b801580610bc75750610bb782610f55565b8015610bc75750610bc782610df2565b610be35760405162461bcd60e51b815260040161038e906114e0565b6001600160a01b0382165f9081526001602052604090819020805460ff60a01b1916600160a01b84151502179055517f93b4211dd03330927c329a2e00965b8a192dbb3b750cfd1181c5755193eda0fe90610c4190849084906112ff565b60405180910390a15050565b6001600160a01b03165f90815260016020526040902054600160a01b900460ff1690565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ccd573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cf191906114a1565b6001600160a01b0316336001600160a01b031614610d215760405162461bcd60e51b815260040161038e906114bc565b6001600160a01b038216610d475760405162461bcd60e51b815260040161038e9061156f565b6001600160a01b0381161580610d735750610d6182610f55565b8015610d735750610d7182610c4d565b155b610d8f5760405162461bcd60e51b815260040161038e906114e0565b6001600160a01b038281165f8181526001602090815260409182902080546001600160a01b031916948616948517905581519283528201929092527f245f530f8f20a4bced981681e908c04fe2da3fff4d915cdb2df5a80220b66fa49101610c41565b6001600160a01b039081165f90815260016020526040902054161590565b610e18611204565b610e20611204565b610e2983610f73565b9150610e3883835f0151611004565b9050915091565b5f610e49836110b2565b80156109e857506109e8826110b2565b5f610e6861ffff8316846115b7565b610e7285426115ca565b11949350505050565b60208301515f9081610e8d8585610e3f565b8015610eb35750610eb18560400151876040015163ffffffff168860600151610e59565b155b8015610ec75750610ec58585846110fd565b155b90508015610f32575f610ee186602001518460ff16611180565b60808801519091506001600160a01b031615610f28575f610f0588608001516108db565b9050670de0b6b3a7640000610f1a82846115dd565b610f2491906115f4565b9150505b9250610f4d915050565b866040516309f95d0f60e01b815260040161038e91906112eb565b949350505050565b6001600160a01b039081165f90815260208190526040902054161590565b610f7b611204565b816001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa925050508015610fd5575060408051601f3d908101601f19168201909252610fd291810190611629565b60015b610fde57919050565b506001600160501b0390931684525060208301526040820152600160608201525b919050565b61100c611204565b6001600160501b0382161561096257604051639a6fc8f560e01b81526001600160501b035f1984011660048201526001600160a01b03841690639a6fc8f59060240160a060405180830381865afa925050508015611087575060408051601f3d908101601f1916820190925261108491810190611629565b60015b1561096257506001600160501b03909316845250602083015260408201526001606082015292915050565b5f816060015180156110cd575081516001600160501b031615155b80156110dc5750604082015115155b80156110ec575042826040015111155b8015610962575050602001515f1290565b5f8061111085602001518460ff16611180565b90505f61112485602001518560ff16611180565b90505f61113183836111e0565b90505f61113e84846111f5565b90505f83670de0b6b3a764000061115585856115ca565b61115f91906115dd565b61116991906115f4565b6706f05b59d3b20000109998505050505050505050565b5f60128203611190575081610962565b60128210156111c0576111a48260126115ca565b6111af90600a61175a565b6111b990846115dd565b9050610962565b6111cb6012836115ca565b6111d690600a61175a565b6111b990846115f4565b5f8183106111ee57816109e8565b5090919050565b5f818310156111ee57816109e8565b60405180608001604052805f6001600160501b031681526020015f81526020015f81526020015f151581525090565b6001600160a01b0381168114611247575f80fd5b50565b8035610fff81611233565b5f805f805f60a08688031215611269575f80fd5b853561127481611233565b9450602086013561128481611233565b9350604086013563ffffffff8116811461129c575f80fd5b9250606086013561ffff811681146112b2575f80fd5b915060808601356112c281611233565b809150509295509295909350565b5f602082840312156112e0575f80fd5b81356109e881611233565b6001600160a01b0391909116815260200190565b6001600160a01b039290921682521515602082015260400190565b634e487b7160e01b5f52604160045260245ffd5b5f6020828403121561133e575f80fd5b81356001600160401b03811115611353575f80fd5b8201601f81018413611363575f80fd5b80356001600160401b0381111561137c5761137c61131a565b604051600582901b90603f8201601f191681016001600160401b03811182821017156113aa576113aa61131a565b6040529182526020818401810192908101878411156113c7575f80fd5b6020850194505b838510156113ed576113df8561124a565b8152602094850194016113ce565b509695505050505050565b602080825282518282018190525f918401906040840190835b8181101561142f578351835260209384019390920191600101611411565b509095945050505050565b5f806040838503121561144b575f80fd5b823561145681611233565b91506020830135801515811461146a575f80fd5b809150509250929050565b5f8060408385031215611486575f80fd5b823561149181611233565b9150602083013561146a81611233565b5f602082840312156114b1575f80fd5b81516109e881611233565b6020808252600a908201526927b7363c9037bbb732b960b11b604082015260600190565b60208082526024908201527f5072696365466565643a20746f6b656e20616c72656164792077686974656c696040820152631cdd195960e21b606082015260800190565b5f60208284031215611534575f80fd5b815160ff811681146109e8575f80fd5b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215611568575f80fd5b5051919050565b6020808252601a90820152795072696365466565643a20746f6b656e2030206164647265737360301b604082015260600190565b634e487b7160e01b5f52601160045260245ffd5b80820180821115610962576109626115a3565b81810381811115610962576109626115a3565b8082028115828204841417610962576109626115a3565b5f8261160e57634e487b7160e01b5f52601260045260245ffd5b500490565b80516001600160501b0381168114610fff575f80fd5b5f805f805f60a0868803121561163d575f80fd5b61164686611613565b6020870151604088015160608901519297509095509350915061166b60808701611613565b90509295509295909350565b6001815b60018411156116b257808504811115611696576116966115a3565b60018416156116a457908102905b60019390931c92800261167b565b935093915050565b5f826116c857506001610962565b816116d457505f610962565b81600181146116ea57600281146116f457611710565b6001915050610962565b60ff841115611705576117056115a3565b50506001821b610962565b5060208310610133831016604e8410600b8410161715611733575081810a610962565b61173f5f198484611677565b805f1904821115611752576117526115a3565b029392505050565b5f6109e883836116ba56fea26469706673582212200d07e57c5f637b428656fc5b3b1657f51031776d20bd82c5643c755f745d874564736f6c634300081a00330000000000000000000000008700af942be2a6e5566306d0ee7bcc5a3a6e0ce8

Deployed Bytecode

0x608060405234801561000f575f80fd5b50600436106100c3575f3560e01c8063068d4664146100c757806315fb33ba146100dc5780631be5c92f1461011d578063452a93201461013357806358a6aa881461013b5780636b6c07741461014a578063771bc577146101715780637cdde506146101b35780638da5cb5b14610250578063a1c7ffb314610258578063a8a0c62f14610278578063ace1798e14610282578063b13d368914610295578063e1bdd0a6146102a8578063fafa76b3146102cb575b5f80fd5b6100da6100d5366004611255565b6102de565b005b6101076100ea3660046112d0565b6001600160a01b039081165f908152600160205260409020541690565b60405161011491906112eb565b60405180910390f35b610125601281565b604051908152602001610114565b610107610757565b6101256706f05b59d3b2000081565b6101077f0000000000000000000000008700af942be2a6e5566306d0ee7bcc5a3a6e0ce881565b6101a561017f3660046112d0565b60016020525f90815260409020546001600160a01b03811690600160a01b900460ff1682565b6040516101149291906112ff565b61020c6101c13660046112d0565b5f60208190529081526040902080546001909101546001600160a01b0380831692600160a01b810460ff1692600160a81b820463ffffffff1692600160c81b90920461ffff16911685565b604080516001600160a01b03968716815260ff909516602086015263ffffffff9093169284019290925261ffff16606083015291909116608082015260a001610114565b6101076107dd565b61026b61026636600461132e565b61083a565b60405161011491906113f8565b6101256202a30081565b6101256102903660046112d0565b6108db565b6100da6102a336600461143a565b610ad0565b6102bb6102b63660046112d0565b610c4d565b6040519015158152602001610114565b6100da6102d9366004611475565b610c71565b7f0000000000000000000000008700af942be2a6e5566306d0ee7bcc5a3a6e0ce86001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561033a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061035e91906114a1565b6001600160a01b0316336001600160a01b0316146103975760405162461bcd60e51b815260040161038e906114bc565b60405180910390fd5b806001600160a01b0316856001600160a01b0316036104085760405162461bcd60e51b815260206004820152602760248201527f5072696365466565643a20746f6b656e2063616e6e6f7420706f696e7420746f6044820152661034ba39b2b63360c91b606482015260840161038e565b6001600160a01b038181165f9081526020819052604090206001015416156104715760405162461bcd60e51b815260206004820152601c60248201527b5072696365466565643a206f6e6c7920746f2055534420706169727360201b604482015260640161038e565b61047a85610df2565b801561048c575061048a85610c4d565b155b6104a85760405162461bcd60e51b815260040161038e906114e0565b6202a3008363ffffffff1611156104d257604051632280d48b60e21b815260040160405180910390fd5b835f806104de83610e10565b90925090506001600160a01b03881661050a5760405163286be11f60e21b815260040160405180910390fd5b6105148282610e3f565b61053357876040516312b2728d60e21b815260040161038e91906112eb565b61054882604001518763ffffffff1687610e59565b156105685787604051633beb416d60e11b815260040161038e91906112eb565b5f6040518060a00160405280856001600160a01b03168152602001856001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156105bf573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105e39190611524565b60ff1681526020018863ffffffff1681526020018761ffff168152602001866001600160a01b03168152509050805f808b6001600160a01b03166001600160a01b031681526020019081526020015f205f820151815f015f6101000a8154816001600160a01b0302191690836001600160a01b031602179055506020820151815f0160146101000a81548160ff021916908360ff1602179055506040820151815f0160156101000a81548163ffffffff021916908363ffffffff1602179055506060820151815f0160196101000a81548161ffff021916908361ffff1602179055506080820151816001015f6101000a8154816001600160a01b0302191690836001600160a01b0316021790555090505061070089828585610e7b565b50604080516001600160a01b038b811682528a8116602083015287168183015290517f1c25fa8a4ce2bfaf59b4c787f30bec3ec45c2e795b27864b088c2ba52cde99ca9181900360600190a1505050505050505050565b5f7f0000000000000000000000008700af942be2a6e5566306d0ee7bcc5a3a6e0ce86001600160a01b031663452a93206040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107b4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107d891906114a1565b905090565b5f7f0000000000000000000000008700af942be2a6e5566306d0ee7bcc5a3a6e0ce86001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107b4573d5f803e3d5ffd5b8051606090806001600160401b038111156108575761085761131a565b604051908082528060200260200182016040528015610880578160200160208202803683370190505b5091505f5b818110156108d4576108af8482815181106108a2576108a2611544565b60200260200101516108db565b8382815181106108c1576108c1611544565b6020908102919091010152600101610885565b5050919050565b6001600160a01b0381165f90815260016020526040812054600160a01b900460ff161561096857816001600160a01b0316630fdb11cf6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561093e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109629190611558565b92915050565b6001600160a01b038083165f908152600160205260409020541680156109ef57806001600160a01b0316630fdb11cf6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156109c4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109e89190611558565b9392505050565b6001600160a01b038381165f9081526020818152604091829020825160a0810184528154808616808352600160a01b820460ff1694830194909452600160a81b810463ffffffff1694820194909452600160c81b90930461ffff16606084015260010154909216608082015290610aa85760405162461bcd60e51b815260206004820152601e60248201527f5072696365466565643a20746f6b656e206e6f7420737570706f727465640000604482015260640161038e565b5f80610ab6835f0151610e10565b91509150610ac686848484610e7b565b9695505050505050565b7f0000000000000000000000008700af942be2a6e5566306d0ee7bcc5a3a6e0ce86001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b2c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b5091906114a1565b6001600160a01b0316336001600160a01b031614610b805760405162461bcd60e51b815260040161038e906114bc565b6001600160a01b038216610ba65760405162461bcd60e51b815260040161038e9061156f565b801580610bc75750610bb782610f55565b8015610bc75750610bc782610df2565b610be35760405162461bcd60e51b815260040161038e906114e0565b6001600160a01b0382165f9081526001602052604090819020805460ff60a01b1916600160a01b84151502179055517f93b4211dd03330927c329a2e00965b8a192dbb3b750cfd1181c5755193eda0fe90610c4190849084906112ff565b60405180910390a15050565b6001600160a01b03165f90815260016020526040902054600160a01b900460ff1690565b7f0000000000000000000000008700af942be2a6e5566306d0ee7bcc5a3a6e0ce86001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ccd573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cf191906114a1565b6001600160a01b0316336001600160a01b031614610d215760405162461bcd60e51b815260040161038e906114bc565b6001600160a01b038216610d475760405162461bcd60e51b815260040161038e9061156f565b6001600160a01b0381161580610d735750610d6182610f55565b8015610d735750610d7182610c4d565b155b610d8f5760405162461bcd60e51b815260040161038e906114e0565b6001600160a01b038281165f8181526001602090815260409182902080546001600160a01b031916948616948517905581519283528201929092527f245f530f8f20a4bced981681e908c04fe2da3fff4d915cdb2df5a80220b66fa49101610c41565b6001600160a01b039081165f90815260016020526040902054161590565b610e18611204565b610e20611204565b610e2983610f73565b9150610e3883835f0151611004565b9050915091565b5f610e49836110b2565b80156109e857506109e8826110b2565b5f610e6861ffff8316846115b7565b610e7285426115ca565b11949350505050565b60208301515f9081610e8d8585610e3f565b8015610eb35750610eb18560400151876040015163ffffffff168860600151610e59565b155b8015610ec75750610ec58585846110fd565b155b90508015610f32575f610ee186602001518460ff16611180565b60808801519091506001600160a01b031615610f28575f610f0588608001516108db565b9050670de0b6b3a7640000610f1a82846115dd565b610f2491906115f4565b9150505b9250610f4d915050565b866040516309f95d0f60e01b815260040161038e91906112eb565b949350505050565b6001600160a01b039081165f90815260208190526040902054161590565b610f7b611204565b816001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa925050508015610fd5575060408051601f3d908101601f19168201909252610fd291810190611629565b60015b610fde57919050565b506001600160501b0390931684525060208301526040820152600160608201525b919050565b61100c611204565b6001600160501b0382161561096257604051639a6fc8f560e01b81526001600160501b035f1984011660048201526001600160a01b03841690639a6fc8f59060240160a060405180830381865afa925050508015611087575060408051601f3d908101601f1916820190925261108491810190611629565b60015b1561096257506001600160501b03909316845250602083015260408201526001606082015292915050565b5f816060015180156110cd575081516001600160501b031615155b80156110dc5750604082015115155b80156110ec575042826040015111155b8015610962575050602001515f1290565b5f8061111085602001518460ff16611180565b90505f61112485602001518560ff16611180565b90505f61113183836111e0565b90505f61113e84846111f5565b90505f83670de0b6b3a764000061115585856115ca565b61115f91906115dd565b61116991906115f4565b6706f05b59d3b20000109998505050505050505050565b5f60128203611190575081610962565b60128210156111c0576111a48260126115ca565b6111af90600a61175a565b6111b990846115dd565b9050610962565b6111cb6012836115ca565b6111d690600a61175a565b6111b990846115f4565b5f8183106111ee57816109e8565b5090919050565b5f818310156111ee57816109e8565b60405180608001604052805f6001600160501b031681526020015f81526020015f81526020015f151581525090565b6001600160a01b0381168114611247575f80fd5b50565b8035610fff81611233565b5f805f805f60a08688031215611269575f80fd5b853561127481611233565b9450602086013561128481611233565b9350604086013563ffffffff8116811461129c575f80fd5b9250606086013561ffff811681146112b2575f80fd5b915060808601356112c281611233565b809150509295509295909350565b5f602082840312156112e0575f80fd5b81356109e881611233565b6001600160a01b0391909116815260200190565b6001600160a01b039290921682521515602082015260400190565b634e487b7160e01b5f52604160045260245ffd5b5f6020828403121561133e575f80fd5b81356001600160401b03811115611353575f80fd5b8201601f81018413611363575f80fd5b80356001600160401b0381111561137c5761137c61131a565b604051600582901b90603f8201601f191681016001600160401b03811182821017156113aa576113aa61131a565b6040529182526020818401810192908101878411156113c7575f80fd5b6020850194505b838510156113ed576113df8561124a565b8152602094850194016113ce565b509695505050505050565b602080825282518282018190525f918401906040840190835b8181101561142f578351835260209384019390920191600101611411565b509095945050505050565b5f806040838503121561144b575f80fd5b823561145681611233565b91506020830135801515811461146a575f80fd5b809150509250929050565b5f8060408385031215611486575f80fd5b823561149181611233565b9150602083013561146a81611233565b5f602082840312156114b1575f80fd5b81516109e881611233565b6020808252600a908201526927b7363c9037bbb732b960b11b604082015260600190565b60208082526024908201527f5072696365466565643a20746f6b656e20616c72656164792077686974656c696040820152631cdd195960e21b606082015260800190565b5f60208284031215611534575f80fd5b815160ff811681146109e8575f80fd5b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215611568575f80fd5b5051919050565b6020808252601a90820152795072696365466565643a20746f6b656e2030206164647265737360301b604082015260600190565b634e487b7160e01b5f52601160045260245ffd5b80820180821115610962576109626115a3565b81810381811115610962576109626115a3565b8082028115828204841417610962576109626115a3565b5f8261160e57634e487b7160e01b5f52601260045260245ffd5b500490565b80516001600160501b0381168114610fff575f80fd5b5f805f805f60a0868803121561163d575f80fd5b61164686611613565b6020870151604088015160608901519297509095509350915061166b60808701611613565b90509295509295909350565b6001815b60018411156116b257808504811115611696576116966115a3565b60018416156116a457908102905b60019390931c92800261167b565b935093915050565b5f826116c857506001610962565b816116d457505f610962565b81600181146116ea57600281146116f457611710565b6001915050610962565b60ff841115611705576117056115a3565b50506001821b610962565b5060208310610133831016604e8410600b8410161715611733575081810a610962565b61173f5f198484611677565b805f1904821115611752576117526115a3565b029392505050565b5f6109e883836116ba56fea26469706673582212200d07e57c5f637b428656fc5b3b1657f51031776d20bd82c5643c755f745d874564736f6c634300081a0033

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

0000000000000000000000008700af942be2a6e5566306d0ee7bcc5a3a6e0ce8

-----Decoded View---------------
Arg [0] : _metaCore (address): 0x8700AF942BE2A6E5566306D0eE7Bcc5a3A6E0ce8

-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 0000000000000000000000008700af942be2a6e5566306d0ee7bcc5a3a6e0ce8


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

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.