ETH Price: $3,112.56 (-0.26%)

Contract

0x3516224e7BE8bC19a07FF79A96AC98839411A7F4
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
0x60806040202945592024-07-13 2:19:23130 days ago1720837163IN
 Create: RepricingOracle
0 ETH0.004435781.65998815

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
RepricingOracle

Compiler Version
v0.8.16+commit.07a7930e

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion
File 1 of 62 : RepricingOracle.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.16;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {IRepricingOracle} from "../interfaces/IRepricingOracle.sol";
import {Repricing, RepriceSnapshot, BalancesSnapshot, RepriceSnapshotState, UpgradeableRepriceSnapshot, WithdrawSnapshotState} from "../libraries/Repricing.sol";
import {IrswETH} from "../interfaces/IrswETH.sol";
import {IrswEXIT} from "../interfaces/IrswEXIT.sol";
import {IAccessControlManager} from "../interfaces/IAccessControlManager.sol";
import {SwellLib} from "../libraries/SwellLib.sol";
import {AggregatorV3Interface} from "../vendors/AggregatorV3Interface.sol";
import {UD60x18, wrap} from "@prb/math/src/UD60x18.sol";

/**
 * @title RepricingOracle
 * @author https://github.com/SwellNetwork
 * @notice This contract receives snapshots from the execution bot and reprices swETH
 */
contract RepricingOracle is IRepricingOracle, Initializable {
  using SafeERC20 for IERC20;
  using Repricing for BalancesSnapshot;

  IAccessControlManager public AccessControlManager;
  AggregatorV3Interface public override ExternalV3ReservesPoROracle;

  uint256 public override maximumRepriceBlockAtSnapshotStaleness;
  uint256 public override maximumRepriceV3ReservesExternalPoRDiffPercentage;

  RepriceSnapshot private _lastRepriceSnapshot; // ! This has been deprecated in favor of the snapshots mapping, we are using a mapping because we want to allow changes to the Snapshot struct in future. This has to be kept here for compability with the storage layout of the previous version of this contract. There is also additional handling in this contract to support the old snapshot when this contract is first upgraded.

  // Using unstructured storage layout for this struct so that we can upgrade the struct in future
  bytes32 internal constant SNAPSHOT_STRUCT_SLOT =
    keccak256("swell.Swell.snapshotStructSlot");

  uint256 public override maximumRoundDataStalenessTime;
  uint256 public override maximumReferencePriceDiffPercentage;

  // This reads from storage so cannot be a pure function
  function getSnapshotStruct()
    internal
    view
    returns (UpgradeableRepriceSnapshot storage s)
  {
    bytes32 slot = SNAPSHOT_STRUCT_SLOT;
    assembly {
      s.slot := slot
    }
  }

  /// @custom:oz-upgrades-unsafe-allow constructor
  constructor() {
    _disableInitializers();
  }

  modifier checkRole(bytes32 role) {
    AccessControlManager.checkRole(role, msg.sender);
    _;
  }

  /**
   * @dev Modifier to check for empty addresses
   * @param _address The address to check
   */
  modifier checkZeroAddress(address _address) {
    SwellLib._checkZeroAddress(_address);

    _;
  }

  fallback() external {
    revert SwellLib.InvalidMethodCall();
  }

  function initialize(
    IAccessControlManager _accessControlManager,
    AggregatorV3Interface _externalV3ReservesPoROracle
  ) external initializer checkZeroAddress(address(_accessControlManager)) {
    AccessControlManager = _accessControlManager;
    ExternalV3ReservesPoROracle = _externalV3ReservesPoROracle;
  }

  // ************************************
  // ***** External methods ******

  function withdrawERC20(
    IERC20 _token
  ) external override checkRole(SwellLib.PLATFORM_ADMIN) {
    uint256 contractBalance = _token.balanceOf(address(this));
    if (contractBalance == 0) {
      revert SwellLib.NoTokensToWithdraw();
    }

    _token.safeTransfer(msg.sender, contractBalance);
  }

  // ** Execution bot methods **

  function submitSnapshot(
    UpgradeableRepriceSnapshot calldata _snapshot
  ) external override checkRole(SwellLib.BOT) {
    if (AccessControlManager.botMethodsPaused()) {
      revert SwellLib.BotMethodsPaused();
    }
    ExternalV3ReservesResult
      memory externalV3ReservesResult = _externalV3ReservesLatestRoundData();
    _assertRepricingSnapshotValidity(_snapshot, externalV3ReservesResult);

    uint256 rswETHToETHRate = AccessControlManager.rswETH().rswETHToETHRate();
    uint256 referenceOnChainRate = _referenceOnChainRate(
      _snapshot.state,
      _snapshot.withdrawState,
      externalV3ReservesResult
    );

    handleReprice(_snapshot);

    uint256 newRswETHToETHRate = AccessControlManager
      .rswETH()
      .rswETHToETHRate();
    _checkReferencePriceDiff(
      newRswETHToETHRate,
      referenceOnChainRate,
      maximumReferencePriceDiffPercentage
    );

    if (rswETHToETHRate > newRswETHToETHRate) {
      AccessControlManager.lockdown();
    }
  }

  function submitSnapshotV2(
    bytes[] calldata activeValidatorsToDelete,
    UpgradeableRepriceSnapshot calldata _snapshot,
    uint256 lastTokenIDToProcess
  ) external override checkRole(SwellLib.BOT) {
    if (AccessControlManager.botMethodsPaused()) {
      revert SwellLib.BotMethodsPaused();
    }
    ExternalV3ReservesResult
      memory externalV3ReservesResult = _externalV3ReservesLatestRoundData();
    _assertRepricingSnapshotValidity(_snapshot, externalV3ReservesResult);

    if (activeValidatorsToDelete.length > 0) {
      AccessControlManager.NodeOperatorRegistry().deleteActiveValidators(
        activeValidatorsToDelete
      );
    }

    uint256 rswETHToETHRate = AccessControlManager.rswETH().rswETHToETHRate();
    uint256 referenceOnChainRate = _referenceOnChainRate(
      _snapshot.state,
      _snapshot.withdrawState,
      externalV3ReservesResult
    );

    handleReprice(_snapshot);

    uint256 newRswETHToETHRate = AccessControlManager
      .rswETH()
      .rswETHToETHRate();
    _checkReferencePriceDiff(
      newRswETHToETHRate,
      referenceOnChainRate,
      maximumReferencePriceDiffPercentage
    );

    if (rswETHToETHRate > newRswETHToETHRate) {
      AccessControlManager.lockdown();
    }

    if (!AccessControlManager.withdrawalsPaused()) {
      AccessControlManager.rswEXIT().processWithdrawals(lastTokenIDToProcess);
    }
  }

  // ** PLATFORM_ADMIN management methods **

  function setExternalV3ReservesPoROracleAddress(
    address _newAddress
  ) external override checkRole(SwellLib.PLATFORM_ADMIN) {
    emit ExternalV3ReservesPoROracleAddressUpdated(
      address(ExternalV3ReservesPoROracle),
      _newAddress
    );
    ExternalV3ReservesPoROracle = AggregatorV3Interface(_newAddress);
  }

  function setMaximumRepriceBlockAtSnapshotStaleness(
    uint256 _maximumRepriceBlockAtSnapshotStaleness
  ) external override checkRole(SwellLib.PLATFORM_ADMIN) {
    emit MaximumRepriceBlockAtSnapshotStalenessUpdated(
      maximumRepriceBlockAtSnapshotStaleness,
      _maximumRepriceBlockAtSnapshotStaleness
    );

    maximumRepriceBlockAtSnapshotStaleness = _maximumRepriceBlockAtSnapshotStaleness;
  }

  function setMaximumRepriceV3ReservesExternalPoRDiffPercentage(
    uint256 _newMaximumRepriceV3ReservesExternalPoRDiffPercentage
  ) external override checkRole(SwellLib.PLATFORM_ADMIN) {
    emit MaximumRepriceV3ReservesExternalPoRDiffPercentageUpdated(
      maximumRepriceV3ReservesExternalPoRDiffPercentage,
      _newMaximumRepriceV3ReservesExternalPoRDiffPercentage
    );

    maximumRepriceV3ReservesExternalPoRDiffPercentage = _newMaximumRepriceV3ReservesExternalPoRDiffPercentage;
  }

  function setMaximumRoundDataStalenessTime(
    uint256 _newMaximumRoundDataStalenessTime
  ) external override checkRole(SwellLib.PLATFORM_ADMIN) {
    emit MaximumRoundDataStalenessTimeUpdated(
      maximumRoundDataStalenessTime,
      _newMaximumRoundDataStalenessTime
    );

    maximumRoundDataStalenessTime = _newMaximumRoundDataStalenessTime;
  }

  function setMaximumReferencePriceDiffPercentage(
    uint256 _newMaximumReferencePriceDiffPercentage
  ) external override checkRole(SwellLib.PLATFORM_ADMIN) {
    emit MaximumReferencePriceDiffPercentageUpdated(
      maximumReferencePriceDiffPercentage,
      _newMaximumReferencePriceDiffPercentage
    );

    maximumReferencePriceDiffPercentage = _newMaximumReferencePriceDiffPercentage;
  }

  // ************************************
  // ***** Internal helpers *****

  function handleReprice(
    UpgradeableRepriceSnapshot calldata _snapshot
  ) internal {
    // gather state
    uint256 reserveAssets = _snapshot.state.balances.reserveAssets();

    // events
    emit SnapshotSubmittedV2(
      _snapshot.meta.blockNumber,
      _snapshot.meta.slot,
      _snapshot.meta.timestamp,
      _snapshot.state.totalETHDeposited,
      _snapshot.state.rswETHTotalSupply,
      _snapshot.withdrawState.totalETHExited
    );

    emit ReservesRecordedV2(
      _snapshot.meta.blockNumber,
      _snapshot.state.balances.executionLayer,
      _snapshot.state.balances.consensusLayerV3Validators,
      _snapshot.state.balances.consensusLayerV2Validators,
      _snapshot.state.balances.transitioning,
      reserveAssets - _snapshot.withdrawState.exitingETH,
      reserveAssets,
      _snapshot.withdrawState.exitingETH
    );

    if (_snapshot.meta.blockOfLastSnapshot != 0) {
      // acquire extra info to add context to rewards event
      (
        int256 reserveAssetsChange,
        uint256 ethDepositsChange,
        uint256 ethExitedChange
      ) = _repricingPeriodDeltas(
          reserveAssets,
          _snapshot.state,
          _snapshot.withdrawState
        );

      emit RewardsCalculatedV2(
        _snapshot.meta.blockNumber,
        _snapshot.meta.blockOfLastSnapshot,
        reserveAssetsChange,
        ethDepositsChange,
        _snapshot.rewardsPayableForFees,
        ethExitedChange
      );
    }

    // reprice call
    uint256 newETHRewards = _snapshot.rewardsPayableForFees;
    uint256 rswETHTotalSupply = _snapshot.state.rswETHTotalSupply;
    uint256 preRewardETHReserves = reserveAssets -
      _snapshot.withdrawState.exitingETH -
      newETHRewards;

    AccessControlManager.rswETH().reprice(
      preRewardETHReserves,
      newETHRewards,
      rswETHTotalSupply
    );

    UpgradeableRepriceSnapshot
      storage upgradeableRepriceSnapshot = getSnapshotStruct();

    // Values must be set individually because of the way the UpgradeableRepriceSnapshot struct is stored in storage
    upgradeableRepriceSnapshot.meta = _snapshot.meta;
    upgradeableRepriceSnapshot.state = _snapshot.state;
    upgradeableRepriceSnapshot.rewardsPayableForFees = _snapshot
      .rewardsPayableForFees;
    upgradeableRepriceSnapshot.withdrawState = _snapshot.withdrawState;
  }

  function _repricingPeriodDeltas(
    uint256 _reserveAssets,
    RepriceSnapshotState memory _snapshotState,
    WithdrawSnapshotState memory _withdrawState
  )
    internal
    view
    returns (
      int256 reserveAssetsChange,
      uint256 ethDepositsChange,
      uint256 ethExitedChange
    )
  {
    UpgradeableRepriceSnapshot
      storage upgradeableRepriceSnapshot = getSnapshotStruct();

    bool useOldSnapshot = upgradeableRepriceSnapshot.meta.blockNumber == 0;

    uint256 reserveAssets = useOldSnapshot
      ? _lastRepriceSnapshot.state.balances.reserveAssets()
      : upgradeableRepriceSnapshot.state.balances.reserveAssets();
    reserveAssetsChange = int256(_reserveAssets) - int256(reserveAssets);

    uint256 totalETHDeposited = useOldSnapshot
      ? _lastRepriceSnapshot.state.totalETHDeposited
      : upgradeableRepriceSnapshot.state.totalETHDeposited;
    ethDepositsChange = _snapshotState.totalETHDeposited - totalETHDeposited;

    uint256 totalETHExited = useOldSnapshot
      ? 0
      : upgradeableRepriceSnapshot.withdrawState.totalETHExited;
    ethExitedChange = _withdrawState.totalETHExited - totalETHExited;
  }

  /**
   * @dev Asserts the validity of a repricing snapshot
   * @param _snapshot The snapshot to assert the validity of
   * @param _externalV3ReservesResult A struct holding information about the external V3 proof of reserves contract: whether the on-chain data source exists, and the latest value if it does
   */
  function _assertRepricingSnapshotValidity(
    UpgradeableRepriceSnapshot memory _snapshot,
    ExternalV3ReservesResult memory _externalV3ReservesResult
  ) internal view {
    UpgradeableRepriceSnapshot
      storage upgradeableRepriceSnapshot = getSnapshotStruct();

    uint256 upgradeableSnapshotBlockNumber = upgradeableRepriceSnapshot
      .meta
      .blockNumber;

    bool useOldSnapshot = upgradeableSnapshotBlockNumber == 0;

    uint256 lastRepriceBlockNumber = useOldSnapshot
      ? _lastRepriceSnapshot.meta.blockNumber
      : upgradeableSnapshotBlockNumber;

    if (_snapshot.meta.blockOfLastSnapshot != lastRepriceBlockNumber) {
      revert RepriceBlockOfLastSnapshotMismatch(
        _snapshot.meta.blockOfLastSnapshot,
        lastRepriceBlockNumber
      );
    }

    if (_snapshot.meta.blockOfLastSnapshot >= _snapshot.meta.blockNumber) {
      revert RepriceBlockAtSnapshotDidNotIncrease();
    }

    uint256 lastRepriceSlot = useOldSnapshot
      ? _lastRepriceSnapshot.meta.slot
      : upgradeableRepriceSnapshot.meta.slot;

    if (_snapshot.meta.slot <= lastRepriceSlot) {
      revert RepriceSlotDidNotIncrease();
    }

    uint256 lastRepriceTimestamp = useOldSnapshot
      ? _lastRepriceSnapshot.meta.timestamp
      : upgradeableRepriceSnapshot.meta.timestamp;

    if (_snapshot.meta.timestamp <= lastRepriceTimestamp) {
      revert RepriceTimestampDidNotIncrease();
    }

    if (_snapshot.meta.timestamp >= block.timestamp) {
      revert RepriceTimestampTooHigh(_snapshot.meta.timestamp, block.timestamp);
    }

    if (_snapshot.meta.blockNumber >= block.number) {
      revert RepriceBlockAtSnapshotTooHigh(
        _snapshot.meta.blockNumber,
        block.number
      );
    }

    uint256 snapshotStalenessInBlocks = block.number -
      _snapshot.meta.blockNumber;

    uint256 cachedMaximumRepriceBlockAtSnapshotStaleness = maximumRepriceBlockAtSnapshotStaleness;

    if (
      snapshotStalenessInBlocks > cachedMaximumRepriceBlockAtSnapshotStaleness
    ) {
      revert RepriceBlockAtSnapshotIsStale(
        snapshotStalenessInBlocks,
        cachedMaximumRepriceBlockAtSnapshotStaleness
      );
    }

    IrswEXIT rswEXIT = AccessControlManager.rswEXIT();

    if (rswEXIT.totalETHExited() != _snapshot.withdrawState.totalETHExited) {
      revert ProcessWithdrawalsTotalETHExitedMismatch();
    }

    // Exiting must rise
    if (rswEXIT.exitingETH() < _snapshot.withdrawState.exitingETH) {
      revert ProcessWithdrawalsExitingETHMustMonotonicallyIncrease();
    }

    // This contract will be deployed on some chains that will not have the AggregatorV3Interface deployed, so we want to skip this check if the address is 0
    if (!_externalV3ReservesResult.exists) {
      return;
    }

    uint256 v3ReservesExternalPoRDiff = _absolute(
      _snapshot.state.balances.consensusLayerV3Validators,
      _externalV3ReservesResult.externallyReportedV3Balance
    );

    uint256 maximumV3ReservesExternalPoRDiff = (_externalV3ReservesResult
      .externallyReportedV3Balance *
      maximumRepriceV3ReservesExternalPoRDiffPercentage) / 1 ether;

    if (v3ReservesExternalPoRDiff > maximumV3ReservesExternalPoRDiff) {
      revert RepriceV3ReservesExternalPoRDifferentialTooHigh(
        v3ReservesExternalPoRDiff,
        maximumV3ReservesExternalPoRDiff
      );
    }
  }

  /**
   * @dev Returns the absolute difference between two uint256 values
   */
  function _absolute(uint256 _a, uint256 _b) internal pure returns (uint256) {
    if (_a < _b) {
      return _b - _a;
    }

    return _a - _b;
  }

  /**
   * @dev Calculates a reference price against which the new swETH rate can be compared. It receives copies of relevant state in the snapshot, overwrites portions of them by fetching onchain values, then simulates repricing to compute the reference rate.
   * @param _state A copy of the state of the snapshot that will be used in repricing. This function will overwrite some values in this struct for the sake of computing the reference price.
   * @param _withdrawState A copy of the withdraw state of the snapshot that will be used in repricing. This function will overwrite some values in this struct for the sake of computing the reference price.
   * @param _externalV3ReservesResult A struct holding information about the external V3 proof of reserves contract: whether the on-chain data source exists, and the latest value if it does
   */
  function _referenceOnChainRate(
    RepriceSnapshotState memory _state,
    WithdrawSnapshotState memory _withdrawState,
    ExternalV3ReservesResult memory _externalV3ReservesResult
  ) internal view returns (uint256) {
    uint256 rewardPercentageTotal;
    {
      IrswETH rswETH = AccessControlManager.rswETH();

      uint256 totalSupply = rswETH.totalSupply();
      if (totalSupply == 0) {
        revert CannotComputeReferencePriceWithZeroRswETHSupply();
      }

      _state.rswETHTotalSupply = totalSupply;
      rewardPercentageTotal =
        rswETH.nodeOperatorRewardPercentage() +
        rswETH.swellTreasuryRewardPercentage();
      _state.totalETHDeposited = rswETH.totalETHDeposited();
    }

    {
      IrswEXIT rswEXIT = AccessControlManager.rswEXIT();
      _withdrawState.totalETHExited = rswEXIT.totalETHExited();
      _withdrawState.exitingETH = rswEXIT.exitingETH();
    }

    if (_externalV3ReservesResult.exists) {
      _state.balances.consensusLayerV3Validators = _externalV3ReservesResult
        .externallyReportedV3Balance;
    }

    uint256 reserveAssets = _state.balances.reserveAssets();

    uint256 rewardsPayableForFees;
    {
      int256 unclampedRewardsPayableForFees;
      {
        (
          int256 reserveAssetsChange,
          uint256 ethDepositsChange,
          uint256 ethExitedChange
        ) = _repricingPeriodDeltas(reserveAssets, _state, _withdrawState);

        unclampedRewardsPayableForFees =
          reserveAssetsChange -
          int256(ethDepositsChange) +
          int256(ethExitedChange);
      }

      if (unclampedRewardsPayableForFees > 0) {
        rewardsPayableForFees = uint256(unclampedRewardsPayableForFees);
      }
    }

    uint256 referenceNewPrice;
    {
      uint256 totalReserves = reserveAssets - _withdrawState.exitingETH;

      UD60x18 rewardsInETH = wrap(rewardsPayableForFees).mul(
        wrap(rewardPercentageTotal)
      );

      UD60x18 rewardsInRswETH = wrap(_state.rswETHTotalSupply)
        .mul(rewardsInETH)
        .div(wrap(totalReserves - rewardsInETH.unwrap()));

      referenceNewPrice = wrap(totalReserves)
        .div(wrap(_state.rswETHTotalSupply + rewardsInRswETH.unwrap()))
        .unwrap();
    }

    return referenceNewPrice;
  }

  /**
   * @dev Checks if the reference price difference is too high. The reference price is a combination of various on-chain sources used to approximate the real rate.
   * @param _newRswETHToETHRate The new swETH to ETH rate used as a basis for comparison
   * @param _referenceRate The reference on-chain rate used as an approximation of the real rate
   * @param _cachedMaximumReferencePriceDiffPercentage The maximum price difference percentage against the reference, cached to save gas
   */
  function _checkReferencePriceDiff(
    uint256 _newRswETHToETHRate,
    uint256 _referenceRate,
    uint256 _cachedMaximumReferencePriceDiffPercentage
  ) internal pure {
    uint256 referencePriceDiff = _absolute(_newRswETHToETHRate, _referenceRate);

    // We compute the maximumReferencePriceDiff twice with different bases (first using _newRswETHToETHRate, second using _referenceRate)
    // This is because these two methods are asymmetrical with respect to price direction.

    // New rate as basis: reverts earlier as new price gets lower
    uint256 maximumReferencePriceDiff = (_newRswETHToETHRate *
      _cachedMaximumReferencePriceDiffPercentage) / 1 ether;

    if (referencePriceDiff > maximumReferencePriceDiff) {
      revert ReferencePriceDiffTooHigh(
        referencePriceDiff,
        _cachedMaximumReferencePriceDiffPercentage
      );
    }

    // Reference rate as basis: reverts earlier as new price gets higher
    maximumReferencePriceDiff =
      (_referenceRate * _cachedMaximumReferencePriceDiffPercentage) /
      1 ether;

    if (referencePriceDiff > maximumReferencePriceDiff) {
      revert ReferencePriceDiffTooHigh(
        referencePriceDiff,
        _cachedMaximumReferencePriceDiffPercentage
      );
    }
  }

  // Holds information about the latest round data from the external V3 reserves PoR oracle
  struct ExternalV3ReservesResult {
    // Whether there is a value for the external V3 reserves that can be used for calculations
    bool exists;
    // The latest round data from the external V3 reserves PoR oracle, if it exists
    uint256 externallyReportedV3Balance;
  }

  /**
   * @dev Returns the latest round data from the external V3 reserves PoR oracle
   * @notice If the address of the external V3 reserves PoR oracle is 0, this function will return a struct with exists set to false
   * @notice If the latest round data from the oracle is stale, this function will revert
   * @return A struct holding information about the latest round data from the external V3 reserves PoR oracle
   */
  function _externalV3ReservesLatestRoundData()
    internal
    view
    returns (ExternalV3ReservesResult memory)
  {
    if (address(ExternalV3ReservesPoROracle) == address(0)) {
      return
        ExternalV3ReservesResult({
          exists: false,
          externallyReportedV3Balance: 0
        });
    }

    (, int256 latestRoundData, , uint256 updatedAt, ) = AggregatorV3Interface(
      ExternalV3ReservesPoROracle
    ).latestRoundData();

    uint256 roundDataExpiryTime = updatedAt + maximumRoundDataStalenessTime;

    if (block.timestamp > roundDataExpiryTime) {
      revert RoundDataIsStale(updatedAt, block.timestamp - roundDataExpiryTime);
    }

    return
      ExternalV3ReservesResult({
        exists: true,
        externallyReportedV3Balance: uint256(latestRoundData)
      });
  }

  // ************************************
  // ***** External view methods *****

  function lastRepriceSnapshot()
    external
    view
    override
    returns (UpgradeableRepriceSnapshot memory)
  {
    UpgradeableRepriceSnapshot
      storage upgradeableRepriceSnapshot = getSnapshotStruct();
    // Handling for when this contract is upgraded and we want to return the last snapshot
    if (upgradeableRepriceSnapshot.meta.blockNumber == 0) {
      return
        UpgradeableRepriceSnapshot({
          meta: _lastRepriceSnapshot.meta,
          state: _lastRepriceSnapshot.state,
          rewardsPayableForFees: _lastRepriceSnapshot.rewardsPayableForFees,
          withdrawState: WithdrawSnapshotState({
            totalETHExited: 0,
            exitingETH: 0
          })
        });
    }

    return upgradeableRepriceSnapshot;
  }

  function assertRepricingSnapshotValidity(
    UpgradeableRepriceSnapshot calldata _snapshot
  ) external view override {
    ExternalV3ReservesResult
      memory externalV3ReservesResult = _externalV3ReservesLatestRoundData();
    _assertRepricingSnapshotValidity(_snapshot, externalV3ReservesResult);
  }
}

File 2 of 62 : IAccessControlEnumerableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)

pragma solidity ^0.8.0;

import "./IAccessControlUpgradeable.sol";

/**
 * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
 */
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) external view returns (address);

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) external view returns (uint256);
}

File 3 of 62 : IAccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControlUpgradeable {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

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

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

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

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

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

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

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

File 4 of 62 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "../../utils/AddressUpgradeable.sol";

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

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

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

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized < type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

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

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

File 5 of 62 : IERC20Upgradeable.sol
// 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 IERC20Upgradeable {
    /**
     * @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);
}

File 6 of 62 : IERC721Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165Upgradeable.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721Upgradeable is IERC165Upgradeable {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

File 7 of 62 : AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

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

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

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

File 8 of 62 : IERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

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

File 9 of 62 : IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.0;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {BeaconProxy} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

File 10 of 62 : draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

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

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

File 11 of 62 : IERC20.sol
// 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);
}

File 12 of 62 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/draft-IERC20Permit.sol";
import "../../../utils/Address.sol";

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

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

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

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

File 13 of 62 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

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

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

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

File 14 of 62 : Common.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

/// Common mathematical functions used in both SD59x18 and UD60x18. Note that these global functions do not
/// always operate with SD59x18 and UD60x18 numbers.

/*//////////////////////////////////////////////////////////////////////////
                                CUSTOM ERRORS
//////////////////////////////////////////////////////////////////////////*/

/// @notice Emitted when the ending result in the fixed-point version of `mulDiv` would overflow uint256.
error PRBMath_MulDiv18_Overflow(uint256 x, uint256 y);

/// @notice Emitted when the ending result in `mulDiv` would overflow uint256.
error PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator);

/// @notice Emitted when attempting to run `mulDiv` with one of the inputs `type(int256).min`.
error PRBMath_MulDivSigned_InputTooSmall();

/// @notice Emitted when the ending result in the signed version of `mulDiv` would overflow int256.
error PRBMath_MulDivSigned_Overflow(int256 x, int256 y);

/*//////////////////////////////////////////////////////////////////////////
                                    CONSTANTS
//////////////////////////////////////////////////////////////////////////*/

/// @dev The maximum value an uint128 number can have.
uint128 constant MAX_UINT128 = type(uint128).max;

/// @dev The maximum value an uint40 number can have.
uint40 constant MAX_UINT40 = type(uint40).max;

/// @dev How many trailing decimals can be represented.
uint256 constant UNIT = 1e18;

/// @dev Largest power of two that is a divisor of `UNIT`.
uint256 constant UNIT_LPOTD = 262144;

/// @dev The `UNIT` number inverted mod 2^256.
uint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281;

/*//////////////////////////////////////////////////////////////////////////
                                    FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

/// @notice Finds the zero-based index of the first one in the binary representation of x.
/// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set
///
/// Each of the steps in this implementation is equivalent to this high-level code:
///
/// ```solidity
/// if (x >= 2 ** 128) {
///     x >>= 128;
///     result += 128;
/// }
/// ```
///
/// Where 128 is swapped with each respective power of two factor. See the full high-level implementation here:
/// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948
///
/// A list of the Yul instructions used below:
/// - "gt" is "greater than"
/// - "or" is the OR bitwise operator
/// - "shl" is "shift left"
/// - "shr" is "shift right"
///
/// @param x The uint256 number for which to find the index of the most significant bit.
/// @return result The index of the most significant bit as an uint256.
function msb(uint256 x) pure returns (uint256 result) {
    // 2^128
    assembly ("memory-safe") {
        let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^64
    assembly ("memory-safe") {
        let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^32
    assembly ("memory-safe") {
        let factor := shl(5, gt(x, 0xFFFFFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^16
    assembly ("memory-safe") {
        let factor := shl(4, gt(x, 0xFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^8
    assembly ("memory-safe") {
        let factor := shl(3, gt(x, 0xFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^4
    assembly ("memory-safe") {
        let factor := shl(2, gt(x, 0xF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^2
    assembly ("memory-safe") {
        let factor := shl(1, gt(x, 0x3))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^1
    // No need to shift x any more.
    assembly ("memory-safe") {
        let factor := gt(x, 0x1)
        result := or(result, factor)
    }
}

/// @notice Calculates floor(x*y÷denominator) with full precision.
///
/// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
///
/// Requirements:
/// - The denominator cannot be zero.
/// - The result must fit within uint256.
///
/// Caveats:
/// - This function does not work with fixed-point numbers.
///
/// @param x The multiplicand as an uint256.
/// @param y The multiplier as an uint256.
/// @param denominator The divisor as an uint256.
/// @return result The result as an uint256.
function mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 result) {
    // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
    // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
    // variables such that product = prod1 * 2^256 + prod0.
    uint256 prod0; // Least significant 256 bits of the product
    uint256 prod1; // Most significant 256 bits of the product
    assembly ("memory-safe") {
        let mm := mulmod(x, y, not(0))
        prod0 := mul(x, y)
        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
    }

    // Handle non-overflow cases, 256 by 256 division.
    if (prod1 == 0) {
        unchecked {
            return prod0 / denominator;
        }
    }

    // Make sure the result is less than 2^256. Also prevents denominator == 0.
    if (prod1 >= denominator) {
        revert PRBMath_MulDiv_Overflow(x, y, denominator);
    }

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

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

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

    // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
    // See https://cs.stackexchange.com/q/138556/92363.
    unchecked {
        // Does not overflow because the denominator cannot be zero at this stage in the function.
        uint256 lpotdod = denominator & (~denominator + 1);
        assembly ("memory-safe") {
            // Divide denominator by lpotdod.
            denominator := div(denominator, lpotdod)

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

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

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

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

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

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

/// @notice Calculates floor(x*y÷1e18) with full precision.
///
/// @dev Variant of `mulDiv` with constant folding, i.e. in which the denominator is always 1e18. Before returning the
/// final result, we add 1 if `(x * y) % UNIT >= HALF_UNIT`. Without this adjustment, 6.6e-19 would be truncated to 0
/// instead of being rounded to 1e-18. See "Listing 6" and text above it at https://accu.org/index.php/journals/1717.
///
/// Requirements:
/// - The result must fit within uint256.
///
/// Caveats:
/// - The body is purposely left uncommented; to understand how this works, see the NatSpec comments in `mulDiv`.
/// - It is assumed that the result can never be `type(uint256).max` when x and y solve the following two equations:
///     1. x * y = type(uint256).max * UNIT
///     2. (x * y) % UNIT >= UNIT / 2
///
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) {
    uint256 prod0;
    uint256 prod1;
    assembly ("memory-safe") {
        let mm := mulmod(x, y, not(0))
        prod0 := mul(x, y)
        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
    }

    if (prod1 >= UNIT) {
        revert PRBMath_MulDiv18_Overflow(x, y);
    }

    uint256 remainder;
    assembly ("memory-safe") {
        remainder := mulmod(x, y, UNIT)
    }

    if (prod1 == 0) {
        unchecked {
            return prod0 / UNIT;
        }
    }

    assembly ("memory-safe") {
        result := mul(
            or(
                div(sub(prod0, remainder), UNIT_LPOTD),
                mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1))
            ),
            UNIT_INVERSE
        )
    }
}

/// @notice Calculates floor(x*y÷denominator) with full precision.
///
/// @dev An extension of `mulDiv` for signed numbers. Works by computing the signs and the absolute values separately.
///
/// Requirements:
/// - None of the inputs can be `type(int256).min`.
/// - The result must fit within int256.
///
/// @param x The multiplicand as an int256.
/// @param y The multiplier as an int256.
/// @param denominator The divisor as an int256.
/// @return result The result as an int256.
function mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) {
    if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
        revert PRBMath_MulDivSigned_InputTooSmall();
    }

    // Get hold of the absolute values of x, y and the denominator.
    uint256 absX;
    uint256 absY;
    uint256 absD;
    unchecked {
        absX = x < 0 ? uint256(-x) : uint256(x);
        absY = y < 0 ? uint256(-y) : uint256(y);
        absD = denominator < 0 ? uint256(-denominator) : uint256(denominator);
    }

    // Compute the absolute value of (x*y)÷denominator. The result must fit within int256.
    uint256 rAbs = mulDiv(absX, absY, absD);
    if (rAbs > uint256(type(int256).max)) {
        revert PRBMath_MulDivSigned_Overflow(x, y);
    }

    // Get the signs of x, y and the denominator.
    uint256 sx;
    uint256 sy;
    uint256 sd;
    assembly ("memory-safe") {
        // This works thanks to two's complement.
        // "sgt" stands for "signed greater than" and "sub(0,1)" is max uint256.
        sx := sgt(x, sub(0, 1))
        sy := sgt(y, sub(0, 1))
        sd := sgt(denominator, sub(0, 1))
    }

    // XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs.
    // If there are, the result should be negative. Otherwise, it should be positive.
    unchecked {
        result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs);
    }
}

/// @notice Calculates the binary exponent of x using the binary fraction method.
/// @dev Has to use 192.64-bit fixed-point numbers.
/// See https://ethereum.stackexchange.com/a/96594/24693.
/// @param x The exponent as an unsigned 192.64-bit fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function prbExp2(uint256 x) pure returns (uint256 result) {
    unchecked {
        // Start from 0.5 in the 192.64-bit fixed-point format.
        result = 0x800000000000000000000000000000000000000000000000;

        // Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows
        // because the initial result is 2^191 and all magic factors are less than 2^65.
        if (x & 0xFF00000000000000 > 0) {
            if (x & 0x8000000000000000 > 0) {
                result = (result * 0x16A09E667F3BCC909) >> 64;
            }
            if (x & 0x4000000000000000 > 0) {
                result = (result * 0x1306FE0A31B7152DF) >> 64;
            }
            if (x & 0x2000000000000000 > 0) {
                result = (result * 0x1172B83C7D517ADCE) >> 64;
            }
            if (x & 0x1000000000000000 > 0) {
                result = (result * 0x10B5586CF9890F62A) >> 64;
            }
            if (x & 0x800000000000000 > 0) {
                result = (result * 0x1059B0D31585743AE) >> 64;
            }
            if (x & 0x400000000000000 > 0) {
                result = (result * 0x102C9A3E778060EE7) >> 64;
            }
            if (x & 0x200000000000000 > 0) {
                result = (result * 0x10163DA9FB33356D8) >> 64;
            }
            if (x & 0x100000000000000 > 0) {
                result = (result * 0x100B1AFA5ABCBED61) >> 64;
            }
        }

        if (x & 0xFF000000000000 > 0) {
            if (x & 0x80000000000000 > 0) {
                result = (result * 0x10058C86DA1C09EA2) >> 64;
            }
            if (x & 0x40000000000000 > 0) {
                result = (result * 0x1002C605E2E8CEC50) >> 64;
            }
            if (x & 0x20000000000000 > 0) {
                result = (result * 0x100162F3904051FA1) >> 64;
            }
            if (x & 0x10000000000000 > 0) {
                result = (result * 0x1000B175EFFDC76BA) >> 64;
            }
            if (x & 0x8000000000000 > 0) {
                result = (result * 0x100058BA01FB9F96D) >> 64;
            }
            if (x & 0x4000000000000 > 0) {
                result = (result * 0x10002C5CC37DA9492) >> 64;
            }
            if (x & 0x2000000000000 > 0) {
                result = (result * 0x1000162E525EE0547) >> 64;
            }
            if (x & 0x1000000000000 > 0) {
                result = (result * 0x10000B17255775C04) >> 64;
            }
        }

        if (x & 0xFF0000000000 > 0) {
            if (x & 0x800000000000 > 0) {
                result = (result * 0x1000058B91B5BC9AE) >> 64;
            }
            if (x & 0x400000000000 > 0) {
                result = (result * 0x100002C5C89D5EC6D) >> 64;
            }
            if (x & 0x200000000000 > 0) {
                result = (result * 0x10000162E43F4F831) >> 64;
            }
            if (x & 0x100000000000 > 0) {
                result = (result * 0x100000B1721BCFC9A) >> 64;
            }
            if (x & 0x80000000000 > 0) {
                result = (result * 0x10000058B90CF1E6E) >> 64;
            }
            if (x & 0x40000000000 > 0) {
                result = (result * 0x1000002C5C863B73F) >> 64;
            }
            if (x & 0x20000000000 > 0) {
                result = (result * 0x100000162E430E5A2) >> 64;
            }
            if (x & 0x10000000000 > 0) {
                result = (result * 0x1000000B172183551) >> 64;
            }
        }

        if (x & 0xFF00000000 > 0) {
            if (x & 0x8000000000 > 0) {
                result = (result * 0x100000058B90C0B49) >> 64;
            }
            if (x & 0x4000000000 > 0) {
                result = (result * 0x10000002C5C8601CC) >> 64;
            }
            if (x & 0x2000000000 > 0) {
                result = (result * 0x1000000162E42FFF0) >> 64;
            }
            if (x & 0x1000000000 > 0) {
                result = (result * 0x10000000B17217FBB) >> 64;
            }
            if (x & 0x800000000 > 0) {
                result = (result * 0x1000000058B90BFCE) >> 64;
            }
            if (x & 0x400000000 > 0) {
                result = (result * 0x100000002C5C85FE3) >> 64;
            }
            if (x & 0x200000000 > 0) {
                result = (result * 0x10000000162E42FF1) >> 64;
            }
            if (x & 0x100000000 > 0) {
                result = (result * 0x100000000B17217F8) >> 64;
            }
        }

        if (x & 0xFF00000000 > 0) {
            if (x & 0x80000000 > 0) {
                result = (result * 0x10000000058B90BFC) >> 64;
            }
            if (x & 0x40000000 > 0) {
                result = (result * 0x1000000002C5C85FE) >> 64;
            }
            if (x & 0x20000000 > 0) {
                result = (result * 0x100000000162E42FF) >> 64;
            }
            if (x & 0x10000000 > 0) {
                result = (result * 0x1000000000B17217F) >> 64;
            }
            if (x & 0x8000000 > 0) {
                result = (result * 0x100000000058B90C0) >> 64;
            }
            if (x & 0x4000000 > 0) {
                result = (result * 0x10000000002C5C860) >> 64;
            }
            if (x & 0x2000000 > 0) {
                result = (result * 0x1000000000162E430) >> 64;
            }
            if (x & 0x1000000 > 0) {
                result = (result * 0x10000000000B17218) >> 64;
            }
        }

        if (x & 0xFF0000 > 0) {
            if (x & 0x800000 > 0) {
                result = (result * 0x1000000000058B90C) >> 64;
            }
            if (x & 0x400000 > 0) {
                result = (result * 0x100000000002C5C86) >> 64;
            }
            if (x & 0x200000 > 0) {
                result = (result * 0x10000000000162E43) >> 64;
            }
            if (x & 0x100000 > 0) {
                result = (result * 0x100000000000B1721) >> 64;
            }
            if (x & 0x80000 > 0) {
                result = (result * 0x10000000000058B91) >> 64;
            }
            if (x & 0x40000 > 0) {
                result = (result * 0x1000000000002C5C8) >> 64;
            }
            if (x & 0x20000 > 0) {
                result = (result * 0x100000000000162E4) >> 64;
            }
            if (x & 0x10000 > 0) {
                result = (result * 0x1000000000000B172) >> 64;
            }
        }

        if (x & 0xFF00 > 0) {
            if (x & 0x8000 > 0) {
                result = (result * 0x100000000000058B9) >> 64;
            }
            if (x & 0x4000 > 0) {
                result = (result * 0x10000000000002C5D) >> 64;
            }
            if (x & 0x2000 > 0) {
                result = (result * 0x1000000000000162E) >> 64;
            }
            if (x & 0x1000 > 0) {
                result = (result * 0x10000000000000B17) >> 64;
            }
            if (x & 0x800 > 0) {
                result = (result * 0x1000000000000058C) >> 64;
            }
            if (x & 0x400 > 0) {
                result = (result * 0x100000000000002C6) >> 64;
            }
            if (x & 0x200 > 0) {
                result = (result * 0x10000000000000163) >> 64;
            }
            if (x & 0x100 > 0) {
                result = (result * 0x100000000000000B1) >> 64;
            }
        }

        if (x & 0xFF > 0) {
            if (x & 0x80 > 0) {
                result = (result * 0x10000000000000059) >> 64;
            }
            if (x & 0x40 > 0) {
                result = (result * 0x1000000000000002C) >> 64;
            }
            if (x & 0x20 > 0) {
                result = (result * 0x10000000000000016) >> 64;
            }
            if (x & 0x10 > 0) {
                result = (result * 0x1000000000000000B) >> 64;
            }
            if (x & 0x8 > 0) {
                result = (result * 0x10000000000000006) >> 64;
            }
            if (x & 0x4 > 0) {
                result = (result * 0x10000000000000003) >> 64;
            }
            if (x & 0x2 > 0) {
                result = (result * 0x10000000000000001) >> 64;
            }
            if (x & 0x1 > 0) {
                result = (result * 0x10000000000000001) >> 64;
            }
        }

        // We're doing two things at the same time:
        //
        //   1. Multiply the result by 2^n + 1, where "2^n" is the integer part and the one is added to account for
        //      the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191
        //      rather than 192.
        //   2. Convert the result to the unsigned 60.18-decimal fixed-point format.
        //
        // This works because 2^(191-ip) = 2^ip / 2^191, where "ip" is the integer part "2^n".
        result *= UNIT;
        result >>= (191 - (x >> 64));
    }
}

/// @notice Calculates the square root of x, rounding down if x is not a perfect square.
/// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
/// Credits to OpenZeppelin for the explanations in code comments below.
///
/// Caveats:
/// - This function does not work with fixed-point numbers.
///
/// @param x The uint256 number for which to calculate the square root.
/// @return result The result as an uint256.
function prbSqrt(uint256 x) pure returns (uint256 result) {
    if (x == 0) {
        return 0;
    }

    // For our first guess, we get the biggest power of 2 which is smaller than the square root of x.
    //
    // We know that the "msb" (most significant bit) of x is a power of 2 such that we have:
    //
    // $$
    // msb(x) <= x <= 2*msb(x)$
    // $$
    //
    // We write $msb(x)$ as $2^k$ and we get:
    //
    // $$
    // k = log_2(x)
    // $$
    //
    // Thus we can write the initial inequality as:
    //
    // $$
    // 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\
    // sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\
    // 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1}
    // $$
    //
    // Consequently, $2^{log_2(x) /2}` is a good first approximation of sqrt(x) with at least one correct bit.
    uint256 xAux = uint256(x);
    result = 1;
    if (xAux >= 2 ** 128) {
        xAux >>= 128;
        result <<= 64;
    }
    if (xAux >= 2 ** 64) {
        xAux >>= 64;
        result <<= 32;
    }
    if (xAux >= 2 ** 32) {
        xAux >>= 32;
        result <<= 16;
    }
    if (xAux >= 2 ** 16) {
        xAux >>= 16;
        result <<= 8;
    }
    if (xAux >= 2 ** 8) {
        xAux >>= 8;
        result <<= 4;
    }
    if (xAux >= 2 ** 4) {
        xAux >>= 4;
        result <<= 2;
    }
    if (xAux >= 2 ** 2) {
        result <<= 1;
    }

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

        // Round down the result in case x is not a perfect square.
        uint256 roundedDownResult = x / result;
        if (result >= roundedDownResult) {
            result = roundedDownResult;
        }
    }
}

File 15 of 62 : Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { MAX_UINT40 } from "../Common.sol";
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import {
    PRBMath_SD1x18_ToUD2x18_Underflow,
    PRBMath_SD1x18_ToUD60x18_Underflow,
    PRBMath_SD1x18_ToUint128_Underflow,
    PRBMath_SD1x18_ToUint256_Underflow,
    PRBMath_SD1x18_ToUint40_Overflow,
    PRBMath_SD1x18_ToUint40_Underflow
} from "./Errors.sol";
import { SD1x18 } from "./ValueType.sol";

/// @notice Casts an SD1x18 number into SD59x18.
/// @dev There is no overflow check because the domain of SD1x18 is a subset of SD59x18.
function intoSD59x18(SD1x18 x) pure returns (SD59x18 result) {
    result = SD59x18.wrap(int256(SD1x18.unwrap(x)));
}

/// @notice Casts an SD1x18 number into UD2x18.
/// - x must be positive.
function intoUD2x18(SD1x18 x) pure returns (UD2x18 result) {
    int64 xInt = SD1x18.unwrap(x);
    if (xInt < 0) {
        revert PRBMath_SD1x18_ToUD2x18_Underflow(x);
    }
    result = UD2x18.wrap(uint64(xInt));
}

/// @notice Casts an SD1x18 number into UD60x18.
/// @dev Requirements:
/// - x must be positive.
function intoUD60x18(SD1x18 x) pure returns (UD60x18 result) {
    int64 xInt = SD1x18.unwrap(x);
    if (xInt < 0) {
        revert PRBMath_SD1x18_ToUD60x18_Underflow(x);
    }
    result = UD60x18.wrap(uint64(xInt));
}

/// @notice Casts an SD1x18 number into uint256.
/// @dev Requirements:
/// - x must be positive.
function intoUint256(SD1x18 x) pure returns (uint256 result) {
    int64 xInt = SD1x18.unwrap(x);
    if (xInt < 0) {
        revert PRBMath_SD1x18_ToUint256_Underflow(x);
    }
    result = uint256(uint64(xInt));
}

/// @notice Casts an SD1x18 number into uint128.
/// @dev Requirements:
/// - x must be positive.
function intoUint128(SD1x18 x) pure returns (uint128 result) {
    int64 xInt = SD1x18.unwrap(x);
    if (xInt < 0) {
        revert PRBMath_SD1x18_ToUint128_Underflow(x);
    }
    result = uint128(uint64(xInt));
}

/// @notice Casts an SD1x18 number into uint40.
/// @dev Requirements:
/// - x must be positive.
/// - x must be less than or equal to `MAX_UINT40`.
function intoUint40(SD1x18 x) pure returns (uint40 result) {
    int64 xInt = SD1x18.unwrap(x);
    if (xInt < 0) {
        revert PRBMath_SD1x18_ToUint40_Underflow(x);
    }
    if (xInt > int64(uint64(MAX_UINT40))) {
        revert PRBMath_SD1x18_ToUint40_Overflow(x);
    }
    result = uint40(uint64(xInt));
}

/// @notice Alias for the `wrap` function.
function sd1x18(int64 x) pure returns (SD1x18 result) {
    result = wrap(x);
}

/// @notice Unwraps an SD1x18 number into int64.
function unwrap(SD1x18 x) pure returns (int64 result) {
    result = SD1x18.unwrap(x);
}

/// @notice Wraps an int64 number into the SD1x18 value type.
function wrap(int64 x) pure returns (SD1x18 result) {
    result = SD1x18.wrap(x);
}

File 16 of 62 : Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { SD1x18 } from "./ValueType.sol";

/// @dev Euler's number as an SD1x18 number.
SD1x18 constant E = SD1x18.wrap(2_718281828459045235);

/// @dev The maximum value an SD1x18 number can have.
int64 constant uMAX_SD1x18 = 9_223372036854775807;
SD1x18 constant MAX_SD1x18 = SD1x18.wrap(uMAX_SD1x18);

/// @dev The maximum value an SD1x18 number can have.
int64 constant uMIN_SD1x18 = -9_223372036854775808;
SD1x18 constant MIN_SD1x18 = SD1x18.wrap(uMIN_SD1x18);

/// @dev PI as an SD1x18 number.
SD1x18 constant PI = SD1x18.wrap(3_141592653589793238);

/// @dev The unit amount that implies how many trailing decimals can be represented.
SD1x18 constant UNIT = SD1x18.wrap(1e18);
int256 constant uUNIT = 1e18;

File 17 of 62 : Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { SD1x18 } from "./ValueType.sol";

/// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in UD2x18.
error PRBMath_SD1x18_ToUD2x18_Underflow(SD1x18 x);

/// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in UD60x18.
error PRBMath_SD1x18_ToUD60x18_Underflow(SD1x18 x);

/// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in uint128.
error PRBMath_SD1x18_ToUint128_Underflow(SD1x18 x);

/// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in uint256.
error PRBMath_SD1x18_ToUint256_Underflow(SD1x18 x);

/// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in uint40.
error PRBMath_SD1x18_ToUint40_Overflow(SD1x18 x);

/// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in uint40.
error PRBMath_SD1x18_ToUint40_Underflow(SD1x18 x);

File 18 of 62 : ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import "./Casting.sol" as C;

/// @notice The signed 1.18-decimal fixed-point number representation, which can have up to 1 digit and up to 18 decimals.
/// The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity type int64.
/// This is useful when end users want to use int64 to save gas, e.g. with tight variable packing in contract storage.
type SD1x18 is int64;

/*//////////////////////////////////////////////////////////////////////////
                                    CASTING
//////////////////////////////////////////////////////////////////////////*/

using { C.intoSD59x18, C.intoUD2x18, C.intoUD60x18, C.intoUint256, C.intoUint128, C.intoUint40, C.unwrap } for SD1x18 global;

File 19 of 62 : Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18, uMIN_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import {
    PRBMath_SD59x18_IntoSD1x18_Overflow,
    PRBMath_SD59x18_IntoSD1x18_Underflow,
    PRBMath_SD59x18_IntoUD2x18_Overflow,
    PRBMath_SD59x18_IntoUD2x18_Underflow,
    PRBMath_SD59x18_IntoUD60x18_Underflow,
    PRBMath_SD59x18_IntoUint128_Overflow,
    PRBMath_SD59x18_IntoUint128_Underflow,
    PRBMath_SD59x18_IntoUint256_Underflow,
    PRBMath_SD59x18_IntoUint40_Overflow,
    PRBMath_SD59x18_IntoUint40_Underflow
} from "./Errors.sol";
import { SD59x18 } from "./ValueType.sol";

/// @notice Casts an SD59x18 number into int256.
/// @dev This is basically a functional alias for the `unwrap` function.
function intoInt256(SD59x18 x) pure returns (int256 result) {
    result = SD59x18.unwrap(x);
}

/// @notice Casts an SD59x18 number into SD1x18.
/// @dev Requirements:
/// - x must be greater than or equal to `uMIN_SD1x18`.
/// - x must be less than or equal to `uMAX_SD1x18`.
function intoSD1x18(SD59x18 x) pure returns (SD1x18 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < uMIN_SD1x18) {
        revert PRBMath_SD59x18_IntoSD1x18_Underflow(x);
    }
    if (xInt > uMAX_SD1x18) {
        revert PRBMath_SD59x18_IntoSD1x18_Overflow(x);
    }
    result = SD1x18.wrap(int64(xInt));
}

/// @notice Casts an SD59x18 number into UD2x18.
/// @dev Requirements:
/// - x must be positive.
/// - x must be less than or equal to `uMAX_UD2x18`.
function intoUD2x18(SD59x18 x) pure returns (UD2x18 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < 0) {
        revert PRBMath_SD59x18_IntoUD2x18_Underflow(x);
    }
    if (xInt > int256(uint256(uMAX_UD2x18))) {
        revert PRBMath_SD59x18_IntoUD2x18_Overflow(x);
    }
    result = UD2x18.wrap(uint64(uint256(xInt)));
}

/// @notice Casts an SD59x18 number into UD60x18.
/// @dev Requirements:
/// - x must be positive.
function intoUD60x18(SD59x18 x) pure returns (UD60x18 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < 0) {
        revert PRBMath_SD59x18_IntoUD60x18_Underflow(x);
    }
    result = UD60x18.wrap(uint256(xInt));
}

/// @notice Casts an SD59x18 number into uint256.
/// @dev Requirements:
/// - x must be positive.
function intoUint256(SD59x18 x) pure returns (uint256 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < 0) {
        revert PRBMath_SD59x18_IntoUint256_Underflow(x);
    }
    result = uint256(xInt);
}

/// @notice Casts an SD59x18 number into uint128.
/// @dev Requirements:
/// - x must be positive.
/// - x must be less than or equal to `uMAX_UINT128`.
function intoUint128(SD59x18 x) pure returns (uint128 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < 0) {
        revert PRBMath_SD59x18_IntoUint128_Underflow(x);
    }
    if (xInt > int256(uint256(MAX_UINT128))) {
        revert PRBMath_SD59x18_IntoUint128_Overflow(x);
    }
    result = uint128(uint256(xInt));
}

/// @notice Casts an SD59x18 number into uint40.
/// @dev Requirements:
/// - x must be positive.
/// - x must be less than or equal to `MAX_UINT40`.
function intoUint40(SD59x18 x) pure returns (uint40 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < 0) {
        revert PRBMath_SD59x18_IntoUint40_Underflow(x);
    }
    if (xInt > int256(uint256(MAX_UINT40))) {
        revert PRBMath_SD59x18_IntoUint40_Overflow(x);
    }
    result = uint40(uint256(xInt));
}

/// @notice Alias for the `wrap` function.
function sd(int256 x) pure returns (SD59x18 result) {
    result = wrap(x);
}

/// @notice Alias for the `wrap` function.
function sd59x18(int256 x) pure returns (SD59x18 result) {
    result = wrap(x);
}

/// @notice Unwraps an SD59x18 number into int256.
function unwrap(SD59x18 x) pure returns (int256 result) {
    result = SD59x18.unwrap(x);
}

/// @notice Wraps an int256 number into the SD59x18 value type.
function wrap(int256 x) pure returns (SD59x18 result) {
    result = SD59x18.wrap(x);
}

File 20 of 62 : Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { SD59x18 } from "./ValueType.sol";

/// NOTICE: the "u" prefix stands for "unwrapped".

/// @dev Euler's number as an SD59x18 number.
SD59x18 constant E = SD59x18.wrap(2_718281828459045235);

/// @dev Half the UNIT number.
int256 constant uHALF_UNIT = 0.5e18;
SD59x18 constant HALF_UNIT = SD59x18.wrap(uHALF_UNIT);

/// @dev log2(10) as an SD59x18 number.
int256 constant uLOG2_10 = 3_321928094887362347;
SD59x18 constant LOG2_10 = SD59x18.wrap(uLOG2_10);

/// @dev log2(e) as an SD59x18 number.
int256 constant uLOG2_E = 1_442695040888963407;
SD59x18 constant LOG2_E = SD59x18.wrap(uLOG2_E);

/// @dev The maximum value an SD59x18 number can have.
int256 constant uMAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_792003956564819967;
SD59x18 constant MAX_SD59x18 = SD59x18.wrap(uMAX_SD59x18);

/// @dev The maximum whole value an SD59x18 number can have.
int256 constant uMAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_000000000000000000;
SD59x18 constant MAX_WHOLE_SD59x18 = SD59x18.wrap(uMAX_WHOLE_SD59x18);

/// @dev The minimum value an SD59x18 number can have.
int256 constant uMIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_792003956564819968;
SD59x18 constant MIN_SD59x18 = SD59x18.wrap(uMIN_SD59x18);

/// @dev The minimum whole value an SD59x18 number can have.
int256 constant uMIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_000000000000000000;
SD59x18 constant MIN_WHOLE_SD59x18 = SD59x18.wrap(uMIN_WHOLE_SD59x18);

/// @dev PI as an SD59x18 number.
SD59x18 constant PI = SD59x18.wrap(3_141592653589793238);

/// @dev The unit amount that implies how many trailing decimals can be represented.
int256 constant uUNIT = 1e18;
SD59x18 constant UNIT = SD59x18.wrap(1e18);

/// @dev Zero as an SD59x18 number.
SD59x18 constant ZERO = SD59x18.wrap(0);

File 21 of 62 : Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { SD59x18 } from "./ValueType.sol";

/// @notice Emitted when taking the absolute value of `MIN_SD59x18`.
error PRBMath_SD59x18_Abs_MinSD59x18();

/// @notice Emitted when ceiling a number overflows SD59x18.
error PRBMath_SD59x18_Ceil_Overflow(SD59x18 x);

/// @notice Emitted when converting a basic integer to the fixed-point format overflows SD59x18.
error PRBMath_SD59x18_Convert_Overflow(int256 x);

/// @notice Emitted when converting a basic integer to the fixed-point format underflows SD59x18.
error PRBMath_SD59x18_Convert_Underflow(int256 x);

/// @notice Emitted when dividing two numbers and one of them is `MIN_SD59x18`.
error PRBMath_SD59x18_Div_InputTooSmall();

/// @notice Emitted when dividing two numbers and one of the intermediary unsigned results overflows SD59x18.
error PRBMath_SD59x18_Div_Overflow(SD59x18 x, SD59x18 y);

/// @notice Emitted when taking the natural exponent of a base greater than 133.084258667509499441.
error PRBMath_SD59x18_Exp_InputTooBig(SD59x18 x);

/// @notice Emitted when taking the binary exponent of a base greater than 192.
error PRBMath_SD59x18_Exp2_InputTooBig(SD59x18 x);

/// @notice Emitted when flooring a number underflows SD59x18.
error PRBMath_SD59x18_Floor_Underflow(SD59x18 x);

/// @notice Emitted when taking the geometric mean of two numbers and their product is negative.
error PRBMath_SD59x18_Gm_NegativeProduct(SD59x18 x, SD59x18 y);

/// @notice Emitted when taking the geometric mean of two numbers and multiplying them overflows SD59x18.
error PRBMath_SD59x18_Gm_Overflow(SD59x18 x, SD59x18 y);

/// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in SD1x18.
error PRBMath_SD59x18_IntoSD1x18_Overflow(SD59x18 x);

/// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in SD1x18.
error PRBMath_SD59x18_IntoSD1x18_Underflow(SD59x18 x);

/// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in UD2x18.
error PRBMath_SD59x18_IntoUD2x18_Overflow(SD59x18 x);

/// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in UD2x18.
error PRBMath_SD59x18_IntoUD2x18_Underflow(SD59x18 x);

/// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in UD60x18.
error PRBMath_SD59x18_IntoUD60x18_Underflow(SD59x18 x);

/// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint128.
error PRBMath_SD59x18_IntoUint128_Overflow(SD59x18 x);

/// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint128.
error PRBMath_SD59x18_IntoUint128_Underflow(SD59x18 x);

/// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint256.
error PRBMath_SD59x18_IntoUint256_Underflow(SD59x18 x);

/// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint40.
error PRBMath_SD59x18_IntoUint40_Overflow(SD59x18 x);

/// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint40.
error PRBMath_SD59x18_IntoUint40_Underflow(SD59x18 x);

/// @notice Emitted when taking the logarithm of a number less than or equal to zero.
error PRBMath_SD59x18_Log_InputTooSmall(SD59x18 x);

/// @notice Emitted when multiplying two numbers and one of the inputs is `MIN_SD59x18`.
error PRBMath_SD59x18_Mul_InputTooSmall();

/// @notice Emitted when multiplying two numbers and the intermediary absolute result overflows SD59x18.
error PRBMath_SD59x18_Mul_Overflow(SD59x18 x, SD59x18 y);

/// @notice Emitted when raising a number to a power and hte intermediary absolute result overflows SD59x18.
error PRBMath_SD59x18_Powu_Overflow(SD59x18 x, uint256 y);

/// @notice Emitted when taking the square root of a negative number.
error PRBMath_SD59x18_Sqrt_NegativeInput(SD59x18 x);

/// @notice Emitted when the calculating the square root overflows SD59x18.
error PRBMath_SD59x18_Sqrt_Overflow(SD59x18 x);

File 22 of 62 : Helpers.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { unwrap, wrap } from "./Casting.sol";
import { SD59x18 } from "./ValueType.sol";

/// @notice Implements the checked addition operation (+) in the SD59x18 type.
function add(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    return wrap(unwrap(x) + unwrap(y));
}

/// @notice Implements the AND (&) bitwise operation in the SD59x18 type.
function and(SD59x18 x, int256 bits) pure returns (SD59x18 result) {
    return wrap(unwrap(x) & bits);
}

/// @notice Implements the equal (=) operation in the SD59x18 type.
function eq(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = unwrap(x) == unwrap(y);
}

/// @notice Implements the greater than operation (>) in the SD59x18 type.
function gt(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = unwrap(x) > unwrap(y);
}

/// @notice Implements the greater than or equal to operation (>=) in the SD59x18 type.
function gte(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = unwrap(x) >= unwrap(y);
}

/// @notice Implements a zero comparison check function in the SD59x18 type.
function isZero(SD59x18 x) pure returns (bool result) {
    result = unwrap(x) == 0;
}

/// @notice Implements the left shift operation (<<) in the SD59x18 type.
function lshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
    result = wrap(unwrap(x) << bits);
}

/// @notice Implements the lower than operation (<) in the SD59x18 type.
function lt(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = unwrap(x) < unwrap(y);
}

/// @notice Implements the lower than or equal to operation (<=) in the SD59x18 type.
function lte(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = unwrap(x) <= unwrap(y);
}

/// @notice Implements the unchecked modulo operation (%) in the SD59x18 type.
function mod(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    result = wrap(unwrap(x) % unwrap(y));
}

/// @notice Implements the not equal operation (!=) in the SD59x18 type.
function neq(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = unwrap(x) != unwrap(y);
}

/// @notice Implements the OR (|) bitwise operation in the SD59x18 type.
function or(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    result = wrap(unwrap(x) | unwrap(y));
}

/// @notice Implements the right shift operation (>>) in the SD59x18 type.
function rshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
    result = wrap(unwrap(x) >> bits);
}

/// @notice Implements the checked subtraction operation (-) in the SD59x18 type.
function sub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    result = wrap(unwrap(x) - unwrap(y));
}

/// @notice Implements the unchecked addition operation (+) in the SD59x18 type.
function uncheckedAdd(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    unchecked {
        result = wrap(unwrap(x) + unwrap(y));
    }
}

/// @notice Implements the unchecked subtraction operation (-) in the SD59x18 type.
function uncheckedSub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    unchecked {
        result = wrap(unwrap(x) - unwrap(y));
    }
}

/// @notice Implements the unchecked unary minus operation (-) in the SD59x18 type.
function uncheckedUnary(SD59x18 x) pure returns (SD59x18 result) {
    unchecked {
        result = wrap(-unwrap(x));
    }
}

/// @notice Implements the XOR (^) bitwise operation in the SD59x18 type.
function xor(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    result = wrap(unwrap(x) ^ unwrap(y));
}

File 23 of 62 : Math.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { MAX_UINT128, MAX_UINT40, msb, mulDiv, mulDiv18, prbExp2, prbSqrt } from "../Common.sol";
import {
    uHALF_UNIT,
    uLOG2_10,
    uLOG2_E,
    uMAX_SD59x18,
    uMAX_WHOLE_SD59x18,
    uMIN_SD59x18,
    uMIN_WHOLE_SD59x18,
    UNIT,
    uUNIT,
    ZERO
} from "./Constants.sol";
import {
    PRBMath_SD59x18_Abs_MinSD59x18,
    PRBMath_SD59x18_Ceil_Overflow,
    PRBMath_SD59x18_Div_InputTooSmall,
    PRBMath_SD59x18_Div_Overflow,
    PRBMath_SD59x18_Exp_InputTooBig,
    PRBMath_SD59x18_Exp2_InputTooBig,
    PRBMath_SD59x18_Floor_Underflow,
    PRBMath_SD59x18_Gm_Overflow,
    PRBMath_SD59x18_Gm_NegativeProduct,
    PRBMath_SD59x18_Log_InputTooSmall,
    PRBMath_SD59x18_Mul_InputTooSmall,
    PRBMath_SD59x18_Mul_Overflow,
    PRBMath_SD59x18_Powu_Overflow,
    PRBMath_SD59x18_Sqrt_NegativeInput,
    PRBMath_SD59x18_Sqrt_Overflow
} from "./Errors.sol";
import { unwrap, wrap } from "./Helpers.sol";
import { SD59x18 } from "./ValueType.sol";

/// @notice Calculate the absolute value of x.
///
/// @dev Requirements:
/// - x must be greater than `MIN_SD59x18`.
///
/// @param x The SD59x18 number for which to calculate the absolute value.
/// @param result The absolute value of x as an SD59x18 number.
function abs(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = unwrap(x);
    if (xInt == uMIN_SD59x18) {
        revert PRBMath_SD59x18_Abs_MinSD59x18();
    }
    result = xInt < 0 ? wrap(-xInt) : x;
}

/// @notice Calculates the arithmetic average of x and y, rounding towards zero.
/// @param x The first operand as an SD59x18 number.
/// @param y The second operand as an SD59x18 number.
/// @return result The arithmetic average as an SD59x18 number.
function avg(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    int256 xInt = unwrap(x);
    int256 yInt = unwrap(y);

    unchecked {
        // This is equivalent to "x / 2 +  y / 2" but faster.
        // This operation can never overflow.
        int256 sum = (xInt >> 1) + (yInt >> 1);

        if (sum < 0) {
            // If at least one of x and y is odd, we add 1 to the result, since shifting negative numbers to the right rounds
            // down to infinity. The right part is equivalent to "sum + (x % 2 == 1 || y % 2 == 1)" but faster.
            assembly ("memory-safe") {
                result := add(sum, and(or(xInt, yInt), 1))
            }
        } else {
            // We need to add 1 if both x and y are odd to account for the double 0.5 remainder that is truncated after shifting.
            result = wrap(sum + (xInt & yInt & 1));
        }
    }
}

/// @notice Yields the smallest whole SD59x18 number greater than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be less than or equal to `MAX_WHOLE_SD59x18`.
///
/// @param x The SD59x18 number to ceil.
/// @param result The least number greater than or equal to x, as an SD59x18 number.
function ceil(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = unwrap(x);
    if (xInt > uMAX_WHOLE_SD59x18) {
        revert PRBMath_SD59x18_Ceil_Overflow(x);
    }

    int256 remainder = xInt % uUNIT;
    if (remainder == 0) {
        result = x;
    } else {
        unchecked {
            // Solidity uses C fmod style, which returns a modulus with the same sign as x.
            int256 resultInt = xInt - remainder;
            if (xInt > 0) {
                resultInt += uUNIT;
            }
            result = wrap(resultInt);
        }
    }
}

/// @notice Divides two SD59x18 numbers, returning a new SD59x18 number. Rounds towards zero.
///
/// @dev This is a variant of `mulDiv` that works with signed numbers. Works by computing the signs and the absolute values
/// separately.
///
/// Requirements:
/// - All from `Common.mulDiv`.
/// - None of the inputs can be `MIN_SD59x18`.
/// - The denominator cannot be zero.
/// - The result must fit within int256.
///
/// Caveats:
/// - All from `Common.mulDiv`.
///
/// @param x The numerator as an SD59x18 number.
/// @param y The denominator as an SD59x18 number.
/// @param result The quotient as an SD59x18 number.
function div(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    int256 xInt = unwrap(x);
    int256 yInt = unwrap(y);
    if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
        revert PRBMath_SD59x18_Div_InputTooSmall();
    }

    // Get hold of the absolute values of x and y.
    uint256 xAbs;
    uint256 yAbs;
    unchecked {
        xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
        yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
    }

    // Compute the absolute value (x*UNIT)÷y. The resulting value must fit within int256.
    uint256 resultAbs = mulDiv(xAbs, uint256(uUNIT), yAbs);
    if (resultAbs > uint256(uMAX_SD59x18)) {
        revert PRBMath_SD59x18_Div_Overflow(x, y);
    }

    // Check if x and y have the same sign. This works thanks to two's complement; the left-most bit is the sign bit.
    bool sameSign = (xInt ^ yInt) > -1;

    // If the inputs don't have the same sign, the result should be negative. Otherwise, it should be positive.
    unchecked {
        result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
    }
}

/// @notice Calculates the natural exponent of x.
///
/// @dev Based on the formula:
///
/// $$
/// e^x = 2^{x * log_2{e}}
/// $$
///
/// Requirements:
/// - All from `log2`.
/// - x must be less than 133.084258667509499441.
///
/// Caveats:
/// - All from `exp2`.
/// - For any x less than -41.446531673892822322, the result is zero.
///
/// @param x The exponent as an SD59x18 number.
/// @return result The result as an SD59x18 number.
function exp(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = unwrap(x);
    // Without this check, the value passed to `exp2` would be less than -59.794705707972522261.
    if (xInt < -41_446531673892822322) {
        return ZERO;
    }

    // Without this check, the value passed to `exp2` would be greater than 192.
    if (xInt >= 133_084258667509499441) {
        revert PRBMath_SD59x18_Exp_InputTooBig(x);
    }

    unchecked {
        // Do the fixed-point multiplication inline to save gas.
        int256 doubleUnitProduct = xInt * uLOG2_E;
        result = exp2(wrap(doubleUnitProduct / uUNIT));
    }
}

/// @notice Calculates the binary exponent of x using the binary fraction method.
///
/// @dev Based on the formula:
///
/// $$
/// 2^{-x} = \frac{1}{2^x}
/// $$
///
/// See https://ethereum.stackexchange.com/q/79903/24693.
///
/// Requirements:
/// - x must be 192 or less.
/// - The result must fit within `MAX_SD59x18`.
///
/// Caveats:
/// - For any x less than -59.794705707972522261, the result is zero.
///
/// @param x The exponent as an SD59x18 number.
/// @return result The result as an SD59x18 number.
function exp2(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = unwrap(x);
    if (xInt < 0) {
        // 2^59.794705707972522262 is the maximum number whose inverse does not truncate down to zero.
        if (xInt < -59_794705707972522261) {
            return ZERO;
        }

        unchecked {
            // Do the fixed-point inversion $1/2^x$ inline to save gas. 1e36 is UNIT * UNIT.
            result = wrap(1e36 / unwrap(exp2(wrap(-xInt))));
        }
    } else {
        // 2^192 doesn't fit within the 192.64-bit format used internally in this function.
        if (xInt >= 192e18) {
            revert PRBMath_SD59x18_Exp2_InputTooBig(x);
        }

        unchecked {
            // Convert x to the 192.64-bit fixed-point format.
            uint256 x_192x64 = uint256((xInt << 64) / uUNIT);

            // It is safe to convert the result to int256 with no checks because the maximum input allowed in this function is 192.
            result = wrap(int256(prbExp2(x_192x64)));
        }
    }
}

/// @notice Yields the greatest whole SD59x18 number less than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be greater than or equal to `MIN_WHOLE_SD59x18`.
///
/// @param x The SD59x18 number to floor.
/// @param result The greatest integer less than or equal to x, as an SD59x18 number.
function floor(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = unwrap(x);
    if (xInt < uMIN_WHOLE_SD59x18) {
        revert PRBMath_SD59x18_Floor_Underflow(x);
    }

    int256 remainder = xInt % uUNIT;
    if (remainder == 0) {
        result = x;
    } else {
        unchecked {
            // Solidity uses C fmod style, which returns a modulus with the same sign as x.
            int256 resultInt = xInt - remainder;
            if (xInt < 0) {
                resultInt -= uUNIT;
            }
            result = wrap(resultInt);
        }
    }
}

/// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right.
/// of the radix point for negative numbers.
/// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part
/// @param x The SD59x18 number to get the fractional part of.
/// @param result The fractional part of x as an SD59x18 number.
function frac(SD59x18 x) pure returns (SD59x18 result) {
    result = wrap(unwrap(x) % uUNIT);
}

/// @notice Calculates the geometric mean of x and y, i.e. sqrt(x * y), rounding down.
///
/// @dev Requirements:
/// - x * y must fit within `MAX_SD59x18`, lest it overflows.
/// - x * y must not be negative, since this library does not handle complex numbers.
///
/// @param x The first operand as an SD59x18 number.
/// @param y The second operand as an SD59x18 number.
/// @return result The result as an SD59x18 number.
function gm(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    int256 xInt = unwrap(x);
    int256 yInt = unwrap(y);
    if (xInt == 0 || yInt == 0) {
        return ZERO;
    }

    unchecked {
        // Equivalent to "xy / x != y". Checking for overflow this way is faster than letting Solidity do it.
        int256 xyInt = xInt * yInt;
        if (xyInt / xInt != yInt) {
            revert PRBMath_SD59x18_Gm_Overflow(x, y);
        }

        // The product must not be negative, since this library does not handle complex numbers.
        if (xyInt < 0) {
            revert PRBMath_SD59x18_Gm_NegativeProduct(x, y);
        }

        // We don't need to multiply the result by `UNIT` here because the x*y product had picked up a factor of `UNIT`
        // during multiplication. See the comments within the `prbSqrt` function.
        uint256 resultUint = prbSqrt(uint256(xyInt));
        result = wrap(int256(resultUint));
    }
}

/// @notice Calculates 1 / x, rounding toward zero.
///
/// @dev Requirements:
/// - x cannot be zero.
///
/// @param x The SD59x18 number for which to calculate the inverse.
/// @return result The inverse as an SD59x18 number.
function inv(SD59x18 x) pure returns (SD59x18 result) {
    // 1e36 is UNIT * UNIT.
    result = wrap(1e36 / unwrap(x));
}

/// @notice Calculates the natural logarithm of x.
///
/// @dev Based on the formula:
///
/// $$
/// ln{x} = log_2{x} / log_2{e}$$.
/// $$
///
/// Requirements:
/// - All from `log2`.
///
/// Caveats:
/// - All from `log2`.
/// - This doesn't return exactly 1 for 2.718281828459045235, for that more fine-grained precision is needed.
///
/// @param x The SD59x18 number for which to calculate the natural logarithm.
/// @return result The natural logarithm as an SD59x18 number.
function ln(SD59x18 x) pure returns (SD59x18 result) {
    // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x)
    // can return is 195.205294292027477728.
    result = wrap((unwrap(log2(x)) * uUNIT) / uLOG2_E);
}

/// @notice Calculates the common logarithm of x.
///
/// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common
/// logarithm based on the formula:
///
/// $$
/// log_{10}{x} = log_2{x} / log_2{10}
/// $$
///
/// Requirements:
/// - All from `log2`.
///
/// Caveats:
/// - All from `log2`.
///
/// @param x The SD59x18 number for which to calculate the common logarithm.
/// @return result The common logarithm as an SD59x18 number.
function log10(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = unwrap(x);
    if (xInt < 0) {
        revert PRBMath_SD59x18_Log_InputTooSmall(x);
    }

    // Note that the `mul` in this block is the assembly mul operation, not the SD59x18 `mul`.
    // prettier-ignore
    assembly ("memory-safe") {
        switch x
        case 1 { result := mul(uUNIT, sub(0, 18)) }
        case 10 { result := mul(uUNIT, sub(1, 18)) }
        case 100 { result := mul(uUNIT, sub(2, 18)) }
        case 1000 { result := mul(uUNIT, sub(3, 18)) }
        case 10000 { result := mul(uUNIT, sub(4, 18)) }
        case 100000 { result := mul(uUNIT, sub(5, 18)) }
        case 1000000 { result := mul(uUNIT, sub(6, 18)) }
        case 10000000 { result := mul(uUNIT, sub(7, 18)) }
        case 100000000 { result := mul(uUNIT, sub(8, 18)) }
        case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
        case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
        case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
        case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
        case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
        case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
        case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
        case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
        case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
        case 1000000000000000000 { result := 0 }
        case 10000000000000000000 { result := uUNIT }
        case 100000000000000000000 { result := mul(uUNIT, 2) }
        case 1000000000000000000000 { result := mul(uUNIT, 3) }
        case 10000000000000000000000 { result := mul(uUNIT, 4) }
        case 100000000000000000000000 { result := mul(uUNIT, 5) }
        case 1000000000000000000000000 { result := mul(uUNIT, 6) }
        case 10000000000000000000000000 { result := mul(uUNIT, 7) }
        case 100000000000000000000000000 { result := mul(uUNIT, 8) }
        case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
        case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
        case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
        case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
        case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
        case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
        case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
        case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
        case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
        case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
        case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
        case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
        case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
        case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
        case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
        case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
        case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
        case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
        case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
        case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
        case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
        case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
        case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
        case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
        case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
        case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
        case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
        case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
        case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
        case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
        case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
        case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
        case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
        case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
        case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
        case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
        case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
        case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
        case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
        case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
        case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
        case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
        case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
        case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
        default {
            result := uMAX_SD59x18
        }
    }

    if (unwrap(result) == uMAX_SD59x18) {
        unchecked {
            // Do the fixed-point division inline to save gas.
            result = wrap((unwrap(log2(x)) * uUNIT) / uLOG2_10);
        }
    }
}

/// @notice Calculates the binary logarithm of x.
///
/// @dev Based on the iterative approximation algorithm.
/// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
///
/// Requirements:
/// - x must be greater than zero.
///
/// Caveats:
/// - The results are not perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation.
///
/// @param x The SD59x18 number for which to calculate the binary logarithm.
/// @return result The binary logarithm as an SD59x18 number.
function log2(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = unwrap(x);
    if (xInt <= 0) {
        revert PRBMath_SD59x18_Log_InputTooSmall(x);
    }

    unchecked {
        // This works because of:
        //
        // $$
        // log_2{x} = -log_2{\frac{1}{x}}
        // $$
        int256 sign;
        if (xInt >= uUNIT) {
            sign = 1;
        } else {
            sign = -1;
            // Do the fixed-point inversion inline to save gas. The numerator is UNIT * UNIT.
            xInt = 1e36 / xInt;
        }

        // Calculate the integer part of the logarithm and add it to the result and finally calculate $y = x * 2^(-n)$.
        uint256 n = msb(uint256(xInt / uUNIT));

        // This is the integer part of the logarithm as an SD59x18 number. The operation can't overflow
        // because n is maximum 255, UNIT is 1e18 and sign is either 1 or -1.
        int256 resultInt = int256(n) * uUNIT;

        // This is $y = x * 2^{-n}$.
        int256 y = xInt >> n;

        // If y is 1, the fractional part is zero.
        if (y == uUNIT) {
            return wrap(resultInt * sign);
        }

        // Calculate the fractional part via the iterative approximation.
        // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster.
        int256 DOUBLE_UNIT = 2e18;
        for (int256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
            y = (y * y) / uUNIT;

            // Is $y^2 > 2$ and so in the range [2,4)?
            if (y >= DOUBLE_UNIT) {
                // Add the 2^{-m} factor to the logarithm.
                resultInt = resultInt + delta;

                // Corresponds to z/2 on Wikipedia.
                y >>= 1;
            }
        }
        resultInt *= sign;
        result = wrap(resultInt);
    }
}

/// @notice Multiplies two SD59x18 numbers together, returning a new SD59x18 number.
///
/// @dev This is a variant of `mulDiv` that works with signed numbers and employs constant folding, i.e. the denominator
/// is always 1e18.
///
/// Requirements:
/// - All from `Common.mulDiv18`.
/// - None of the inputs can be `MIN_SD59x18`.
/// - The result must fit within `MAX_SD59x18`.
///
/// Caveats:
/// - To understand how this works in detail, see the NatSpec comments in `Common.mulDivSigned`.
///
/// @param x The multiplicand as an SD59x18 number.
/// @param y The multiplier as an SD59x18 number.
/// @return result The product as an SD59x18 number.
function mul(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    int256 xInt = unwrap(x);
    int256 yInt = unwrap(y);
    if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
        revert PRBMath_SD59x18_Mul_InputTooSmall();
    }

    // Get hold of the absolute values of x and y.
    uint256 xAbs;
    uint256 yAbs;
    unchecked {
        xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
        yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
    }

    uint256 resultAbs = mulDiv18(xAbs, yAbs);
    if (resultAbs > uint256(uMAX_SD59x18)) {
        revert PRBMath_SD59x18_Mul_Overflow(x, y);
    }

    // Check if x and y have the same sign. This works thanks to two's complement; the left-most bit is the sign bit.
    bool sameSign = (xInt ^ yInt) > -1;

    // If the inputs have the same sign, the result should be negative. Otherwise, it should be positive.
    unchecked {
        result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
    }
}

/// @notice Raises x to the power of y.
///
/// @dev Based on the formula:
///
/// $$
/// x^y = 2^{log_2{x} * y}
/// $$
///
/// Requirements:
/// - All from `exp2`, `log2` and `mul`.
/// - x cannot be zero.
///
/// Caveats:
/// - All from `exp2`, `log2` and `mul`.
/// - Assumes 0^0 is 1.
///
/// @param x Number to raise to given power y, as an SD59x18 number.
/// @param y Exponent to raise x to, as an SD59x18 number
/// @return result x raised to power y, as an SD59x18 number.
function pow(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    int256 xInt = unwrap(x);
    int256 yInt = unwrap(y);

    if (xInt == 0) {
        result = yInt == 0 ? UNIT : ZERO;
    } else {
        if (yInt == uUNIT) {
            result = x;
        } else {
            result = exp2(mul(log2(x), y));
        }
    }
}

/// @notice Raises x (an SD59x18 number) to the power y (unsigned basic integer) using the famous algorithm
/// algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring
///
/// Requirements:
/// - All from `abs` and `Common.mulDiv18`.
/// - The result must fit within `MAX_SD59x18`.
///
/// Caveats:
/// - All from `Common.mulDiv18`.
/// - Assumes 0^0 is 1.
///
/// @param x The base as an SD59x18 number.
/// @param y The exponent as an uint256.
/// @return result The result as an SD59x18 number.
function powu(SD59x18 x, uint256 y) pure returns (SD59x18 result) {
    uint256 xAbs = uint256(unwrap(abs(x)));

    // Calculate the first iteration of the loop in advance.
    uint256 resultAbs = y & 1 > 0 ? xAbs : uint256(uUNIT);

    // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster.
    uint256 yAux = y;
    for (yAux >>= 1; yAux > 0; yAux >>= 1) {
        xAbs = mulDiv18(xAbs, xAbs);

        // Equivalent to "y % 2 == 1" but faster.
        if (yAux & 1 > 0) {
            resultAbs = mulDiv18(resultAbs, xAbs);
        }
    }

    // The result must fit within `MAX_SD59x18`.
    if (resultAbs > uint256(uMAX_SD59x18)) {
        revert PRBMath_SD59x18_Powu_Overflow(x, y);
    }

    unchecked {
        // Is the base negative and the exponent an odd number?
        int256 resultInt = int256(resultAbs);
        bool isNegative = unwrap(x) < 0 && y & 1 == 1;
        if (isNegative) {
            resultInt = -resultInt;
        }
        result = wrap(resultInt);
    }
}

/// @notice Calculates the square root of x, rounding down. Only the positive root is returned.
/// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Requirements:
/// - x cannot be negative, since this library does not handle complex numbers.
/// - x must be less than `MAX_SD59x18` divided by `UNIT`.
///
/// @param x The SD59x18 number for which to calculate the square root.
/// @return result The result as an SD59x18 number.
function sqrt(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = unwrap(x);
    if (xInt < 0) {
        revert PRBMath_SD59x18_Sqrt_NegativeInput(x);
    }
    if (xInt > uMAX_SD59x18 / uUNIT) {
        revert PRBMath_SD59x18_Sqrt_Overflow(x);
    }

    unchecked {
        // Multiply x by `UNIT` to account for the factor of `UNIT` that is picked up when multiplying two SD59x18
        // numbers together (in this case, the two numbers are both the square root).
        uint256 resultUint = prbSqrt(uint256(xInt * uUNIT));
        result = wrap(int256(resultUint));
    }
}

File 24 of 62 : ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import "./Casting.sol" as C;
import "./Helpers.sol" as H;
import "./Math.sol" as M;

/// @notice The signed 59.18-decimal fixed-point number representation, which can have up to 59 digits and up to 18 decimals.
/// The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity type int256.
type SD59x18 is int256;

/*//////////////////////////////////////////////////////////////////////////
                                    CASTING
//////////////////////////////////////////////////////////////////////////*/

using {
    C.intoInt256,
    C.intoSD1x18,
    C.intoUD2x18,
    C.intoUD60x18,
    C.intoUint256,
    C.intoUint128,
    C.intoUint40,
    C.unwrap
} for SD59x18 global;

/*//////////////////////////////////////////////////////////////////////////
                            MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

using {
    M.abs,
    M.avg,
    M.ceil,
    M.div,
    M.exp,
    M.exp2,
    M.floor,
    M.frac,
    M.gm,
    M.inv,
    M.log10,
    M.log2,
    M.ln,
    M.mul,
    M.pow,
    M.powu,
    M.sqrt
} for SD59x18 global;

/*//////////////////////////////////////////////////////////////////////////
                                HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

using {
    H.add,
    H.and,
    H.eq,
    H.gt,
    H.gte,
    H.isZero,
    H.lshift,
    H.lt,
    H.lte,
    H.mod,
    H.neq,
    H.or,
    H.rshift,
    H.sub,
    H.uncheckedAdd,
    H.uncheckedSub,
    H.uncheckedUnary,
    H.xor
} for SD59x18 global;

File 25 of 62 : Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { PRBMath_UD2x18_IntoSD1x18_Overflow, PRBMath_UD2x18_IntoUint40_Overflow } from "./Errors.sol";
import { UD2x18 } from "./ValueType.sol";

/// @notice Casts an UD2x18 number into SD1x18.
/// - x must be less than or equal to `uMAX_SD1x18`.
function intoSD1x18(UD2x18 x) pure returns (SD1x18 result) {
    uint64 xUint = UD2x18.unwrap(x);
    if (xUint > uint64(uMAX_SD1x18)) {
        revert PRBMath_UD2x18_IntoSD1x18_Overflow(x);
    }
    result = SD1x18.wrap(int64(xUint));
}

/// @notice Casts an UD2x18 number into SD59x18.
/// @dev There is no overflow check because the domain of UD2x18 is a subset of SD59x18.
function intoSD59x18(UD2x18 x) pure returns (SD59x18 result) {
    result = SD59x18.wrap(int256(uint256(UD2x18.unwrap(x))));
}

/// @notice Casts an UD2x18 number into UD60x18.
/// @dev There is no overflow check because the domain of UD2x18 is a subset of UD60x18.
function intoUD60x18(UD2x18 x) pure returns (UD60x18 result) {
    result = UD60x18.wrap(UD2x18.unwrap(x));
}

/// @notice Casts an UD2x18 number into uint128.
/// @dev There is no overflow check because the domain of UD2x18 is a subset of uint128.
function intoUint128(UD2x18 x) pure returns (uint128 result) {
    result = uint128(UD2x18.unwrap(x));
}

/// @notice Casts an UD2x18 number into uint256.
/// @dev There is no overflow check because the domain of UD2x18 is a subset of uint256.
function intoUint256(UD2x18 x) pure returns (uint256 result) {
    result = uint256(UD2x18.unwrap(x));
}

/// @notice Casts an UD2x18 number into uint40.
/// @dev Requirements:
/// - x must be less than or equal to `MAX_UINT40`.
function intoUint40(UD2x18 x) pure returns (uint40 result) {
    uint64 xUint = UD2x18.unwrap(x);
    if (xUint > uint64(MAX_UINT40)) {
        revert PRBMath_UD2x18_IntoUint40_Overflow(x);
    }
    result = uint40(xUint);
}

/// @notice Alias for the `wrap` function.
function ud2x18(uint64 x) pure returns (UD2x18 result) {
    result = wrap(x);
}

/// @notice Unwrap an UD2x18 number into uint64.
function unwrap(UD2x18 x) pure returns (uint64 result) {
    result = UD2x18.unwrap(x);
}

/// @notice Wraps an uint64 number into the UD2x18 value type.
function wrap(uint64 x) pure returns (UD2x18 result) {
    result = UD2x18.wrap(x);
}

File 26 of 62 : Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { UD2x18 } from "./ValueType.sol";

/// @dev Euler's number as an UD2x18 number.
UD2x18 constant E = UD2x18.wrap(2_718281828459045235);

/// @dev The maximum value an UD2x18 number can have.
uint64 constant uMAX_UD2x18 = 18_446744073709551615;
UD2x18 constant MAX_UD2x18 = UD2x18.wrap(uMAX_UD2x18);

/// @dev PI as an UD2x18 number.
UD2x18 constant PI = UD2x18.wrap(3_141592653589793238);

/// @dev The unit amount that implies how many trailing decimals can be represented.
uint256 constant uUNIT = 1e18;
UD2x18 constant UNIT = UD2x18.wrap(1e18);

File 27 of 62 : Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { UD2x18 } from "./ValueType.sol";

/// @notice Emitted when trying to cast a UD2x18 number that doesn't fit in SD1x18.
error PRBMath_UD2x18_IntoSD1x18_Overflow(UD2x18 x);

/// @notice Emitted when trying to cast a UD2x18 number that doesn't fit in uint40.
error PRBMath_UD2x18_IntoUint40_Overflow(UD2x18 x);

File 28 of 62 : ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import "./Casting.sol" as C;

/// @notice The unsigned 2.18-decimal fixed-point number representation, which can have up to 2 digits and up to 18 decimals.
/// The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity type uint64.
/// This is useful when end users want to use uint64 to save gas, e.g. with tight variable packing in contract storage.
type UD2x18 is uint64;

/*//////////////////////////////////////////////////////////////////////////
                                    CASTING
//////////////////////////////////////////////////////////////////////////*/

using { C.intoSD1x18, C.intoSD59x18, C.intoUD60x18, C.intoUint256, C.intoUint128, C.intoUint40, C.unwrap } for UD2x18 global;

File 29 of 62 : UD60x18.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import "./ud60x18/Casting.sol";
import "./ud60x18/Constants.sol";
import "./ud60x18/Conversions.sol";
import "./ud60x18/Errors.sol";
import "./ud60x18/Helpers.sol";
import "./ud60x18/Math.sol";
import "./ud60x18/ValueType.sol";

File 30 of 62 : Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { uMAX_SD59x18 } from "../sd59x18/Constants.sol";
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import {
    PRBMath_UD60x18_IntoSD1x18_Overflow,
    PRBMath_UD60x18_IntoUD2x18_Overflow,
    PRBMath_UD60x18_IntoSD59x18_Overflow,
    PRBMath_UD60x18_IntoUint128_Overflow,
    PRBMath_UD60x18_IntoUint40_Overflow
} from "./Errors.sol";
import { UD60x18 } from "./ValueType.sol";

/// @notice Casts an UD60x18 number into SD1x18.
/// @dev Requirements:
/// - x must be less than or equal to `uMAX_SD1x18`.
function intoSD1x18(UD60x18 x) pure returns (SD1x18 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > uint256(int256(uMAX_SD1x18))) {
        revert PRBMath_UD60x18_IntoSD1x18_Overflow(x);
    }
    result = SD1x18.wrap(int64(uint64(xUint)));
}

/// @notice Casts an UD60x18 number into UD2x18.
/// @dev Requirements:
/// - x must be less than or equal to `uMAX_UD2x18`.
function intoUD2x18(UD60x18 x) pure returns (UD2x18 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > uMAX_UD2x18) {
        revert PRBMath_UD60x18_IntoUD2x18_Overflow(x);
    }
    result = UD2x18.wrap(uint64(xUint));
}

/// @notice Casts an UD60x18 number into SD59x18.
/// @dev Requirements:
/// - x must be less than or equal to `uMAX_SD59x18`.
function intoSD59x18(UD60x18 x) pure returns (SD59x18 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > uint256(uMAX_SD59x18)) {
        revert PRBMath_UD60x18_IntoSD59x18_Overflow(x);
    }
    result = SD59x18.wrap(int256(xUint));
}

/// @notice Casts an UD60x18 number into uint128.
/// @dev This is basically a functional alias for the `unwrap` function.
function intoUint256(UD60x18 x) pure returns (uint256 result) {
    result = UD60x18.unwrap(x);
}

/// @notice Casts an UD60x18 number into uint128.
/// @dev Requirements:
/// - x must be less than or equal to `MAX_UINT128`.
function intoUint128(UD60x18 x) pure returns (uint128 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > MAX_UINT128) {
        revert PRBMath_UD60x18_IntoUint128_Overflow(x);
    }
    result = uint128(xUint);
}

/// @notice Casts an UD60x18 number into uint40.
/// @dev Requirements:
/// - x must be less than or equal to `MAX_UINT40`.
function intoUint40(UD60x18 x) pure returns (uint40 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > MAX_UINT40) {
        revert PRBMath_UD60x18_IntoUint40_Overflow(x);
    }
    result = uint40(xUint);
}

/// @notice Alias for the `wrap` function.
function ud(uint256 x) pure returns (UD60x18 result) {
    result = wrap(x);
}

/// @notice Alias for the `wrap` function.
function ud60x18(uint256 x) pure returns (UD60x18 result) {
    result = wrap(x);
}

/// @notice Unwraps an UD60x18 number into uint256.
function unwrap(UD60x18 x) pure returns (uint256 result) {
    result = UD60x18.unwrap(x);
}

/// @notice Wraps an uint256 number into the UD60x18 value type.
function wrap(uint256 x) pure returns (UD60x18 result) {
    result = UD60x18.wrap(x);
}

File 31 of 62 : Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { UD60x18 } from "./ValueType.sol";

/// @dev Euler's number as an UD60x18 number.
UD60x18 constant E = UD60x18.wrap(2_718281828459045235);

/// @dev Half the UNIT number.
uint256 constant uHALF_UNIT = 0.5e18;
UD60x18 constant HALF_UNIT = UD60x18.wrap(uHALF_UNIT);

/// @dev log2(10) as an UD60x18 number.
uint256 constant uLOG2_10 = 3_321928094887362347;
UD60x18 constant LOG2_10 = UD60x18.wrap(uLOG2_10);

/// @dev log2(e) as an UD60x18 number.
uint256 constant uLOG2_E = 1_442695040888963407;
UD60x18 constant LOG2_E = UD60x18.wrap(uLOG2_E);

/// @dev The maximum value an UD60x18 number can have.
uint256 constant uMAX_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_584007913129639935;
UD60x18 constant MAX_UD60x18 = UD60x18.wrap(uMAX_UD60x18);

/// @dev The maximum whole value an UD60x18 number can have.
uint256 constant uMAX_WHOLE_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_000000000000000000;
UD60x18 constant MAX_WHOLE_UD60x18 = UD60x18.wrap(uMAX_WHOLE_UD60x18);

/// @dev PI as an UD60x18 number.
UD60x18 constant PI = UD60x18.wrap(3_141592653589793238);

/// @dev The unit amount that implies how many trailing decimals can be represented.
uint256 constant uUNIT = 1e18;
UD60x18 constant UNIT = UD60x18.wrap(uUNIT);

/// @dev Zero as an UD60x18 number.
UD60x18 constant ZERO = UD60x18.wrap(0);

File 32 of 62 : Conversions.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { uMAX_UD60x18, uUNIT } from "./Constants.sol";
import { PRBMath_UD60x18_Convert_Overflow } from "./Errors.sol";
import { UD60x18 } from "./ValueType.sol";

/// @notice Converts an UD60x18 number to a simple integer by dividing it by `UNIT`. Rounds towards zero in the process.
/// @dev Rounds down in the process.
/// @param x The UD60x18 number to convert.
/// @return result The same number in basic integer form.
function convert(UD60x18 x) pure returns (uint256 result) {
    result = UD60x18.unwrap(x) / uUNIT;
}

/// @notice Converts a simple integer to UD60x18 by multiplying it by `UNIT`.
///
/// @dev Requirements:
/// - x must be less than or equal to `MAX_UD60x18` divided by `UNIT`.
///
/// @param x The basic integer to convert.
/// @param result The same number converted to UD60x18.
function convert(uint256 x) pure returns (UD60x18 result) {
    if (x > uMAX_UD60x18 / uUNIT) {
        revert PRBMath_UD60x18_Convert_Overflow(x);
    }
    unchecked {
        result = UD60x18.wrap(x * uUNIT);
    }
}

/// @notice Alias for the `convert` function defined above.
/// @dev Here for backward compatibility. Will be removed in V4.
function fromUD60x18(UD60x18 x) pure returns (uint256 result) {
    result = convert(x);
}

/// @notice Alias for the `convert` function defined above.
/// @dev Here for backward compatibility. Will be removed in V4.
function toUD60x18(uint256 x) pure returns (UD60x18 result) {
    result = convert(x);
}

File 33 of 62 : Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { UD60x18 } from "./ValueType.sol";

/// @notice Emitted when ceiling a number overflows UD60x18.
error PRBMath_UD60x18_Ceil_Overflow(UD60x18 x);

/// @notice Emitted when converting a basic integer to the fixed-point format overflows UD60x18.
error PRBMath_UD60x18_Convert_Overflow(uint256 x);

/// @notice Emitted when taking the natural exponent of a base greater than 133.084258667509499441.
error PRBMath_UD60x18_Exp_InputTooBig(UD60x18 x);

/// @notice Emitted when taking the binary exponent of a base greater than 192.
error PRBMath_UD60x18_Exp2_InputTooBig(UD60x18 x);

/// @notice Emitted when taking the geometric mean of two numbers and multiplying them overflows UD60x18.
error PRBMath_UD60x18_Gm_Overflow(UD60x18 x, UD60x18 y);

/// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in SD1x18.
error PRBMath_UD60x18_IntoSD1x18_Overflow(UD60x18 x);

/// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in SD59x18.
error PRBMath_UD60x18_IntoSD59x18_Overflow(UD60x18 x);

/// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in UD2x18.
error PRBMath_UD60x18_IntoUD2x18_Overflow(UD60x18 x);

/// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint128.
error PRBMath_UD60x18_IntoUint128_Overflow(UD60x18 x);

/// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint40.
error PRBMath_UD60x18_IntoUint40_Overflow(UD60x18 x);

/// @notice Emitted when taking the logarithm of a number less than 1.
error PRBMath_UD60x18_Log_InputTooSmall(UD60x18 x);

/// @notice Emitted when calculating the square root overflows UD60x18.
error PRBMath_UD60x18_Sqrt_Overflow(UD60x18 x);

File 34 of 62 : Helpers.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { unwrap, wrap } from "./Casting.sol";
import { UD60x18 } from "./ValueType.sol";

/// @notice Implements the checked addition operation (+) in the UD60x18 type.
function add(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(unwrap(x) + unwrap(y));
}

/// @notice Implements the AND (&) bitwise operation in the UD60x18 type.
function and(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
    result = wrap(unwrap(x) & bits);
}

/// @notice Implements the equal operation (==) in the UD60x18 type.
function eq(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = unwrap(x) == unwrap(y);
}

/// @notice Implements the greater than operation (>) in the UD60x18 type.
function gt(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = unwrap(x) > unwrap(y);
}

/// @notice Implements the greater than or equal to operation (>=) in the UD60x18 type.
function gte(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = unwrap(x) >= unwrap(y);
}

/// @notice Implements a zero comparison check function in the UD60x18 type.
function isZero(UD60x18 x) pure returns (bool result) {
    // This wouldn't work if x could be negative.
    result = unwrap(x) == 0;
}

/// @notice Implements the left shift operation (<<) in the UD60x18 type.
function lshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
    result = wrap(unwrap(x) << bits);
}

/// @notice Implements the lower than operation (<) in the UD60x18 type.
function lt(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = unwrap(x) < unwrap(y);
}

/// @notice Implements the lower than or equal to operation (<=) in the UD60x18 type.
function lte(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = unwrap(x) <= unwrap(y);
}

/// @notice Implements the checked modulo operation (%) in the UD60x18 type.
function mod(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(unwrap(x) % unwrap(y));
}

/// @notice Implements the not equal operation (!=) in the UD60x18 type
function neq(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = unwrap(x) != unwrap(y);
}

/// @notice Implements the OR (|) bitwise operation in the UD60x18 type.
function or(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(unwrap(x) | unwrap(y));
}

/// @notice Implements the right shift operation (>>) in the UD60x18 type.
function rshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
    result = wrap(unwrap(x) >> bits);
}

/// @notice Implements the checked subtraction operation (-) in the UD60x18 type.
function sub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(unwrap(x) - unwrap(y));
}

/// @notice Implements the unchecked addition operation (+) in the UD60x18 type.
function uncheckedAdd(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    unchecked {
        result = wrap(unwrap(x) + unwrap(y));
    }
}

/// @notice Implements the unchecked subtraction operation (-) in the UD60x18 type.
function uncheckedSub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    unchecked {
        result = wrap(unwrap(x) - unwrap(y));
    }
}

/// @notice Implements the XOR (^) bitwise operation in the UD60x18 type.
function xor(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(unwrap(x) ^ unwrap(y));
}

File 35 of 62 : Math.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import { msb, mulDiv, mulDiv18, prbExp2, prbSqrt } from "../Common.sol";
import { unwrap, wrap } from "./Casting.sol";
import { uHALF_UNIT, uLOG2_10, uLOG2_E, uMAX_UD60x18, uMAX_WHOLE_UD60x18, UNIT, uUNIT, ZERO } from "./Constants.sol";
import {
    PRBMath_UD60x18_Ceil_Overflow,
    PRBMath_UD60x18_Exp_InputTooBig,
    PRBMath_UD60x18_Exp2_InputTooBig,
    PRBMath_UD60x18_Gm_Overflow,
    PRBMath_UD60x18_Log_InputTooSmall,
    PRBMath_UD60x18_Sqrt_Overflow
} from "./Errors.sol";
import { UD60x18 } from "./ValueType.sol";

/*//////////////////////////////////////////////////////////////////////////
                            MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

/// @notice Calculates the arithmetic average of x and y, rounding down.
///
/// @dev Based on the formula:
///
/// $$
/// avg(x, y) = (x & y) + ((xUint ^ yUint) / 2)
/// $$
//
/// In English, what this formula does is:
///
/// 1. AND x and y.
/// 2. Calculate half of XOR x and y.
/// 3. Add the two results together.
///
/// This technique is known as SWAR, which stands for "SIMD within a register". You can read more about it here:
/// https://devblogs.microsoft.com/oldnewthing/20220207-00/?p=106223
///
/// @param x The first operand as an UD60x18 number.
/// @param y The second operand as an UD60x18 number.
/// @return result The arithmetic average as an UD60x18 number.
function avg(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    uint256 xUint = unwrap(x);
    uint256 yUint = unwrap(y);
    unchecked {
        result = wrap((xUint & yUint) + ((xUint ^ yUint) >> 1));
    }
}

/// @notice Yields the smallest whole UD60x18 number greater than or equal to x.
///
/// @dev This is optimized for fractional value inputs, because for every whole value there are "1e18 - 1" fractional
/// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be less than or equal to `MAX_WHOLE_UD60x18`.
///
/// @param x The UD60x18 number to ceil.
/// @param result The least number greater than or equal to x, as an UD60x18 number.
function ceil(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = unwrap(x);
    if (xUint > uMAX_WHOLE_UD60x18) {
        revert PRBMath_UD60x18_Ceil_Overflow(x);
    }

    assembly ("memory-safe") {
        // Equivalent to "x % UNIT" but faster.
        let remainder := mod(x, uUNIT)

        // Equivalent to "UNIT - remainder" but faster.
        let delta := sub(uUNIT, remainder)

        // Equivalent to "x + delta * (remainder > 0 ? 1 : 0)" but faster.
        result := add(x, mul(delta, gt(remainder, 0)))
    }
}

/// @notice Divides two UD60x18 numbers, returning a new UD60x18 number. Rounds towards zero.
///
/// @dev Uses `mulDiv` to enable overflow-safe multiplication and division.
///
/// Requirements:
/// - The denominator cannot be zero.
///
/// @param x The numerator as an UD60x18 number.
/// @param y The denominator as an UD60x18 number.
/// @param result The quotient as an UD60x18 number.
function div(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(mulDiv(unwrap(x), uUNIT, unwrap(y)));
}

/// @notice Calculates the natural exponent of x.
///
/// @dev Based on the formula:
///
/// $$
/// e^x = 2^{x * log_2{e}}
/// $$
///
/// Requirements:
/// - All from `log2`.
/// - x must be less than 133.084258667509499441.
///
/// @param x The exponent as an UD60x18 number.
/// @return result The result as an UD60x18 number.
function exp(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = unwrap(x);

    // Without this check, the value passed to `exp2` would be greater than 192.
    if (xUint >= 133_084258667509499441) {
        revert PRBMath_UD60x18_Exp_InputTooBig(x);
    }

    unchecked {
        // We do the fixed-point multiplication inline rather than via the `mul` function to save gas.
        uint256 doubleUnitProduct = xUint * uLOG2_E;
        result = exp2(wrap(doubleUnitProduct / uUNIT));
    }
}

/// @notice Calculates the binary exponent of x using the binary fraction method.
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693.
///
/// Requirements:
/// - x must be 192 or less.
/// - The result must fit within `MAX_UD60x18`.
///
/// @param x The exponent as an UD60x18 number.
/// @return result The result as an UD60x18 number.
function exp2(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = unwrap(x);

    // Numbers greater than or equal to 2^192 don't fit within the 192.64-bit format.
    if (xUint >= 192e18) {
        revert PRBMath_UD60x18_Exp2_InputTooBig(x);
    }

    // Convert x to the 192.64-bit fixed-point format.
    uint256 x_192x64 = (xUint << 64) / uUNIT;

    // Pass x to the `prbExp2` function, which uses the 192.64-bit fixed-point number representation.
    result = wrap(prbExp2(x_192x64));
}

/// @notice Yields the greatest whole UD60x18 number less than or equal to x.
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
/// @param x The UD60x18 number to floor.
/// @param result The greatest integer less than or equal to x, as an UD60x18 number.
function floor(UD60x18 x) pure returns (UD60x18 result) {
    assembly ("memory-safe") {
        // Equivalent to "x % UNIT" but faster.
        let remainder := mod(x, uUNIT)

        // Equivalent to "x - remainder * (remainder > 0 ? 1 : 0)" but faster.
        result := sub(x, mul(remainder, gt(remainder, 0)))
    }
}

/// @notice Yields the excess beyond the floor of x.
/// @dev Based on the odd function definition https://en.wikipedia.org/wiki/Fractional_part.
/// @param x The UD60x18 number to get the fractional part of.
/// @param result The fractional part of x as an UD60x18 number.
function frac(UD60x18 x) pure returns (UD60x18 result) {
    assembly ("memory-safe") {
        result := mod(x, uUNIT)
    }
}

/// @notice Calculates the geometric mean of x and y, i.e. $$sqrt(x * y)$$, rounding down.
///
/// @dev Requirements:
/// - x * y must fit within `MAX_UD60x18`, lest it overflows.
///
/// @param x The first operand as an UD60x18 number.
/// @param y The second operand as an UD60x18 number.
/// @return result The result as an UD60x18 number.
function gm(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    uint256 xUint = unwrap(x);
    uint256 yUint = unwrap(y);
    if (xUint == 0 || yUint == 0) {
        return ZERO;
    }

    unchecked {
        // Checking for overflow this way is faster than letting Solidity do it.
        uint256 xyUint = xUint * yUint;
        if (xyUint / xUint != yUint) {
            revert PRBMath_UD60x18_Gm_Overflow(x, y);
        }

        // We don't need to multiply the result by `UNIT` here because the x*y product had picked up a factor of `UNIT`
        // during multiplication. See the comments in the `prbSqrt` function.
        result = wrap(prbSqrt(xyUint));
    }
}

/// @notice Calculates 1 / x, rounding toward zero.
///
/// @dev Requirements:
/// - x cannot be zero.
///
/// @param x The UD60x18 number for which to calculate the inverse.
/// @return result The inverse as an UD60x18 number.
function inv(UD60x18 x) pure returns (UD60x18 result) {
    unchecked {
        // 1e36 is UNIT * UNIT.
        result = wrap(1e36 / unwrap(x));
    }
}

/// @notice Calculates the natural logarithm of x.
///
/// @dev Based on the formula:
///
/// $$
/// ln{x} = log_2{x} / log_2{e}$$.
/// $$
///
/// Requirements:
/// - All from `log2`.
///
/// Caveats:
/// - All from `log2`.
/// - This doesn't return exactly 1 for 2.718281828459045235, for that more fine-grained precision is needed.
///
/// @param x The UD60x18 number for which to calculate the natural logarithm.
/// @return result The natural logarithm as an UD60x18 number.
function ln(UD60x18 x) pure returns (UD60x18 result) {
    unchecked {
        // We do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value
        // that `log2` can return is 196.205294292027477728.
        result = wrap((unwrap(log2(x)) * uUNIT) / uLOG2_E);
    }
}

/// @notice Calculates the common logarithm of x.
///
/// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common
/// logarithm based on the formula:
///
/// $$
/// log_{10}{x} = log_2{x} / log_2{10}
/// $$
///
/// Requirements:
/// - All from `log2`.
///
/// Caveats:
/// - All from `log2`.
///
/// @param x The UD60x18 number for which to calculate the common logarithm.
/// @return result The common logarithm as an UD60x18 number.
function log10(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = unwrap(x);
    if (xUint < uUNIT) {
        revert PRBMath_UD60x18_Log_InputTooSmall(x);
    }

    // Note that the `mul` in this assembly block is the assembly multiplication operation, not the UD60x18 `mul`.
    // prettier-ignore
    assembly ("memory-safe") {
        switch x
        case 1 { result := mul(uUNIT, sub(0, 18)) }
        case 10 { result := mul(uUNIT, sub(1, 18)) }
        case 100 { result := mul(uUNIT, sub(2, 18)) }
        case 1000 { result := mul(uUNIT, sub(3, 18)) }
        case 10000 { result := mul(uUNIT, sub(4, 18)) }
        case 100000 { result := mul(uUNIT, sub(5, 18)) }
        case 1000000 { result := mul(uUNIT, sub(6, 18)) }
        case 10000000 { result := mul(uUNIT, sub(7, 18)) }
        case 100000000 { result := mul(uUNIT, sub(8, 18)) }
        case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
        case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
        case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
        case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
        case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
        case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
        case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
        case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
        case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
        case 1000000000000000000 { result := 0 }
        case 10000000000000000000 { result := uUNIT }
        case 100000000000000000000 { result := mul(uUNIT, 2) }
        case 1000000000000000000000 { result := mul(uUNIT, 3) }
        case 10000000000000000000000 { result := mul(uUNIT, 4) }
        case 100000000000000000000000 { result := mul(uUNIT, 5) }
        case 1000000000000000000000000 { result := mul(uUNIT, 6) }
        case 10000000000000000000000000 { result := mul(uUNIT, 7) }
        case 100000000000000000000000000 { result := mul(uUNIT, 8) }
        case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
        case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
        case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
        case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
        case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
        case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
        case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
        case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
        case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
        case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
        case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
        case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
        case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
        case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
        case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
        case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
        case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
        case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
        case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
        case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
        case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
        case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
        case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
        case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
        case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
        case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
        case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
        case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
        case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
        case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
        case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
        case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
        case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
        case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
        case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
        case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
        case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
        case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
        case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
        case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
        case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
        case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
        case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
        case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
        case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 59) }
        default {
            result := uMAX_UD60x18
        }
    }

    if (unwrap(result) == uMAX_UD60x18) {
        unchecked {
            // Do the fixed-point division inline to save gas.
            result = wrap((unwrap(log2(x)) * uUNIT) / uLOG2_10);
        }
    }
}

/// @notice Calculates the binary logarithm of x.
///
/// @dev Based on the iterative approximation algorithm.
/// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
///
/// Requirements:
/// - x must be greater than or equal to UNIT, otherwise the result would be negative.
///
/// Caveats:
/// - The results are nor perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation.
///
/// @param x The UD60x18 number for which to calculate the binary logarithm.
/// @return result The binary logarithm as an UD60x18 number.
function log2(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = unwrap(x);

    if (xUint < uUNIT) {
        revert PRBMath_UD60x18_Log_InputTooSmall(x);
    }

    unchecked {
        // Calculate the integer part of the logarithm, add it to the result and finally calculate y = x * 2^(-n).
        uint256 n = msb(xUint / uUNIT);

        // This is the integer part of the logarithm as an UD60x18 number. The operation can't overflow because n
        // n is maximum 255 and UNIT is 1e18.
        uint256 resultUint = n * uUNIT;

        // This is $y = x * 2^{-n}$.
        uint256 y = xUint >> n;

        // If y is 1, the fractional part is zero.
        if (y == uUNIT) {
            return wrap(resultUint);
        }

        // Calculate the fractional part via the iterative approximation.
        // The "delta.rshift(1)" part is equivalent to "delta /= 2", but shifting bits is faster.
        uint256 DOUBLE_UNIT = 2e18;
        for (uint256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
            y = (y * y) / uUNIT;

            // Is y^2 > 2 and so in the range [2,4)?
            if (y >= DOUBLE_UNIT) {
                // Add the 2^{-m} factor to the logarithm.
                resultUint += delta;

                // Corresponds to z/2 on Wikipedia.
                y >>= 1;
            }
        }
        result = wrap(resultUint);
    }
}

/// @notice Multiplies two UD60x18 numbers together, returning a new UD60x18 number.
/// @dev See the documentation for the `Common.mulDiv18` function.
/// @param x The multiplicand as an UD60x18 number.
/// @param y The multiplier as an UD60x18 number.
/// @return result The product as an UD60x18 number.
function mul(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(mulDiv18(unwrap(x), unwrap(y)));
}

/// @notice Raises x to the power of y.
///
/// @dev Based on the formula:
///
/// $$
/// x^y = 2^{log_2{x} * y}
/// $$
///
/// Requirements:
/// - All from `exp2`, `log2` and `mul`.
///
/// Caveats:
/// - All from `exp2`, `log2` and `mul`.
/// - Assumes 0^0 is 1.
///
/// @param x Number to raise to given power y, as an UD60x18 number.
/// @param y Exponent to raise x to, as an UD60x18 number.
/// @return result x raised to power y, as an UD60x18 number.
function pow(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    uint256 xUint = unwrap(x);
    uint256 yUint = unwrap(y);

    if (xUint == 0) {
        result = yUint == 0 ? UNIT : ZERO;
    } else {
        if (yUint == uUNIT) {
            result = x;
        } else {
            result = exp2(mul(log2(x), y));
        }
    }
}

/// @notice Raises x (an UD60x18 number) to the power y (unsigned basic integer) using the famous algorithm
/// "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring
///
/// Requirements:
/// - The result must fit within `MAX_UD60x18`.
///
/// Caveats:
/// - All from "Common.mulDiv18".
/// - Assumes 0^0 is 1.
///
/// @param x The base as an UD60x18 number.
/// @param y The exponent as an uint256.
/// @return result The result as an UD60x18 number.
function powu(UD60x18 x, uint256 y) pure returns (UD60x18 result) {
    // Calculate the first iteration of the loop in advance.
    uint256 xUint = unwrap(x);
    uint256 resultUint = y & 1 > 0 ? xUint : uUNIT;

    // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster.
    for (y >>= 1; y > 0; y >>= 1) {
        xUint = mulDiv18(xUint, xUint);

        // Equivalent to "y % 2 == 1" but faster.
        if (y & 1 > 0) {
            resultUint = mulDiv18(resultUint, xUint);
        }
    }
    result = wrap(resultUint);
}

/// @notice Calculates the square root of x, rounding down.
/// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Requirements:
/// - x must be less than `MAX_UD60x18` divided by `UNIT`.
///
/// @param x The UD60x18 number for which to calculate the square root.
/// @return result The result as an UD60x18 number.
function sqrt(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = unwrap(x);

    unchecked {
        if (xUint > uMAX_UD60x18 / uUNIT) {
            revert PRBMath_UD60x18_Sqrt_Overflow(x);
        }
        // Multiply x by `UNIT` to account for the factor of `UNIT` that is picked up when multiplying two UD60x18
        // numbers together (in this case, the two numbers are both the square root).
        result = wrap(prbSqrt(xUint * uUNIT));
    }
}

File 36 of 62 : ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13;

import "./Casting.sol" as C;
import "./Helpers.sol" as H;
import "./Math.sol" as M;

/// @notice The unsigned 60.18-decimal fixed-point number representation, which can have up to 60 digits and up to 18 decimals.
/// The values of this are bound by the minimum and the maximum values permitted by the Solidity type uint256.
/// @dev The value type is defined here so it can be imported in all other files.
type UD60x18 is uint256;

/*//////////////////////////////////////////////////////////////////////////
                                    CASTING
//////////////////////////////////////////////////////////////////////////*/

using { C.intoSD1x18, C.intoUD2x18, C.intoSD59x18, C.intoUint128, C.intoUint256, C.intoUint40, C.unwrap } for UD60x18 global;

/*//////////////////////////////////////////////////////////////////////////
                            MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

/// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
using {
    M.avg,
    M.ceil,
    M.div,
    M.exp,
    M.exp2,
    M.floor,
    M.frac,
    M.gm,
    M.inv,
    M.ln,
    M.log10,
    M.log2,
    M.mul,
    M.pow,
    M.powu,
    M.sqrt
} for UD60x18 global;

/*//////////////////////////////////////////////////////////////////////////
                                HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

/// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
using {
    H.add,
    H.and,
    H.eq,
    H.gt,
    H.gte,
    H.isZero,
    H.lshift,
    H.lt,
    H.lte,
    H.mod,
    H.neq,
    H.or,
    H.rshift,
    H.sub,
    H.uncheckedAdd,
    H.uncheckedSub,
    H.xor
} for UD60x18 global;

File 37 of 62 : IAccessControlManager.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.16;

import {IAccessControlEnumerableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/IAccessControlEnumerableUpgradeable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import {IDepositManager} from "./IDepositManager.sol";
import {IrswETH} from "./IrswETH.sol";
import {IrswEXIT} from "./IrswEXIT.sol";
import {INodeOperatorRegistry} from "./INodeOperatorRegistry.sol";

/**
  @title IAccessControlManager
  @author https://github.com/max-taylor 
  @dev The interface for the Access Control Manager, which manages roles and permissions for contracts within the Swell ecosystem
*/
interface IAccessControlManager is IAccessControlEnumerableUpgradeable {
  // ***** Structs ******

  /**
    @dev Parameters for initializing the contract.
    @param admin The admin address
    @param swellTreasury The swell treasury address
  */
  struct InitializeParams {
    address admin;
    address swellTreasury;
  }

  // ***** Errors ******

  /**
    @dev Error thrown when attempting to pause an already-paused boolean
  */
  error AlreadyPaused();

  /**
    @dev Error thrown when attempting to unpause an already-unpaused boolean
  */
  error AlreadyUnpaused();

  // ***** Events ******

  /**
    @dev Emitted when a new DepositManager contract address is set.
    @param newAddress The new DepositManager contract address.
    @param oldAddress The old DepositManager contract address.
  */
  event UpdatedDepositManager(address newAddress, address oldAddress);

  /**
    @dev Emitted when a new NodeOperatorRegistry contract address is set.
    @param newAddress The new NodeOperatorRegistry contract address.
    @param oldAddress The old NodeOperatorRegistry contract address.
  */
  event UpdatedNodeOperatorRegistry(address newAddress, address oldAddress);

  /**
    @dev Emitted when a new SwellTreasury contract address is set.
    @param newAddress The new SwellTreasury contract address.
    @param oldAddress The old SwellTreasury contract address.
  */
  event UpdatedSwellTreasury(address newAddress, address oldAddress);

  /**
    @dev Emitted when a new rswETH contract address is set.
    @param newAddress The new rswETH contract address.
    @param oldAddress The old rswETH contract address.
  */
  event UpdatedRswETH(address newAddress, address oldAddress);

  /**
    @dev Emitted when a new rswEXIT contract address is set.
    @param newAddress The new rswEXIT contract address.
    @param oldAddress The old rswEXIT contract address.
  */
  event UpdatedRswEXIT(address newAddress, address oldAddress);

  /**
    @dev Emitted when core methods functionality is paused or unpaused.
    @param newPausedStatus The new paused status.
  */
  event CoreMethodsPause(bool newPausedStatus);

  /**
    @dev Emitted when bot methods functionality is paused or unpaused.
    @param newPausedStatus The new paused status.
  */
  event BotMethodsPause(bool newPausedStatus);

  /**
    @dev Emitted when operator methods functionality is paused or unpaused.
    @param newPausedStatus The new paused status.
  */
  event OperatorMethodsPause(bool newPausedStatus);

  /**
    @dev Emitted when withdrawals functionality is paused or unpaused.
    @param newPausedStatus The new paused status.
  */
  event WithdrawalsPause(bool newPausedStatus);

  /**
    @dev Emitted when all functionality is paused.
  */
  event Lockdown();

  // ************************************
  // ***** External Methods ******

  /**
   * @dev Pass-through method to call the _checkRole method on the inherited access control contract. This method is to be used by external contracts that are using this centralised access control manager, this ensures that if the check fails it reverts with the correct access control error message
   * @param role The role to check
   * @param account The account to check for
   */
  function checkRole(bytes32 role, address account) external view;

  // ***** Setters ******

  /**
   * @notice Sets the `rswETH` address to `_rswETH`.
   * @dev This function is only callable by the `PLATFORM_ADMIN` role.
   * @param _rswETH The address of the `rswETH` contract.
   */
  function setRswETH(IrswETH _rswETH) external;

  /**
   * @notice Sets the `rswEXIT` address to `_rswEXIT`.
   * @dev This function is only callable by the `PLATFORM_ADMIN` role.
   * @param _rswEXIT The address of the `rswEXIT` contract.
   */
  function setRswEXIT(IrswEXIT _rswEXIT) external;

  /**
   * @notice Sets the `DepositManager` address to `_depositManager`.
   * @dev This function is only callable by the `PLATFORM_ADMIN` role.
   * @param _depositManager The address of the `DepositManager` contract.
   */
  function setDepositManager(IDepositManager _depositManager) external;

  /**
   * @notice Sets the `NodeOperatorRegistry` address to `_NodeOperatorRegistry`.
   * @dev This function is only callable by the `PLATFORM_ADMIN` role.
   * @param _NodeOperatorRegistry The address of the `NodeOperatorRegistry` contract.
   */
  function setNodeOperatorRegistry(
    INodeOperatorRegistry _NodeOperatorRegistry
  ) external;

  /**
   * @notice Sets the `SwellTreasury` address to `_swellTreasury`.
   * @dev This function is only callable by the `PLATFORM_ADMIN` role.
   * @param _swellTreasury The new address of the `SwellTreasury` contract.
   */
  function setSwellTreasury(address _swellTreasury) external;

  // ***** Getters ******

  /**
    @dev Returns the PLATFORM_ADMIN role.
    @return The bytes32 representation of the PLATFORM_ADMIN role.
  */
  function PLATFORM_ADMIN() external pure returns (bytes32);

  /**
    @dev Returns the Swell Restaked ETH contract.
    @return The Swell Restaked ETH contract.
  */
  function rswETH() external view returns (IrswETH);

  /**
   * @dev Returns the rswEXIT contract.
   * @return The rswEXIT contract.
   */
  function rswEXIT() external view returns (IrswEXIT);

  /**
    @dev Returns the address of the Swell Treasury contract.
    @return The address of the Swell Treasury contract.
  */
  function SwellTreasury() external view returns (address);

  /**
    @dev Returns the Deposit Manager contract.
    @return The Deposit Manager contract.
  */
  function DepositManager() external view returns (IDepositManager);

  /**
    @dev Returns the Node Operator Registry contract.
    @return The Node Operator Registry contract.
  */
  function NodeOperatorRegistry() external view returns (INodeOperatorRegistry);

  /**
    @dev Returns true if core methods are currently paused.
    @return Whether core methods are paused.
  */
  function coreMethodsPaused() external view returns (bool);

  /**
    @dev Returns true if bot methods are currently paused.
    @return Whether bot methods are paused.
  */
  function botMethodsPaused() external view returns (bool);

  /**
    @dev Returns true if operator methods are currently paused.
    @return Whether operator methods are paused.
  */
  function operatorMethodsPaused() external view returns (bool);

  /**
    @dev Returns true if withdrawals are currently paused.
    @dev ! Note that this is completely unused in the current implementation and is a placeholder that will be used once the withdrawals are implemented.
    @return Whether withdrawals are paused.
  */
  function withdrawalsPaused() external view returns (bool);

  // ***** Pausable methods ******

  /**
    @dev Pauses the core methods of the Swell ecosystem, only callable by the PAUSER role
  */
  function pauseCoreMethods() external;

  /**
    @dev Unpauses the core methods of the Swell ecosystem, only callable by the UNPAUSER role
  */
  function unpauseCoreMethods() external;

  /**
    @dev Pauses the bot specific methods, only callable by the PAUSER role
  */
  function pauseBotMethods() external;

  /**
    @dev Unpauses the bot specific methods, only callable by the UNPAUSER role
  */
  function unpauseBotMethods() external;

  /**
    @dev Pauses the operator methods in the NO registry contract, only callable by the PAUSER role
  */
  function pauseOperatorMethods() external;

  /**
    @dev Unpauses the operator methods in the NO registry contract, only callable by the UNPAUSER role
  */
  function unpauseOperatorMethods() external;

  /**
    @dev Pauses the withdrawals of the Swell ecosystem, only callable by the PAUSER role
  */
  function pauseWithdrawals() external;

  /**
    @dev Unpauses the withdrawals of the Swell ecosystem, only callable by the UNPAUSER role
  */
  function unpauseWithdrawals() external;

  /**
    @dev Pause all the methods in one go, only callable by the PAUSER role.
  */
  function lockdown() external;

  /**
   * @dev This method withdraws contract's _token balance to a platform admin
   * @param _token The ERC20 token to withdraw from the contract
   */
  function withdrawERC20(IERC20 _token) external;
}

File 38 of 62 : IDepositManager.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.16;

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

/**
 * @title IDepositManager
 * @notice The interface for the deposit manager contract
 */
interface IDepositManager {
  // ***** Errors ******
  /**
   * @dev Error thrown when delegating to an operator who is not registered correctly for EigenLayer
   */
  error OperatorNotVerified();

  /**
   * @dev Error thrown when calling the withdrawETH method from an account that isn't the rswETH contract
   */
  error InvalidETHWithdrawCaller();

  /**
   * @dev Error thrown when the depositDataRoot parameter in the setupValidators contract doesn't match the onchain deposit data root from the deposit contract
   */
  error InvalidDepositDataRoot();

  /**
   * @dev Error thrown when setting up new validators and the contract doesn't hold enough ETH to be able to set them up.
   */
  error InsufficientETHBalance();

  /**
   * @dev Error thrown when the transferETHForWithdrawRequests method is called from an account other than rswEXIT
   */
  error OnlyRswEXITCanWithdrawETH();

  /**
   * @dev Error thrown when the transferETHForEigenLayerDeposits method is called from an account other than the EigenLayerManager
   */
  error OnlyEigenLayerManagerCanWithdrawETH();

  /**
   * @dev Error thrown when the transferTokenForDepositIntoStrategy method is called from an account other than the EigenLayerManager
   * @notice This method can only be called by the EigenLayerManager contract
   */
  error OnlyEigenLayerManagerCanWithdrawTokens();

  /**
   * @dev Error thrown when the admin has not set a LST Rate Provider
   */
  error NoRateProviderSet();

  /**
   * @dev Error thrown when a user tries to deposit an amount of zero
   */
  error CannotDepositZero();

  /**
   * @dev Error thrown when no public keys have been provided for validator setup
   */
  error NoPubKeysProvided();

  /**
   * @dev Error thrown when the EigenPod has not been created
   */
  error EigenPodNotCreated();

  // ***** Events ******
  /**
   * Emitted when new validators are setup
   * @param pubKeys The pubKeys that have been used for validator setup
   */
  event ValidatorsSetup(bytes[] pubKeys);

  /**
   * @dev Event is fired when some contracts receive ETH
   * @param from The account that sent the ETH
   * @param amount The amount of ETH received
   */
  event ETHReceived(address indexed from, uint256 amount);

  /**
   * @dev Event fired when the admin succesfully sets an exchange rate provider
   * @param token The address of the LST for which the exchange rate provider provides a rate
   * @param exchangeRateProvider The address of the exchange rate provider contract
   */
  event ExchangeRateProviderSet(
    address indexed token,
    address indexed exchangeRateProvider
  );

  /**
   * @dev Event is fired when the DepositManager sends ETH, this will currently only happen when rswEXIT calls transferETHForWithdrawRequests to get ETH for fulfill withdraw requests
   * @param to The account that is receiving the ETH
   * @param amount The amount of ETH sent
   */
  event EthSent(address indexed to, uint256 amount);

  /**
   * @dev Event fired when a user succesfully deposits an LST's into the Swell Deposit Manager
   * @param token The address of the LST deposited
   * @param tokenAmount The amount of the LST deposited
   */
  event LSTDeposited(address indexed token, uint256 tokenAmount);

  /**
   * @dev Event fired when the admin succesfully sets the EigenLayerManager contract
   * @param eigenLayerManager The address of the EigenLayerManager contract
   */
  event EigenLayerManagerSet(address eigenLayerManager);

  // ************************************

  // ***** External methods ******


  /**
   * @return The address of the EigenLayerManager contract
   */
  function eigenLayerManager() external view returns (IEigenLayerManager);

  /**
   * @dev Allows the admin to set the EigenLayer staking admin contract
   * @param _eigenLayerManager The address of the EigenLayerManager contract
   * @notice This method can only be called by the admin
   */
  function setEigenLayerManager(address _eigenLayerManager) external;
  
  /**
   * @dev This method is called by rswEXIT when it needs ETH to fulfill withdraw requests
   * @param _amount The amount of ETH to transfer to rswEXIT
   */
  function transferETHForWithdrawRequests(uint256 _amount) external;

  /**
   * @dev This method is called by the EigenLayerManager contract when it needs ETH to fulfill deposit requests onto EigenLayer
   * @param _pubKeys An array of public keys for operators registered on the Swell Network
   * @param _depositDataRoot The deposit data root
   * @return An array of ValidatorDetails
   */
  function transferETHForEigenLayerDeposits(
    bytes[] calldata _pubKeys,
    bytes32 _depositDataRoot
  ) external returns (INodeOperatorRegistry.ValidatorDetails[] memory);

  /**
   * @dev This method is called by the EigenLayerManager contract when it needs to transfer tokens to a StakerProxy to deposit into a strategy
   * @param _token The ERC20 token to transfer
   * @param _amount The amount of tokens to transfer
   * @param _stakerProxyAddress The address of the staker proxy contract who will receive the tokens to deposit
   */
  function transferTokenForDepositIntoStrategy(
    address _token,
    uint256 _amount,
    address _stakerProxyAddress
  ) external;

  /**
   * @dev This method withdraws the Deposit Manager contract's _token balance to a platform admin
   * @param _token The ERC20 token to withdraw from the contract
   */
  function withdrawERC20(IERC20 _token) external;

  /**
   * @dev Allows Users to Deposit liquid staking tokens into Swell Deposit Manager.
   * @param _token The LST token address.
   * @param _amount The amount of LST to deposit.
   * @param _minRswETH The minimum amount of RswETH to receive for the LST deposited.
   */
  function depositLST(address _token, uint256 _amount, uint256 _minRswETH) external;
}

File 39 of 62 : IEigenLayerManager.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.16;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IDelegationManager} from "../vendors/contracts/interfaces/IDelegationManager.sol";
import {IEigenPodManager} from "../vendors/contracts/interfaces/IEigenPodManager.sol";
import {BeaconChainProofs} from "../vendors/contracts/libraries/BeaconChainProofs.sol";
import {IDelayedWithdrawalRouter} from "../vendors/contracts/interfaces/IDelayedWithdrawalRouter.sol";
import {IStrategy} from "../vendors/contracts/interfaces/IStrategy.sol";

/**
 * @title IEigenLayerManager
 * @notice The interface for the EigenLayerManager contract
 */
interface IEigenLayerManager {
  // ***** Errors ******
  /**
   * @dev Error thrown when an admin passes an invalid staker Id
   */
  error InvalidStakerId();

  /**
   * @dev Error thrown when batch creating a staker and its pod with a batch size of zero.
   */
  error BatchSizeCannotBeZero();

  /**
   * @dev Error thrown when array lengths dont match.
   */
  error ArrayLengthMismatch();

  /**
   * @dev Error thrown when trying to send to the zero address.
   */
  error CannotSendToZeroAddress();

  /**
   * @dev Error thrown when stakerProxy implementation address already set.
   */
  error AddressAlreadySet();

  /**
   * @dev Error thrown when trying to deposit zero amount into a strategy
   */
  error CannotDepositZero();

  /**
   * @dev Error thrown when a token address does not match a Strategy's underlying token.
   */
  error StrategyTokenMismatch();

  /**
   * @dev Error thrown when a strategy is not set for a token.
   */
  error StrategyNotSet();

  /**
   * @dev Error thrown when a staker is still delegated to an operator during manual unassignment.
   */
  error StakerIsStillDelegatedToOperator();

  /**
   * @dev Error thrown when a staker was not found in an operator's staker list during manual unassignment.
   */
  error StakerNotFoundInOperatorStakerList();

  /**
   * @dev Error thrown when a staker is already assigned to an operator during manual assignment.
   */
  error StakerIsAlreadyAssignedToOperator();

  /**
   * @dev Error thrown when a staker is not delegated to an operator during manual assignment.
   */
  error StakerIsNotDelegatedToOperator();

  // ***** Events ******

  /**
   * @dev Event fired when an admin succesfully updates the signer address used for delegation
   * @param oldSigner The address of the old admin signer
   * @param newSigner The address of the new admin signer
   */
  event AdminSignerUpdated(address oldSigner, address newSigner);

  /**
   * @dev Event fired when a stakerProxy is successfully created
   * @param stakerProxyAddress The address of the created stakerProxy contract
   */
  event StakerCreated(address stakerProxyAddress);

  /**
   * @dev Event fired when the DelayedWithdrawalRouter is set.
   * @param delayedWithdrawalRouter The address of the DelayedWithdrawalRouter contract
   */
  event DelayedWithdrawalRouterSet(address delayedWithdrawalRouter);

  /**
   * @dev Event fired when the StrategyManager contract is set.
   * @param strategyManager The address of the StrategyManager contract
   */
  event StrategyManagerAddressSet(address strategyManager);

  /**
   * @dev Event fired when the DelegationManager contract is set.
   * @param _delegationManager The address of the DelegationManager contract
   */
  event DelegationManagerSet(address _delegationManager);

  /**
   * Emitted when new validators are setup on EigenLayer
   * @param stakerIds The IDs of the stakerProxy contracts used for validator setup
   * @param pubKeys The pubKeys that have been used for validator setup
   */
  event ValidatorsSetupOnEigenLayer(uint256[] stakerIds, bytes[] pubKeys);

  /**
   * @dev Event fired when the admin succesfully deposits LST's into an Eigen Layer Strategy
   * @param amount The amount of the LST deiposited into the Eigen Layer strategy
   * @param token The address of the LST deposited
   * @param currentStrategy The interface of the Eigen Layer strategy the LST was deposited into
   */
  event DepositedIntoStrategy(
    uint256 amount,
    address token,
    IStrategy currentStrategy
  );

  /**
   * Emitted when a stakerProxy contract is successfully registered
   * @param beacon The address of the beacon contract
   */
  event StakerProxyRegistered(address beacon);

  /**
   * Emitted when a stakerProxy contract is successfully upgraded to a new implementation
   * @param newImplementation The address of the new implementation contract
   */
  event StakerProxyUpgraded(address newImplementation);

  /**
   * @dev Event is fired when some contracts receive ETH
   * @param from The account that sent the ETH
   * @param amount The amount of ETH received
   */
  event ETHReceived(address indexed from, uint256 amount);

  /**
   * @dev Event fired when the admin succesfully sets the Eigen Layer strategy for a LST
   * @param token The address of the LST for which corresponds to the Eigen Layer strategy
   * @param strategy The address Eigen Layer strategy contract for the above LST
   */
  event StrategySetAndApproved(address indexed token, address indexed strategy);

  /**
   * @dev Event fired when a staker is manually unassigned from an operator.
   * @param stakerId The ID of the stakerProxy contract
   * @param operator The address of the operator
   */
  event StakerUnassignedFromOperator(uint256 stakerId, address operator);

  /**
   * @dev Event fired when a staker is manually assigned to an operator.
   * @param stakerId The ID of the stakerProxy contract
   * @param operator The address of the operator
   */
  event StakerAssignedToOperator(uint256 stakerId, address operator);

  // ************************************
  // ***** External methods ******

  /**
   * @dev Returns the address of the EigenLayer DelegationManager contract.
   * @return The address of the DelegationManager contract.
   */
  function DelegationManager() external view returns (IDelegationManager);

  /**
   * @dev Returns the address of the DelayedWithdrawalRouter contract.
   * @return The address of the DelayedWithdrawalRouter contract.
   */
  function DelayedWithdrawalRouter()
    external
    view
    returns (IDelayedWithdrawalRouter);

  /**
   * @dev Returns the address of the EigenPodManager contract.
   * @return The address of the EigenPodManager contract.
   */
  function EigenPodManager() external view returns (IEigenPodManager);

  /**
   * @dev Returns the address of the StrategyManager contract.
   * @return The address of the StrategyManager contract.
   */
  function strategyManagerAddress() external view returns (address);

  /**
   * @dev Returns the address of the admin signer.
   * @return The address of the admin signer.
   */
  function adminSigner() external view returns (address);

  /**
   * @dev Returns the latest stakeId assigned to a stakerProxy contract.
   * @return The latest stakeId.
   */
  function stakeId() external view returns (uint256);

  /**
   * @dev A mapping of token addresses to their corresponding EigenLayer strategy.
   * @param _token The address of the token.
   * @return The address of the strategy.
   */
  function tokenToStrategy(address _token) external view returns (address);

  /**
   * @dev A mapping of operator addresses to associated stakerProxy Ids.
   * @param _operator The address of the operator.
   * @return An array of stakerProxy Ids.
   */
  function getDelegatedStakers(
    address _operator
  ) external view returns (uint256[] memory);

  /**
   * @dev Returns the stakerProxy address for a given staker ID.
   * @notice Reverts if the staker ID is invalid.
   * @param _stakerId The ID of the staker.
   * @return stakerProxy The address of the stakerProxy contract.
   */
  function isValidStaker(
    uint256 _stakerId
  ) external view returns (address stakerProxy);

  /**
   * @dev Returns the stakerProxy address for a given staker ID.
   * @param _stakerId The ID of the staker.
   * @return stakerProxy The address of the stakerProxy contract.
   */
  function stakerProxyAddresses(
    uint256 _stakerId
  ) external view returns (address stakerProxy);

  /**
   * @dev Sets the StrategyManager contract address.
   * @param _strategyManager The address of the StrategyManager contract.
   */
  function setStrategyManager(address _strategyManager) external;

  /**
   * @dev Sets the admin signer address.
   * @param _adminSigner The address of the admin signer.
   */
  function setAdminSigner(address _adminSigner) external;

  /**
   * @dev Sets the DelayedWithdrawalRouter contract address.
   * @param _delayedWithdrawalRouter The address of the DelayedWithdrawalRouter contract.
   */
  function setDelayedWithdrawalRouter(
    address _delayedWithdrawalRouter
  ) external;

  /**
   * @dev Sets the DelegationManager contract address.
   * @param _delegationManager The address of the DelegationManager contract.
   */
  function setDelegationManager(address _delegationManager) external;

  /**
   * @dev Allows a Swell Admin to set the Eigen Layer Strategy for a given token.
   * @param _token The address of the token.
   * @param _strategy The address of the strategy.
   */
  function setEigenLayerStrategy(address _token, address _strategy) external;

  /**
   * @dev Stake on the EigenLayer network.
   * @param _stakerIds An array of stakerProxy Ids.
   * @param _pubKeys An array of public keys for operators registered on the Swell Network.
   * @param _depositDataRoot The deposit data root.
   */
  function stakeOnEigenLayer(
    uint256[] calldata _stakerIds,
    bytes[] calldata _pubKeys,
    bytes32 _depositDataRoot
  ) external;

  /**
   * @dev Allows a Swell Admin to Deposit liquid staking tokens into an Eigen Layer Strategy.
   * @param _stakerId The Id if the stakerProxy contract to deposit on behalf of.
   * @param _amount The amount of LST's to deposit.
   * @param _token The LST token address.
   */
  function depositIntoEigenLayerStrategy(
    uint256 _stakerId,
    uint256 _amount,
    address _token
  ) external;

  /**
   * @dev Delegates the staker's Eigen Layer shares to the specified operator using the provided signatures and expiry times.
   * @param _stakerId The Id of the stakerProxy contract.
   * @param _operator The address of the operator.
   * @param _stakerSignatureAndExpiry A struct containing the staker's signature and expiry time.
   * @param _approverSignatureAndExpiry A struct containing the approver's signature and expiry time.
   * @param _approverSalt A unique salt value used for the approver's signature.
   */
  function delegateToWithSignature(
    uint256 _stakerId,
    address _operator,
    IDelegationManager.SignatureWithExpiry calldata _stakerSignatureAndExpiry,
    IDelegationManager.SignatureWithExpiry calldata _approverSignatureAndExpiry,
    bytes32 _approverSalt
  ) external;

  /**
   * @dev Batch delegates multiple stakers to multiple operators using their signatures and expiry times.
   * @param stakerIds An array of stakerProxy Ids.
   * @param operatorArray An array of operator addresses.
   * @param stakerSignatureAndExpiryArray An array of SignatureWithExpiry structs containing staker signatures and expiry times.
   * @param approverSignatureAndExpiryArray An array of SignatureWithExpiry structs containing approver signatures and expiry times.
   * @param approverSaltArray An array of salts used for the approver signatures.
   */
  function batchDelegateToWithSignature(
    uint256[] calldata stakerIds,
    address[] calldata operatorArray,
    IDelegationManager.SignatureWithExpiry[]
      calldata stakerSignatureAndExpiryArray,
    IDelegationManager.SignatureWithExpiry[]
      calldata approverSignatureAndExpiryArray,
    bytes32[] calldata approverSaltArray
  ) external;

  /**
   * @dev Manually unassigns a staker from an operator.
   * @dev This is a cleanup function which requires that the staker is undelegated on EigenLayer. This can occur when the operator or their delegation approver forces one of their delegated stakers to undelegate.
   * @param _stakerId The ID of the staker to unassign.
   * @param _operator The address of the operator.
   */
  function unassignStakerFromOperator(
    uint256 _stakerId,
    address _operator
  ) external;

  /**
   * @dev Manually assigns a staker to an operator.
   * @dev This is a cleanup function which requires that the staker is delegated on EigenLayer. This can occur when a staker is delegated to an operator directly via DelegationManager.
   * @param stakerId The ID of the staker to assign.
   * @param operator The address of the operator.
   */
  function assignStakerToOperator(uint256 stakerId, address operator) external;

  /**
   * @dev Queues multiple withdrawals for a staker proxy.
   * @param _stakerProxyId The ID of the staker proxy.
   * @param _queuedWithdrawalParams An array of QueuedWithdrawalParams struct containing withdrawal details.
   * @return An array of bytes32 representing the withdrawal roots.
   */
  function queueWithdrawals(
    uint256 _stakerProxyId,
    IDelegationManager.QueuedWithdrawalParams[] calldata _queuedWithdrawalParams
  ) external returns (bytes32[] memory);

  /**
   * @dev Complete a queued withdrawal via a StakerProxy
   * @param _stakerProxyId The ID of the staker proxy.
   * @param _withdrawal The Withdrawal to complete.
   * @param _tokens Array in which the i-th entry specifies the `token` input to the 'withdraw' function of the i-th Strategy in the `withdrawal.strategies` array.
   * This input can be provided with zero length if `receiveAsTokens` is set to 'false' (since in that case, this input will be unused)
   * @param _middlewareTimesIndex is the index in the operator that the staker who triggered the withdrawal was delegated to's middleware times array
   * @param _receiveAsTokens If true, the shares specified in the withdrawal will be withdrawn from the specified strategies themselves
   * and sent to the caller, through calls to `withdrawal.strategies[i].withdraw`. If false, then the shares in the specified strategies
   * will simply be transferred to the caller directly.
   * @dev middlewareTimesIndex should be calculated off chain before calling this function by finding the first index that satisfies `slasher.canWithdraw`
   * @dev beaconChainETHStrategy shares are non-transferrable, so if `receiveAsTokens = false` and `withdrawal.withdrawer != withdrawal.staker`, note that
   * any beaconChainETHStrategy shares in the `withdrawal` will be _returned to the staker_, rather than transferred to the withdrawer, unlike shares in
   * any other strategies, which will be transferred to the withdrawer.
   */
  function completeQueuedWithdrawal(
    uint256 _stakerProxyId,
    IDelegationManager.Withdrawal calldata _withdrawal,
    IERC20[] calldata _tokens,
    uint256 _middlewareTimesIndex,
    bool _receiveAsTokens
  ) external;

  /**
   * @dev This function is used to claim partial withdrawals on behalf of the recipient after the withdrawal delay has passed.
   * @param _recipient The address of the recipient to claim the withdrawals for.
   * @param _maxNumberOfWithdrawalsToClaim The maximum number of withdrawals to claim.
   */
  function claimDelayedWithdrawals(
    address _recipient,
    uint256 _maxNumberOfWithdrawalsToClaim
  ) external;

  /**
   * @dev  For a staker proxy: Verify the withdrawal credentials of validator(s) owned by the pod owner are pointing to the eigenpod.
   * @param _stakerProxyId is the ID of the staker proxy contract
   * @param _oracleTimestamp is the Beacon Chain timestamp whose state root the `proof` will be proven against.
   * @param _stateRootProof proves a `beaconStateRoot` against a block root fetched from the oracle
   * @param _validatorIndices is the list of indices of the validators being proven, refer to consensus specs
   * @param _validatorFieldsProofs proofs against the `beaconStateRoot` for each validator in `validatorFields`
   * @param _validatorFields are the fields of the "Validator Container", refer to consensus specs
   * for details: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#validator
   */
  function verifyPodWithdrawalCredentials(
    uint256 _stakerProxyId,
    uint64 _oracleTimestamp,
    BeaconChainProofs.StateRootProof calldata _stateRootProof,
    uint40[] calldata _validatorIndices,
    bytes[] calldata _validatorFieldsProofs,
    bytes32[][] calldata _validatorFields
  ) external;

  /**
   * @dev Verifies and processes withdrawals for a staker proxy.
   * @param _stakerProxyId The ID of the staker proxy.
   * @param _oracleTimestamp The timestamp provided by the oracle.
   * @param _stateRootProof The proof of the state root.
   * @param _withdrawalProofs An array of withdrawal proofs.
   * @param _validatorFieldsProofs An array of validator fields proofs.
   * @param _validatorFields An array of validator fields.
   * @param _withdrawalFields An array of withdrawal fields.
   */
  function verifyAndProcessWithdrawals(
    uint256 _stakerProxyId,
    uint64 _oracleTimestamp,
    BeaconChainProofs.StateRootProof calldata _stateRootProof,
    BeaconChainProofs.WithdrawalProof[] calldata _withdrawalProofs,
    bytes[] calldata _validatorFieldsProofs,
    bytes32[][] calldata _validatorFields,
    bytes32[][] calldata _withdrawalFields
  ) external;

  /**
   * @dev Undelegates a staker from an operator.
   * @param _stakerId The ID of the staker to undelegate.
   */
  function undelegateStakerFromOperator(uint256 _stakerId) external;

  /**
   * @dev Batch undelegates multiple stakers from their associated operators.
   * @param _stakerIdArray An array of staker IDs to undelegate.
   */
  function batchUndelegateStakerFromOperator(
    uint256[] calldata _stakerIdArray
  ) external;

  /**
   * @dev Batch withdraws ERC20 tokens from a specific staker's pod.
   * @param _stakeId The ID of the stake.
   * @param _tokens An array of ERC20 tokens to withdraw.
   * @param _amounts An array of amounts to withdraw for each token.
   * @param _recipient The address to receive the withdrawn tokens.
   */
  function batchWithdrawERC20(
    uint256 _stakeId,
    IERC20[] memory _tokens,
    uint256[] memory _amounts,
    address _recipient
  ) external;

  /**
   * @dev Allows a Swell Admin to create a batch of stakerProxy contracts with associated Eigen Pods.
   * @param _batchSize The amount of stakerProxy contracts to create.
   */
  function createStakerAndPod(uint256 _batchSize) external;

  /**
   * @dev Registers the implementation of the StakerProxy contract.
   * @param _beacon The address of the beacon contract.
   */
  function registerStakerProxyImplementation(address _beacon) external;

  /**
   * @dev Upgrades the StakerProxy contract to a new implementation.
   * @param _newImplementation The address of the new implementation contract.
   */
  function upgradeStakerProxy(address _newImplementation) external;
}

File 40 of 62 : INodeOperatorRegistry.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.16;

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

import {IAccessControlManager} from "../interfaces/IAccessControlManager.sol";

import {IPoRAddresses} from "../vendors/IPoRAddresses.sol";

/**
 * @title INodeOperatorRegistry
 * @author https://github.com/max-taylor
 * @notice Interface for the Node Operator Registry contract.
 */
interface INodeOperatorRegistry is IPoRAddresses {
  /**
   * @dev  Struct containing the required details to setup a validator on the beacon chain
   * @param pubKey Public key of the validator
   * @param signature The signature of the validator
   */
  struct ValidatorDetails {
    bytes pubKey;
    bytes signature;
  }

  /**
   * @dev  Struct containing operator details
   * @param enabled Flag indicating if the operator is enabled or disabled
   * @param rewardAddress Address to sending repricing rewards to
   * @param controllingAddress The address that can control the operator account
   * @param name The name of the operator
   * @param activeValidators The amount of active validators for the operator
   */
  struct Operator {
    bool enabled;
    address rewardAddress;
    address controllingAddress;
    string name;
    uint128 activeValidators;
  }

  // ***** Events *****
  /**
   * @dev  Emitted when a new operator is added.
   * @param operatorAddress  The address of the newly added operator.
   * @param rewardAddress    The address associated with the reward for the operator.
   */
  event OperatorAdded(address operatorAddress, address rewardAddress);

  /**
   * @dev  Emitted when an operator is enabled.
   * @param operator  The address of the operator that was enabled.
   */
  event OperatorEnabled(address indexed operator);

  /**
   * @dev  Emitted when an operator is disabled.
   * @param operator  The address of the operator that was disabled.
   */
  event OperatorDisabled(address indexed operator);

  /**
   * @dev  Emitted when the validator details for an operator are added.
   * @param operator  The address of the operator for which the validator details were added.
   * @param pubKeys   An array of `ValidatorDetails` for the operator.
   */
  event OperatorAddedValidatorDetails(
    address indexed operator,
    ValidatorDetails[] pubKeys
  );

  /**
   * @dev  Emitted when active public keys are deleted.
   * @param pubKeys  An array of public keys that were deleted.
   */
  event ActivePubKeysDeleted(bytes[] pubKeys);

  /**
   * @dev  Emitted when pending public keys are deleted.
   * @param pubKeys  An array of public keys that were deleted.
   */
  event PendingPubKeysDeleted(bytes[] pubKeys);

  /**
   * @dev  Emitted when public keys are used for validator setup.
   * @param pubKeys  An array of public keys that were used for validator setup.
   */
  event PubKeysUsedForValidatorSetup(bytes[] pubKeys);

  /**
   * @dev  Emitted when the controlling address for an operator is updated.
   * @param oldControllingAddress  The old controlling address for the operator.
   * @param newControllingAddress  The new controlling address for the operator.
   */
  event OperatorControllingAddressUpdated(
    address indexed oldControllingAddress,
    address indexed newControllingAddress
  );

  /**
   * @dev  Emitted when the reward address for an operator is updated.
   * @param operator  The address of the operator for which the reward address was updated.
   * @param newRewardAddress  The new reward address for the operator.
   * @param oldRewardAddress  The old reward address for the operator.
   */
  event OperatorRewardAddressUpdated(
    address indexed operator,
    address indexed newRewardAddress,
    address indexed oldRewardAddress
  );

  /**
   * @dev  Emitted when the name for an operator is updated.
   * @param operator  The address of the operator for which the name was updated.
   * @param newName  The new name for the operator.
   * @param oldName  The old name for the operator.
   */
  event OperatorNameUpdated(
    address indexed operator,
    string newName,
    string oldName
  );

  // ***** Errors *****
  /**
   * @dev Thrown when an operator is not found.
   * @param operator  The address of the operator that was not found.
   */
  error NoOperatorFound(address operator);

  /**
   * @dev Thrown when an operator already exists.
   * @param operator The address of the operator that already exists.
   */
  error OperatorAlreadyExists(address operator);

  /**
   * @dev Thrown when an operator is already enabled.
   */
  error OperatorAlreadyEnabled();

  /**
   * @dev Thrown when an operator is already disabled.
   */
  error OperatorAlreadyDisabled();

  /**
   * @dev Thrown when an array length of zero is invalid.
   */
  error InvalidArrayLengthOfZero();

  /**
   * @dev Thrown when an operator is adding new validator details and this causes the total amount of operator's validator details to exceed uint128
   */
  error AmountOfValidatorDetailsExceedsLimit();

  /**
   * @dev Thrown during setup of new validators, when comparing the next operator's public key to the provided public key they should match. This ensures consistency in the tracking of the active and pending validator details.
   * @param foundPubKey The operator's next available public key
   * @param providedPubKey The public key that was passed in as an argument
   */
  error NextOperatorPubKeyMismatch(bytes foundPubKey, bytes providedPubKey);

  /**
   * @dev Thrown during the setup of new validators and when the operator that has no pending details left to use
   */
  error OperatorOutOfPendingKeys();

  /**
   * @dev Thrown when the given pubKey hasn't been added to the registry and cannot be found
   * @param pubKey  The public key that was not found.
   */
  error NoPubKeyFound(bytes pubKey);

  /**
   * @dev Thrown when an operator tries to use the node operator registry whilst they are disabled
   */
  error CannotUseDisabledOperator();

  /**
   * @dev Thrown when a duplicate public key is added.
   * @param existingKey  The public key that already exists.
   */
  error CannotAddDuplicatePubKey(bytes existingKey);

  /**
   * @dev Thrown when the given pubKey doesn't exist in the pending validator details sets
   * @param pubKey  The missing pubKey
   */
  error MissingPendingValidatorDetails(bytes pubKey);

  /**
   * @dev Thrown when the pubKey doesn't exist in the active validator details set
   * @param pubKey  The missing pubKey
   */
  error MissingActiveValidatorDetails(bytes pubKey);

  /**
   * @dev Throw when the msg.sender isn't the Deposit Manager contract
   */
  error InvalidPubKeySetupCaller();

  /**
   * @dev Thrown when an operator is trying to add validator details and a provided pubKey isn't the correct length
   */
  error InvalidPubKeyLength();

  /**
   * @dev Thrown when an operator is trying to add validator details and a provided signature isn't the correct length
   */
  error InvalidSignatureLength();

  /**
   * @dev Thrown when calling the delete active validators method from an address that doens't have the PLATFORM_ADMIN or DELETE_ACTIVE_VALIDATORS role
   */
  error InvalidCallerToDeleteActiveValidators();

  /**
   * @dev Thrown when trying to update the controlling address for an operator and the new controlling address is the same as the current controlling address
   */
  error CannotSetOperatorControllingAddressToSameAddress();

  /**
   * @dev Thrown when trying to update the controlling address for an operator and the new controlling address is already assigned to another operator
   */
  error CannotUpdateOperatorControllingAddressToAlreadyAssignedAddress();

  // ************************************
  // ***** External  methods ******

  /**
   * @dev This method withdraws contract's _token balance to a PLATFORM_ADMIN
   * @param _token The ERC20 token to withdraw from the contract
   */
  function withdrawERC20(IERC20 _token) external;

  /**
   * @dev  Gets the next available validator details, ordered by operators with the least amount of active validators. There may be less available validators then the provided _numNewValidators amount, in that case the function will return an array of length equal to _numNewValidators but all indexes after the second return value; foundValidators, will be 0x0 values
   * @param _numNewValidators The number of new validators to get details for.
   * @return An array of ValidatorDetails and the length of the array of non-zero validator details
   * @notice This method tries to return enough validator details to equal the provided _numNewValidators, but if there aren't enough validator details to find, it will simply return what it found, and the caller will need to check for empty values.
   */
  function getNextValidatorDetails(
    uint256 _numNewValidators
  ) external view returns (ValidatorDetails[] memory, uint256 foundValidators);

  /**
   * @dev  Allows the DepositManager to move provided _pubKeys from the pending validator details arrays into the active validator details array. It also returns the validator details, so that the DepositManager can pass the signature along to the ETH2 deposit contract.
   * @param _pubKeys Array of public keys to use for validator setup.
   * @return validatorDetails The associated validator details for the given public keys
   * @notice This method will be called when the DepositManager is setting up new validators.
   */
  function usePubKeysForValidatorSetup(
    bytes[] calldata _pubKeys
  ) external returns (ValidatorDetails[] memory validatorDetails);

  // ** Operator management methods **

  /**
   * @dev  Adds new validator details to the registry.
  /**
   * @dev  Callable by node operator's to add their validator details to the setup queue
   * @param _validatorDetails Array of ValidatorDetails to add.
  */
  function addNewValidatorDetails(
    ValidatorDetails[] calldata _validatorDetails
  ) external;

  // ** PLATFORM_ADMIN management methods **

  /**
   * @dev  Adds a new operator to the registry.
   * @param _name Name of the operator.
   * @param _operatorAddress Address of the operator.
   * @param _rewardAddress Address of the reward recipient for this operator.
   * @notice Throws if an operator already exists with the given _operatorAddress
   */
  function addOperator(
    string calldata _name,
    address _operatorAddress,
    address _rewardAddress
  ) external;

  /**
   * @dev  Enables an operator in the registry.
   * @param _operatorAddress Address of the operator to enable.
   * @notice Throws NoOperatorFound if the operator address is not found in the registry
   */
  function enableOperator(address _operatorAddress) external;

  /**
   * @dev  Disables an operator in the registry.
   * @param _operatorAddress Address of the operator to disable.
   * @notice Throws NoOperatorFound if the operator address is not found in the registry
   */
  function disableOperator(address _operatorAddress) external;

  /**
   * @dev  Updates the controlling address of an operator in the registry.
   * @param _operatorAddress Current address of the operator.
   * @param _newOperatorAddress New address of the operator.
   * @notice Throws NoOperatorFound if the operator address is not found in the registry
   */
  function updateOperatorControllingAddress(
    address _operatorAddress,
    address _newOperatorAddress
  ) external;

  /**
   * @dev  Updates the reward address of an operator in the registry.
   * @param _operatorAddress Address of the operator to update.
   * @param _newRewardAddress New reward address for the operator.
   * @notice Throws NoOperatorFound if the operator address is not found in the registry
   */
  function updateOperatorRewardAddress(
    address _operatorAddress,
    address _newRewardAddress
  ) external;

  /**
   * @dev  Updates the name of an operator in the registry
   * @param _operatorAddress The address of the operator to update
   * @param _name The new name for the operator
   * @notice Throws NoOperatorFound if the operator address is not found in the registry
   */
  function updateOperatorName(
    address _operatorAddress,
    string calldata _name
  ) external;

  /**
   * @dev  Allows the PLATFORM_ADMIN to delete validators that are pending. This is likely to be called via an admin if a public key fails the front-running checks
   * @notice Throws InvalidArrayLengthOfZero if the length of _pubKeys is 0
   * @notice Throws NoPubKeyFound if any of the provided pubKeys is not found in the pending validators set
   * @param _pubKeys The public keys of the pending validators to delete
   */
  function deletePendingValidators(bytes[] calldata _pubKeys) external;

  /**
   * @dev  Allows the PLATFORM_ADMIN to delete validator public keys that have been used to setup a validator and that validator has now exited
   * @notice Throws NoPubKeyFound if any of the provided pubKeys is not found in the active validators set
   * @notice Throws InvalidArrayLengthOfZero if the length of _pubKeys is 0
   * @param _pubKeys The public keys of the active validators to delete
   */
  function deleteActiveValidators(bytes[] calldata _pubKeys) external;

  /**
   * @dev  Returns the address of the AccessControlManager contract
   */
  function AccessControlManager() external returns (IAccessControlManager);

  /**
   * @dev  Returns the operator details for a given operator address
   * @notice Throws NoOperatorFound if the operator address is not found in the registry
   * @param _operatorAddress The address of the operator to retrieve
   * @return operator The operator details, including name, reward address, and enabled status
   * @return totalValidatorDetails The total amount of validator details for an operator
   * @return operatorId The operator's Id
   */
  function getOperator(
    address _operatorAddress
  )
    external
    view
    returns (
      Operator memory operator,
      uint128 totalValidatorDetails,
      uint128 operatorId
    );

  /**
   * @dev  Returns the pending validator details for a given operator address
   * @notice Throws NoOperatorFound if the operator address is not found in the registry
   * @param _operatorAddress The address of the operator to retrieve pending validator details for
   * @return validatorDetails The pending validator details for the given operator
   */
  function getOperatorsPendingValidatorDetails(
    address _operatorAddress
  ) external returns (ValidatorDetails[] memory);

  /**
   * @dev  Returns the active validator details for a given operator address
   * @notice Throws NoOperatorFound if the operator address is not found in the registry
   * @param _operatorAddress The address of the operator to retrieve active validator details for
   * @return validatorDetails The active validator details for the given operator
   */
  function getOperatorsActiveValidatorDetails(
    address _operatorAddress
  ) external returns (ValidatorDetails[] memory validatorDetails);

  /**
   * @dev  Returns the reward details for a given operator Id, this method is used in the rswETH contract when paying rswETH rewards
   * @param _operatorId The operator Id to get the reward details for
   * @return rewardAddress The reward address of the operator
   * @return activeValidators The amount of active validators for the operator
   */
  function getRewardDetailsForOperatorId(
    uint128 _operatorId
  ) external returns (address rewardAddress, uint128 activeValidators);

  /**
   * @dev  Returns the number of operators in the registry
   */
  function numOperators() external returns (uint128);

  /**
   * @dev  Returns the amount of pending validator keys in the registry
   */
  function numPendingValidators() external returns (uint256);

  /**
   * @dev  Returns the operator ID for a given operator address
   * @notice Throws NoOperatorFound if the operator address is not found in the registry
   * @param _operator The address of the operator to retrieve the operator ID for
   * @return _operatorId The operator ID for the given operator
   */
  function getOperatorIdForAddress(
    address _operator
  ) external returns (uint128 _operatorId);

  /**
   * @dev Returns the `operatorId` associated with the given `pubKey`.
   * @param pubKey  The public key to lookup the `operatorId` for.
   * @notice Returns 0 if no operatorId controls the pubKey
   */
  function getOperatorIdForPubKey(
    bytes calldata pubKey
  ) external returns (uint128);
}

File 41 of 62 : IRepricingOracle.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.16;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {UpgradeableRepriceSnapshot} from "../libraries/Repricing.sol";
import {AggregatorV3Interface} from "../vendors/AggregatorV3Interface.sol";
import {IrswETH} from "../interfaces/IrswETH.sol";

interface IRepricingOracle {
  // ***** Errors ******

  /**
   * @dev Error thrown when the blockOfLastSnapshot specified in the submitted RepriceSnapshot struct does not match the on-chain value.
   * @param blockOfLastSnapshotSupplied The blockOfLastSnapshot specified in the submitted RepriceSnapshot struct.
   * @param blockOfLastSnapshotOnChain The on-chain value for blockOfLastSnapshot in the lastRepriceSnapshot.
   */
  error RepriceBlockOfLastSnapshotMismatch(
    uint256 blockOfLastSnapshotSupplied,
    uint256 blockOfLastSnapshotOnChain
  );

  /**
   * @dev Error thrown when reprice blockAtSnapshot did not increase since the last snapshot.
   */
  error RepriceBlockAtSnapshotDidNotIncrease();

  /**
   * @dev Error thrown when the consensus layer slot did not increase since the last repricing snapshot.
   */
  error RepriceSlotDidNotIncrease();

  /**
   * @dev Error thrown when timestamp did not increase since the last reprice snapshot.
   */
  error RepriceTimestampDidNotIncrease();

  /**
   * @dev Error thrown when reprice blockAtSnapshot is higher than current block on-chain.
   * @param snapshotBlockNumber The block number at the time of the snapshot.
   * @param currentBlockNumber The current block number on-chain.
   */
  error RepriceBlockAtSnapshotTooHigh(
    uint256 snapshotBlockNumber,
    uint256 currentBlockNumber
  );

  /**
   * @dev Error thrown when the block number supplied in a repricing report is older than the current block by some configurable threshold.
   * @param snapshotStalenessInBlocks The number of blocks by which the snapshot is stale.
   * @param maximumRepriceBlockAtSnapshotStaleness The threshold number of blocks by which the snapshot is allowed to be stale.
   */
  error RepriceBlockAtSnapshotIsStale(
    uint256 snapshotStalenessInBlocks,
    uint256 maximumRepriceBlockAtSnapshotStaleness
  );

  /**
   * @dev Error thrown when a repricing snapshot's v3 validator reserves differs from the value reported by the external PoR oracle by more than the allowed threshold.
   * @param v3ReservesExternalPoRDiff The difference between the repricing snapshot's v3 validator reserves and externally reported v3 validator reserves.
   * @param maximumV3ReservesExternalPoRDiff The maximum allowed difference between the repricing snapshot's v3 validator reserves and externally reported v3 validator reserves.
   */
  error RepriceV3ReservesExternalPoRDifferentialTooHigh(
    uint256 v3ReservesExternalPoRDiff,
    uint256 maximumV3ReservesExternalPoRDiff
  );

  /**
   * @dev Error thrown when round data is read from the oracle and the updatedAt time is greater than the block.timestamp + maximumRoundDataStalenessTime
   * @param latestRoundDataTime The round data time
   * @param secondsSinceExpiry The number of seconds since the round data expired
   */
  error RoundDataIsStale(
    uint256 latestRoundDataTime,
    uint256 secondsSinceExpiry
  );

  /**
   * @dev Error thrown when calling process withdrawals and the totalETHExited provided in the snapshot doesn't match rswEXIT.totalETHExited after processWithdrawals is called
   */
  error ProcessWithdrawalsTotalETHExitedMismatch();

  /**
   * @dev Error thrown after calling process withdrawals and the exitingETH provided in the snapshot is less than rswEXIT.exitingETH
   */
  error ProcessWithdrawalsExitingETHMustMonotonicallyIncrease();

  /**
   * @dev Error thrown when the reference price computed from on-chain values differs from the new price resulting from the snapshot submission by more than the allowed threshold.
   * @param referencePriceDiff The difference between the new price and the reference price
   * @param maximumReferencePriceDiffPercentage The maximum allowed difference between the new price and the on-chain reference price
   */
  error ReferencePriceDiffTooHigh(
    uint256 referencePriceDiff,
    uint256 maximumReferencePriceDiffPercentage
  );

  /**
   * @dev Error thrown when attempting to compute the reference price with a rswETH supply of zero.
   */
  error CannotComputeReferencePriceWithZeroRswETHSupply();

  /**
   * @dev Error thrown when the timestamp supplied in a repricing report is exceeds the current block's timestamp.
   * @param snapshotTimestamp The timestamp supplied in the repricing report.
   * @param blockTimestamp The current block's timestamp.
   */
  error RepriceTimestampTooHigh(
    uint256 snapshotTimestamp,
    uint256 blockTimestamp
  );

  // ***** Events ******

  /**
   * @dev Event emitted on a successful call to update the address of the external Proof of Reserves (PoR) contract used for verifying v3 validators' reserves during repricing.
   * @param oldAddress The previous address of the PoR contract.
   * @param newAddress The new updated address of the PoR contract.
   */
  event ExternalV3ReservesPoROracleAddressUpdated(
    address oldAddress,
    address newAddress
  );

  /**
   * @dev Event emitted on a successful call to setMaximumRepriceBlockAtSnapshotStaleness
   * @param _oldMaximumRepriceBlockAtSnapshotStaleness The old staleness threshold, expressed in terms of number of blocks
   * @param _newMaximumRepriceBlockAtSnapshotStaleness The new staleness threshold, expressed in terms of number of blocks
   */
  event MaximumRepriceBlockAtSnapshotStalenessUpdated(
    uint256 _oldMaximumRepriceBlockAtSnapshotStaleness,
    uint256 _newMaximumRepriceBlockAtSnapshotStaleness
  );

  /**
   * @dev Event emitted on a successful call to update the maximum allowed percentage difference between a repricing snapshot's v3 reserves and the externally reported v3 reserves.
   * @param _oldMaximumRepriceV3ReservesExternalPoRDiffPercentage The previous maximum percentage difference.
   * @param _newMaximumRepriceV3ReservesExternalPoRDiffPercentage The new updated maximum percentage difference.
   */
  event MaximumRepriceV3ReservesExternalPoRDiffPercentageUpdated(
    uint256 _oldMaximumRepriceV3ReservesExternalPoRDiffPercentage,
    uint256 _newMaximumRepriceV3ReservesExternalPoRDiffPercentage
  );

  /**
   * @dev Event emitted when a reprice snapshot submitted to initiate the repricing process.
   * @param blockNumber The block number at the time of the snapshot.
   * @param slot The slot on the beacon chain associated with the snapshot block.
   * @param reportTimestamp A timestamp provided by the execution bot, indicating when it started calculations.
   * @param totalETHDeposited The total ETH deposited at the time of the snapshot.
   * @param rswETHTotalSupply The total rswETH supply at the time of the snapshot.
   */
  event SnapshotSubmitted(
    uint256 indexed blockNumber,
    uint256 slot,
    uint256 reportTimestamp,
    uint256 totalETHDeposited,
    uint256 rswETHTotalSupply
  );

  /**
   * @dev Event emitted when a reprice snapshot submitted to initiate the repricing process.
   * @param blockNumber The block number at the time of the snapshot.
   * @param slot The slot on the beacon chain associated with the snapshot block.
   * @param reportTimestamp A timestamp provided by the execution bot, indicating when it started calculations.
   * @param totalETHDeposited The total ETH deposited at the time of the snapshot.
   * @param rswETHTotalSupply The total rswETH supply at the time of the snapshot.
   * @param totalETHExited The total ETH exited via processed withdrawal requests at the time of the snapshot.
   */
  event SnapshotSubmittedV2(
    uint256 indexed blockNumber,
    uint256 slot,
    uint256 reportTimestamp,
    uint256 totalETHDeposited,
    uint256 rswETHTotalSupply,
    uint256 totalETHExited
  );

  /**
   * @dev Event emitted when reserves are recorded following a repricing snapshot submission.
   * @param blockAtSnapshot The block number at the time of the snapshot.
   * @param elBalance ETH in Swell controlled contracts on the execution layer at the time of the snapshot, which has not yet been deposited on the beacon chain.
   * @param clV3Balance The total sum of ETH held by v3 validators on the consensus layer at the moment of the snapshot's slot.
   * @param clV2Balance The total sum of ETH held by v2 validators on the consensus layer at the moment of the snapshot's slot.
   * @param transitioningBalance ETH Reserves held by validators transitioning to the beacon chain at the time of the snapshot.
   * @param newETHReserves Total ETH reserves at the time of snapshot.
   */
  event ReservesRecorded(
    uint256 indexed blockAtSnapshot,
    uint256 elBalance,
    uint256 clV3Balance,
    uint256 clV2Balance,
    uint256 transitioningBalance,
    uint256 newETHReserves
  );

  /**
   * @dev Event emitted when reserves are recorded following a repricing snapshot submission.
   * @param blockAtSnapshot The block number at the time of the snapshot.
   * @param elBalance ETH in Swell controlled contracts on the execution layer at the time of the snapshot, which has not yet been deposited on the beacon chain. Does not include swEXIT balance.
   * @param clV3Balance The total sum of ETH held by v3 validators on the consensus layer at the moment of the snapshot's slot.
   * @param clV2Balance The total sum of ETH held by v2 validators on the consensus layer at the moment of the snapshot's slot.
   * @param transitioningBalance ETH Reserves held by validators transitioning to the beacon chain at the time of the snapshot.
   * @param newETHReserves Reserve assets minus exiting ETH.
   * @param reserveAssets The sum of all balances in the snapshot.
   * @param exitingETH The current amount of exiting ETH, which is has not yet been processed for withdrawals. This value estimates the amount of ETH that will exit when withdrawals are processed.
   */
  event ReservesRecordedV2(
    uint256 indexed blockAtSnapshot,
    uint256 elBalance,
    uint256 clV3Balance,
    uint256 clV2Balance,
    uint256 transitioningBalance,
    uint256 newETHReserves,
    uint256 reserveAssets,
    uint256 exitingETH
  );

  /**
   * @dev Event emitted when rewards are calculated during reprice.
   * @param blockAtSnapshot The block number at the time of the repricing snapshot.
   * @param blockOfLastSnapshot The block number of the last repricing snapshot. In conjunction with blockAtSnapshot, this describes the period over which rewards were calculated.
   * @param reservesChange Change in ETH reserves since the last repricing.
   * @param ethDepositsChange Change in total ETH deposited by stakers since the last repricing.
   * @param rewardsPayableForFees The amount of rewards to be distributed among rswETH holders, node operators, and the Swell Treasury, resulting from changes to total reserves and total ETH deposited.
   */
  event RewardsCalculated(
    uint256 indexed blockAtSnapshot,
    uint256 blockOfLastSnapshot,
    int256 reservesChange,
    uint256 ethDepositsChange,
    uint256 rewardsPayableForFees
  );

  /**
   * @dev Event emitted when rewards are calculated during reprice.
   * @param blockAtSnapshot The block number at the time of the repricing snapshot.
   * @param blockOfLastSnapshot The block number of the last repricing snapshot. In conjunction with blockAtSnapshot, this describes the period over which rewards were calculated.
   * @param reserveAssetsChange Change in reserve assets since the last repricing.
   * @param ethDepositsChange Change in total ETH deposited by stakers since the last repricing.
   * @param rewardsPayableForFees The amount of rewards to be distributed among rswETH holders, node operators, and the Swell Treasury, resulting from changes to total reserves and total ETH deposited.
   * @param ethExitedChange Change in the total amount of ETH that has exited the protocol, due to processed withdrawals.
   */
  event RewardsCalculatedV2(
    uint256 indexed blockAtSnapshot,
    uint256 blockOfLastSnapshot,
    int256 reserveAssetsChange,
    uint256 ethDepositsChange,
    uint256 rewardsPayableForFees,
    uint256 ethExitedChange
  );

  /**
   * @dev Event emitted when the maximum round data staleness time is updated by the PLATFORM_ADMIN
   * @param _oldMaximumRoundDataStalenessTime The old maximum staleness time for chainlink data
   * @param _newMaximumRoundDataStalenessTime The new maximum staleness time for chainlink data
   */
  event MaximumRoundDataStalenessTimeUpdated(
    uint256 _oldMaximumRoundDataStalenessTime,
    uint256 _newMaximumRoundDataStalenessTime
  );

  /**
   * @dev Event emitted when the maximum reference price difference percentage is updated by the PLATFORM_ADMIN
   * @param _oldMaximumReferencePriceDiffPercentage The old maximum reference price difference percentage
   * @param _newMaximumReferencePriceDiffPercentage The new maximum reference price difference percentage
   */
  event MaximumReferencePriceDiffPercentageUpdated(
    uint256 _oldMaximumReferencePriceDiffPercentage,
    uint256 _newMaximumReferencePriceDiffPercentage
  );

  // ************************************
  // ***** External Methods ******

  /**
   * @dev This method withdraws contract's _token balance to a platform admin
   * @param _token The ERC20 token to withdraw from the contract
   */
  function withdrawERC20(IERC20 _token) external;

  /**
   * @dev Returns the maximum number of blocks that can elapse between block.number and blockAtSnapshot before data is considered stale.
   * @return The maximum number of blocks that can elapse between block.number and blockAtSnapshot.
   */
  function maximumRepriceBlockAtSnapshotStaleness()
    external
    view
    returns (uint256);

  /**
   * @dev Returns the maximum length of time that can elapse between the last round data update and the current block timestamp before the chainlink data is considered stale, in which case the transaction will revert
   * @return The maximum staleness time for chainlink data
   */
  function maximumRoundDataStalenessTime() external view returns (uint256);

  /**
   * @dev Returns the maximum percentage difference allowed between a repricing snapshot's v3 validator reserves and the externally reported v3 reserves.
   * @return The maximum percentage difference allowed between the repricing snapshot's reported V3 validator reserves and the externally reported v3 reserves.
   */
  function maximumRepriceV3ReservesExternalPoRDiffPercentage()
    external
    view
    returns (uint256);

  /**
   * @dev Returns the maximum percentage difference allowed between the new price and the on-chain reference price
   * @return The maximum percentage difference allowed between the new price and the on-chain reference price
   */
  function maximumReferencePriceDiffPercentage()
    external
    view
    returns (uint256);

  /**
   * @dev The repricing snapshot that was most recently used to execute a reprice of the rswETH token.
   * @return The `RepriceSnapshot` struct data that was most recently used to execute a reprice of the rswETH token.
   */
  function lastRepriceSnapshot()
    external
    view
    returns (UpgradeableRepriceSnapshot memory);

  /**
   * @dev Returns the address of the external Proof of Reserves (PoR) contract used for verifying v3 validator reserves during repricing.
   * @return The address of the PoR contract.
   */
  function ExternalV3ReservesPoROracle()
    external
    view
    returns (AggregatorV3Interface);

  /**
   * @dev Asserts the validity of a repricing snapshot. This function will revert upon receiving a snapshot that would be rejected by submitSnapshot.
   * @param _snapshot The reprice snapshot struct to be validated
   */
  function assertRepricingSnapshotValidity(
    UpgradeableRepriceSnapshot calldata _snapshot
  ) external view;

  /**
   * @dev The entrypoint for trusted execution bots to submit RepricingSnapshot data. The data is ultimately used to perform a repricing of the rswETH token.
   * @dev A repricing snapshot outlines the ETH reserves backing rswETH at a moment in time (denoted by a block number on the execution layer and a slot on the consensus layer),
   * @dev  as well as information describing a reward period (given by the difference in blocks since the last snapshot) and the payable rewards over this period resulting from validator performance.
   * @dev Repricing snapshots include other stateful information, associated with a snapshot's block number, necessary to reprice the rswETH token (totalETHDeposited and rswETHTotalSupply).
   * @param _snapshot The `RepriceSnapshot` struct data submitted by the trusted execution bot.
   */
  function submitSnapshot(
    UpgradeableRepriceSnapshot calldata _snapshot
  ) external;

  /**
   * @dev This entrypoint will be used when submitting a snapshot and processing withdrawals. In this case we also want to allow the execution bot to be able to delete active validators.
   * @param activeValidatorsToDelete The list of active validators to delete
   * @param _snapshot The `RepriceSnapshot` struct data submitted by the trusted execution bot.
   * @param lastTokenIDToProcess The last withdrawal token ID to process
   */
  function submitSnapshotV2(
    bytes[] calldata activeValidatorsToDelete,
    UpgradeableRepriceSnapshot calldata _snapshot,
    uint256 lastTokenIDToProcess
  ) external;

  /**
   * @dev Sets the threshold number of blocks by which a repricing report is allowed to be stale
   * @notice Only a platform admin can call this function.
   * @param _maximumRepriceBlockAtSnapshotStaleness The new staleness threshold, expressed in terms of number of blocks
   */
  function setMaximumRepriceBlockAtSnapshotStaleness(
    uint256 _maximumRepriceBlockAtSnapshotStaleness
  ) external;

  /**
   * @dev Sets the address of the external Proof of Reserves (PoR) contract to be used for verifying v3 validator reserves during repricing.
   * @notice Only a platform admin can call this function.
   * @param _newAddress The new address of the PoR contract to be set.
   */
  function setExternalV3ReservesPoROracleAddress(address _newAddress) external;

  /**
   * @dev Sets the maximum percentage difference allowed between a repricing snapshot's v3 reserves and the externally reported v3 reserves.
   * @notice Only a platform admin can call this function.
   * @param _newMaximumRepriceV3ReservesExternalPoRDiffPercentage The new maximum percentage difference allowed between current v3 reserves and the externally reported v3 reserves.
   */
  function setMaximumRepriceV3ReservesExternalPoRDiffPercentage(
    uint256 _newMaximumRepriceV3ReservesExternalPoRDiffPercentage
  ) external;

  /**
   * @dev Sets the maximum length of time that can elapse between the last round data update and the current block timestamp before the chainlink data is considered stale, in which case the transaction will revert
   * @param _newMaximumRoundDataStalenessTime The new maximum staleness time for chainlink data
   */
  function setMaximumRoundDataStalenessTime(
    uint256 _newMaximumRoundDataStalenessTime
  ) external;

  /**
   * @dev Sets the maximum percentage difference allowed between the new price and the on-chain reference price
   * @param _newMaximumReferencePriceDiffPercentage The new maximum percentage difference allowed between the new price and the on-chain reference price
   */
  function setMaximumReferencePriceDiffPercentage(
    uint256 _newMaximumReferencePriceDiffPercentage
  ) external;
}

File 42 of 62 : IrswETH.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.16;

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

/**
 * @title RswETH Interface
 * @dev This interface provides the methods to interact with the RswETH contract.
 */
interface IrswETH is IERC20Upgradeable {
  // ***** Errors ******

  /**
   * @dev Error thrown when attempting to reprice with zero RswETH supply.
   */
  error CannotRepriceWithZeroRswETHSupply();

  /**
   * @dev Error thrown when passing a preRewardETHReserves value equal to 0 into the repricing function
   */
  error InvalidPreRewardETHReserves();

  /**
   * @dev Error thrown when updating the reward percentage for either the NOs or the swell treasury and the update will cause the NO percentage + swell treasury percentage to exceed 100%.
   */
  error RewardPercentageTotalOverflow();

  /**
   * @dev Thrown when calling the reprice function and not enough time has elapsed between the previous repriace and the current reprice.
   * @param remainingTime Remaining time until reprice can be called
   */
  error NotEnoughTimeElapsedForReprice(uint256 remainingTime);

  /**
   * @dev Thrown when repricing the rate and the difference in reserves values is greater than expected
   * @param repriceDiff The difference between the previous rswETH rate and what would be the updated rate
   * @param maximumRepriceDiff The maximum allowed difference in rswETH rate
   */
  error RepriceDifferenceTooLarge(
    uint256 repriceDiff,
    uint256 maximumRepriceDiff
  );

  /**
   * @dev Thrown during repricing when the difference in rswETH supplied to repricing compared to the actual supply is too great
   * @param repriceRswETHDiff The difference between the rswETH supplied to repricing and actual supply
   * @param maximumRswETHRepriceDiff The maximum allowed difference in rswETH supply
   */
  error RepriceRswETHDifferenceTooLarge(
    uint256 repriceRswETHDiff,
    uint256 maximumRswETHRepriceDiff
  );

  /**
   * @dev Throw when the caller tries to burn 0 rswETH
   */
  error CannotBurnZeroRswETH();

  /**
   * @dev Error thrown when attempting to call a method that is only callable by the DepositManager contract.
   */
  error OnlyDepositManager();

  /**
   * @dev Error thrown when the amount of rswETH received in exchange for ETH is less than the minimum amount specified.
   * @dev This can occur during depositViaDepositManager, as the flow must account for slippage.
   * @param rswETHAmount The amount of rswETH resulting from the exchange rate conversion
   * @param minRswETH The minimum amount of rswETH required
   */
  error InsufficientRswETHReceived(
    uint256 rswETHAmount,
    uint256 minRswETH
  );

  // ***** Events *****

  /**
   * @dev Event emitted when a user withdraws ETH for swETH
   * @param to Address of the recipient.
   * @param rswETHBurned Amount of RswETH burned in the transaction.
   * @param ethReturned Amount of ETH returned in the transaction.
   */
  event ETHWithdrawn(
    address indexed to,
    uint256 rswETHBurned,
    uint256 ethReturned
  );

  /**
   * @dev Event emitted when the swell treasury reward percentage is updated.
   * @dev Only callable by the platform admin
   * @param oldPercentage The previous swell treasury reward percentage.
   * @param newPercentage The new swell treasury reward percentage.
   */
  event SwellTreasuryRewardPercentageUpdate(
    uint256 oldPercentage,
    uint256 newPercentage
  );

  /**
   * @dev Event emitted when the node operator reward percentage is updated.
   * @dev Only callable by the platform admin
   * @param oldPercentage The previous node operator reward percentage.
   * @param newPercentage The new node operator reward percentage.
   */
  event NodeOperatorRewardPercentageUpdate(
    uint256 oldPercentage,
    uint256 newPercentage
  );

  /**
   * @dev Event emitted when the rswETH - ETH rate is updated
   * @param newEthReserves The new ETH reserves for the swell protocol
   * @param newRswETHToETHRate The new RswETH to ETH rate.
   * @param nodeOperatorRewards The rewards for the node operator's.
   * @param swellTreasuryRewards The rewards for the swell treasury.
   * @param totalETHDeposited Current total ETH staked at time of reprice.
   */
  event Reprice(
    uint256 newEthReserves,
    uint256 newRswETHToETHRate,
    uint256 nodeOperatorRewards,
    uint256 swellTreasuryRewards,
    uint256 totalETHDeposited
  );

  /**
   * @dev Event is fired when some contracts receive ETH
   * @param from The account that sent the ETH
   * @param rswETHMinted The amount of rswETH minted to the caller
   * @param amount The amount of ETH received
   * @param referral The referrer's address
   */
  event ETHDepositReceived(
    address indexed from,
    uint256 amount,
    uint256 rswETHMinted,
    uint256 newTotalETHDeposited,
    address indexed referral
  );

  /**
   * @dev Event emitted on a successful call to setMinimumRepriceTime
   * @param _oldMinimumRepriceTime The old reprice time
   * @param _newMinimumRepriceTime The new updated reprice time
   */
  event MinimumRepriceTimeUpdated(
    uint256 _oldMinimumRepriceTime,
    uint256 _newMinimumRepriceTime
  );

  /**
   * @dev Event emitted on a successful call to setMaximumRepriceRswETHDifferencePercentage
   * @param _oldMaximumRepriceRswETHDifferencePercentage The old maximum rswETH supply difference
   * @param _newMaximumRepriceRswETHDifferencePercentage The new updated rswETH supply difference
   */
  event MaximumRepriceRswETHDifferencePercentageUpdated(
    uint256 _oldMaximumRepriceRswETHDifferencePercentage,
    uint256 _newMaximumRepriceRswETHDifferencePercentage
  );

  /**
   * @dev Event emitted on a successful call to setMaximumRepriceDifferencePercentage
   * @param _oldMaximumRepriceDifferencePercentage The old maximum reprice difference
   * @param _newMaximumRepriceDifferencePercentage The new updated maximum reprice difference
   */
  event MaximumRepriceDifferencePercentageUpdated(
    uint256 _oldMaximumRepriceDifferencePercentage,
    uint256 _newMaximumRepriceDifferencePercentage
  );

  /**
   * @dev Event emitted on successful call from the DepositManager to mint rswETH to a LST depositor
   * @param _receiver The person receiving the rswETH. Should be the same person who deposited their LST's in the DepositManager
   * @param _ethSpent The amount of ETH their LST's were worth at the time of deposit. Used to mint rswETH.
   * @param _rswETHReceived The amount of rswETH received by the user
   */
  event DepoistManagerDeposit(
    address _receiver,
    uint256 _ethSpent,
    uint256 _rswETHReceived
  );

  // ************************************
  // ***** External Methods ******

  /**
   * @dev This method withdraws contract's _token balance to a platform admin
   * @param _token The ERC20 token to withdraw from the contract
   */
  function withdrawERC20(IERC20 _token) external;

  /**
   * @dev Returns the ETH reserves that were provided in the most recent call to the reprice function
   * @return The last recorded ETH reserves
   */
  function lastRepriceETHReserves() external view returns (uint256);

  /**
   * @dev Returns the last time the reprice method was called in UNIX
   * @return The UNIX timestamp of the last time reprice was called
   */
  function lastRepriceUNIX() external view returns (uint256);

  /**
   * @dev Returns the total ETH that has been deposited over the protocols lifespan
   * @return The current total amount of ETH that has been deposited
   */
  function totalETHDeposited() external view returns (uint256);

  /**
   * @dev Returns the current swell treasury reward percentage.
   * @return The current swell treasury reward percentage.
   */
  function swellTreasuryRewardPercentage() external view returns (uint256);

  /**
   * @dev Returns the current node operator reward percentage.
   * @return The current node operator reward percentage.
   */
  function nodeOperatorRewardPercentage() external view returns (uint256);

  /**
   * @dev Returns the current RswETH to ETH rate, returns 1:1 if no reprice has occurred otherwise it returns the rswETHToETHRateFixed rate.
   * @return The current RswETH to ETH rate.
   */
  function rswETHToETHRate() external view returns (uint256);

  /**
   * @dev Returns the current ETH to RswETH rate.
   * @return The current ETH to RswETH rate.
   */
  function ethToRswETHRate() external view returns (uint256);

  /**
   * @dev Returns the minimum reprice time
   * @return The minimum reprice time
   */
  function minimumRepriceTime() external view returns (uint256);

  /**
   * @dev Returns the maximum percentage difference with 1e18 precision
   * @return The maximum percentage difference
   */
  function maximumRepriceDifferencePercentage() external view returns (uint256);

  /**
   * @dev Returns the maximum percentage difference with 1e18 precision
   * @return The maximum percentage difference in suppled and actual swETH supply
   */
  function maximumRepriceRswETHDifferencePercentage()
    external
    view
    returns (uint256);

  /**
   * @dev Sets the new swell treasury reward percentage.
   * @notice Only a platform admin can call this function.
   * @param _newSwellTreasuryRewardPercentage The new swell treasury reward percentage to set.
   */
  function setSwellTreasuryRewardPercentage(
    uint256 _newSwellTreasuryRewardPercentage
  ) external;

  /**
   * @dev Sets the new node operator reward percentage.
   * @notice Only a platform admin can call this function.
   * @param _newNodeOperatorRewardPercentage The new node operator reward percentage to set.
   */
  function setNodeOperatorRewardPercentage(
    uint256 _newNodeOperatorRewardPercentage
  ) external;

  /**
   * @dev Sets the minimum permitted time between successful repricing calls using the block timestamp.
   * @notice Only a platform admin can call this function.
   * @param _minimumRepriceTime The new minimum time between successful repricing calls
   */
  function setMinimumRepriceTime(uint256 _minimumRepriceTime) external;

  /**
   * @dev Sets the maximum percentage allowable difference in rswETH supplied to repricing compared to current rswETH supply.
   * @notice Only a platform admin can call this function.
   * @param _maximumRepriceRswETHDifferencePercentage The new maximum percentage rswETH supply difference allowed.
   */
  function setMaximumRepriceRswETHDifferencePercentage(
    uint256 _maximumRepriceRswETHDifferencePercentage
  ) external;

  /**
   * @dev Sets the maximum percentage allowable difference in swETH to ETH price changes for a repricing call.
   * @notice Only a platform admin can call this function.
   * @param _maximumRepriceDifferencePercentage The new maximum percentage difference in repricing rate.
   */
  function setMaximumRepriceDifferencePercentage(
    uint256 _maximumRepriceDifferencePercentage
  ) external;

  /**
   * @dev Deposits ETH into the contract
   * @notice The amount of ETH deposited will be converted to RswETH at the current RswETH to ETH rate
   */
  function deposit() external payable;

  /**
   * @dev Deposits ETH into the contract
   * @param referral The referrer's address
   * @notice The amount of ETH deposited will be converted to RswETH at the current RswETH to ETH rate
   */
  function depositWithReferral(address referral) external payable;

  /**
   * @dev Called when a user deposits a LST into the deposit manager.
   * @param _amount The amount of ETH to mint rswETH for.
   * @param _to The address to mint rswETH for.
   * @param _minRsweTH The minimum amount of rswETH to mint.
   * @notice Calculates the current LST -> ETH exhange rate and mints the equivalent amount of rswETH to the depositor.
   * @notice Does not actually deposit ETH into the DepositManager.
   */
  function depositViaDepositManager(
    uint256 _amount,
    address _to,
    uint256 _minRsweTH
  ) external;

  /**
   * @dev Burns the requested amount of rswETH, it does not return any ETH to the caller
   * @param amount The amount of rswETH to burn
   */
  function burn(uint256 amount) external;

  /**
   * @dev This method reprices the rswETH -> ETH rate, this will be called via an offchain service on a regular interval, likely ~1 day. The rswETH total supply is passed as an argument to avoid a potential race conditions between the off-chain reserve calculations and the on-chain repricing
   * @dev This method also mints a percentage of rswETH as rewards to be claimed by NO's and the swell treasury. The formula for determining the amount of rswETH to mint is the following: rswETHToMint = (rswETHSupply * newETHRewards * feeRate) / (preRewardETHReserves - newETHRewards * feeRate + newETHRewards)
   * @dev The formula is quite complicated because it needs to factor in the updated exchange rate whilst it calculates the amount of rswETH rewards to mint. This ensures the rewards aren't double-minted and are backed by ETH.
   * @param _preRewardETHReserves The PoR value exclusive of the new ETH rewards earned
   * @param _newETHRewards The total amount of new ETH earnt over the period.
   * @param _rswETHTotalSupply The total rswETH supply at the time of off-chain reprice calculation
   */
  function reprice(
    uint256 _preRewardETHReserves,
    uint256 _newETHRewards,
    uint256 _rswETHTotalSupply
  ) external;
}

File 43 of 62 : IrswEXIT.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.16;

import {IERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/**
 * @title RswEXIT Interface
 * @dev This interface provides the methods to interact with the SwEXIT contract.
 */
interface IrswEXIT is IERC721Upgradeable {
  /**
   * @dev Struct representing a withdrawal request.
   * @param timestamp The timestamp of the withdrawal request.
   * @param amount The amount of RswETH that was requested to be withdrawn.
   * @param lastTokenIdProcessed The last token ID processed when the withdraw request was created, required later on when fetching the rates.
   * @param rateWhenCreated The rate when the withdrawal request was created.
   */
  struct WithdrawRequest {
    uint256 amount;
    uint256 lastTokenIdProcessed;
    uint256 rateWhenCreated;
  }

  /**
   * @dev Thrown when the withdrawal request is too large
   * @param amount The withdrawal request amount.
   * @param limit The withdrawal request limit.
   */
  error WithdrawRequestTooLarge(uint256 amount, uint256 limit);

  /**
   * @dev Thrown when the withdrawal request amount is less than the minimum.
   * @param amount The withdrawal request amount.
   * @param minimum The withdrawal request minimum.
   */
  error WithdrawRequestTooSmall(uint256 amount, uint256 minimum);

  /**
   * @dev Thrown when trying to claim withdrawals for a token that doesn't exist
   */
  error WithdrawalRequestDoesNotExist();

  /**
   * @dev Thrown when trying to claim withdrawals and the requested token has not been processed.
   */
  error WithdrawalRequestNotProcessed();

  /**
   * @dev Thrown when processing withdrawals and the provided _lastRequestIdToProcess hasn't been minted
   */
  error CannotProcessWithdrawalsForNonExistentToken();

  /**
   * @dev Thrown when processing withdrawals and the provided _lastRequestIdToProcess is less than the previous token ID processed
   */
  error LastTokenIdToProcessMustBeGreaterOrEqualThanPrevious();

  /**
   * @dev Thrown when calling a withdrawal method and the withdrawals are paused.
   */
  error WithdrawalsPaused();

  /**
   * @dev Thrown when trying to update the withdrawal request minimum to be less than the withdrawal request maximum.
   */
  error WithdrawRequestMinimumMustBeLessOrEqualToMaximum();

  /**
   * @dev Thrown when trying to update the withdrawal request maximum to be less than the withdrawal request minimum.
   */
  error WithdrawRequestMaximumMustBeGreaterOrEqualToMinimum();

  /**
   * @dev Thrown when anyone except the owner tries to finalize a withdrawal request
   */
  error WithdrawalRequestFinalizationOnlyAllowedForNFTOwner();

  /**
   * @dev Emitted when the base URI is updated.
   * @param oldBaseURI The old base URI.
   * @param newBaseURI The new base URI.
   */
  event BaseURIUpdated(string oldBaseURI, string newBaseURI);

  /**
   * @dev Emitted when a withdrawal request is created.
   * @param tokenId The token ID of the withdrawal request.
   * @param amount The amount of RswETH to withdraw.
   * @param timestamp The timestamp of the withdrawal request.
   * @param lastTokenIdProcessed The last token ID processed, required later on when fetching the rates.
   * @param rateWhenCreated The rate when the withdrawal request was created.
   * @param owner The owner of the withdrawal request.
   */
  event WithdrawRequestCreated(
    uint256 tokenId,
    uint256 amount,
    uint256 timestamp,
    uint256 indexed lastTokenIdProcessed,
    uint256 rateWhenCreated,
    address indexed owner
  );

  /**
   * @dev Emitted when a withdrawal request is claimed.
   * @param owner The owner of the withdrawal request.
   * @param tokenId The token ID of the withdrawal request.
   * @param exitClaimedETH The amount of ETH the owner received.
   */
  event WithdrawalClaimed(
    address indexed owner,
    uint256 tokenId,
    uint256 exitClaimedETH
  );

  /**
   * @dev Emitted when withdrawals are processed.
   * @param fromTokenId The first token ID to process.
   * @param toTokenId The last token ID to process.
   * @param processedRate The rate that the withdrawal requests were processed at, not the finalised rate when claiming just the processed rate
   * @param processedExitingETH The amount of exiting ETH accumulated when processing withdrawals.
   * @param processedExitedETH The amount of exited ETH accumulated when processing withdrawals.
   */
  event WithdrawalsProcessed(
    uint256 fromTokenId,
    uint256 toTokenId,
    uint256 processedRate,
    uint256 processedExitingETH,
    uint256 processedExitedETH
  );

  /**
   * @dev Emitted when the withdrawal request limit is updated.
   * @param oldLimit The old withdrawal request limit.
   * @param newLimit The new withdrawal request limit.
   */
  event WithdrawalRequestMaximumUpdated(uint256 oldLimit, uint256 newLimit);

  /**
   * @dev Emitted when the withdrawal request minimum is updated.
   * @param oldMinimum The old withdrawal request minimum.
   * @param newMinimum The new withdrawal request minimum.
   */
  event WithdrawalRequestMinimumUpdated(uint256 oldMinimum, uint256 newMinimum);

  /**
   * @dev Emitted when ETH is received.
   * @param sender The sender of the ETH.
   * @param amount The amount of ETH received.
   */
  event ETHReceived(address indexed sender, uint256 amount);

  /**
   * @dev Returns the base URI.
   */
  function baseURI() external view returns (string memory);

  /**
   * @dev This method withdraws contract's _token balance to a platform admin
   * @param _token The ERC20 token to withdraw from the contract
   */
  function withdrawERC20(IERC20 _token) external;

  /**
   * @dev Returns the withdrawal request maximum size.
   * @return The withdrawal request maximum size.
   */
  function withdrawRequestMaximum() external view returns (uint256);

  /**
   * @dev Returns the withdrawal request minimum.
   * @return The withdrawal request minimum.
   */
  function withdrawRequestMinimum() external view returns (uint256);

  /**
   * @dev Returns the amount of exiting ETH, which is has not yet been processed for withdrawals.
   * @dev This value is increased by new withdrawal requests and decreased when withdrawals are processed.
   * @dev The amount is given by (amount * rate when requested), where amount is the amount of withdrawn rswETH.
   * @return The current amount of exiting ETH.
   */
  function exitingETH() external view returns (uint256);

  /**
   * @dev Returns the total amount of exited ETH to date. Exited ETH is ETH that was processed in a withdrawal request.
   * @dev When ETH is processed in a withdrawal request, the amount of exited ETH is given by (amount * finalRate), where finalRate is the lesser of the rate when requested and the processed rate, and amount is the amount of withdrawn rswETH.
   * @return The exited ETH.
   */
  function totalETHExited() external view returns (uint256);

  /**
   * @dev Allows the platform admin to update the base URI.
   * @param _baseURI The new base URI.
   */
  function setBaseURI(string memory _baseURI) external;

  /**
   * @dev Allows the platform admin to update the withdrawal request maximum.
   * @param _withdrawRequestMaximum The new withdrawal request maximum.
   */
  function setWithdrawRequestMaximum(uint256 _withdrawRequestMaximum) external;

  /**
   * @dev Allows the platform admin to update the withdrawal request minimum.
   * @param _withdrawRequestMinimum The new withdrawal request minimum.
   */
  function setWithdrawRequestMinimum(uint256 _withdrawRequestMinimum) external;

  /**
   * @dev Processes withdrawals for a given range of token IDs.
   * @param _lastTokenIdToProcess The last token Id to process.
   */
  function processWithdrawals(uint256 _lastTokenIdToProcess) external;

  /**
   * @dev Creates a new withdrawal request.
   * @param amount The amount of RswETH to withdraw.
   */
  function createWithdrawRequest(uint256 amount) external;

  /**
   * @dev Finalizes a withdrawal request, sending the ETH to the owner of the request. This is callable by anyone.
   * @param tokenId The token ID of the withdrawal request to claim.
   */
  function finalizeWithdrawal(uint256 tokenId) external;

  /**
   * @dev Checks if the provided token ID has been processed and returns the rate it was processed at. NOTE: This isn't the final rate that the user will receive, it's just the rate that the withdrawal request was processed at.
   * @param tokenId The token ID to check.
   * @return isProcessed A boolean indicating whether or not the token ID has been processed.
   * @return processedRate The processed rate for the given token ID.
   */
  function getProcessedRateForTokenId(
    uint256 tokenId
  ) external view returns (bool isProcessed, uint256 processedRate);

  /**
   * @dev Returns the last token ID that was processed.
   * @return The last token ID processed.
   */
  function getLastTokenIdProcessed() external view returns (uint256);

  /**
   * @dev Returns the last token ID that was created.
   * @return The last token ID created.
   */
  function getLastTokenIdCreated() external view returns (uint256);
}

File 44 of 62 : Repricing.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.16;

/**
 * @title BalancesSnapshot
 * @dev An exhaustive categorization of the ETH reserves backing the rswETH token at a point in time.
 */
struct BalancesSnapshot {
  uint256 executionLayer; // ETH in protocol controlled contracts on the execution layer which has not yet been deposited on the beacon chain.
  uint256 consensusLayerV3Validators; // ETH Reserves held by v3 validators on the consensus layer.
  uint256 consensusLayerV2Validators; // ETH Reserves held by v2 validators on the consensus layer.
  uint256 transitioning; // ETH Reserves held by validators transitioning to the beacon chain.
}

/**
 * @title RepriceSnapshotState
 * @dev A struct representing the state of a repricing snapshot.
 */
struct RepriceSnapshotState {
  uint256 totalETHDeposited; // The total amount of ETH deposited by stakers.
  uint256 rswETHTotalSupply; // The total supply of the rswETH token.
  BalancesSnapshot balances; // A struct which exhaustively categorizes the current ETH reserves backing rswETH.
}

/**
 * @title RepriceSnapshotMeta
 * @dev A struct containing metadata related to a particular repricing snapshot.
 */
struct RepriceSnapshotMeta {
  uint256 blockNumber; // The block number at which the snapshot was taken.
  uint256 blockOfLastSnapshot; // The block number of the snapshot which preceded this one.
  uint256 slot; // The slot on the consensus layer in which the block associated with the snapshot was proposed.
  uint256 timestamp; // A timestamp which indicates when the execution bot started calculations.
}

/**
 * @title RepriceSnapshot
 * @dev A struct representing a complete repricing snapshot.
 * @dev A repricing snapshot outlines the ETH reserves backing rswETH at a moment in time (denoted by a block number on the execution layer and a slot on the consensus layer),
 * @dev  as well as information describing a reward period (given by the difference in blocks since the last snapshot) and the payable rewards over this period resulting from validator performance.
 * @dev Repricing snapshots include other stateful information, associated with a snapshot's block number, necessary to reprice the rswETH token (totalETHDeposited and rswETHTotalSupply).
 */
struct RepriceSnapshot {
  RepriceSnapshotMeta meta; // An instance of RepriceSnapshotMeta containing metadata about the snapshot.
  RepriceSnapshotState state; // An instance of RepriceSnapshotState representing the state of the snapshot.
  uint256 rewardsPayableForFees; // The amount of rewards to be distributed among rswETH holders, node operators, and the Swell Treasury, resulting from changes to total reserves and total ETH deposited since the last snapshot.
}

/**
 * @title WithdrawSnapshotState
 * @dev A struct representing the state of a withdrawal snapshot.
 */
struct WithdrawSnapshotState {
  uint256 totalETHExited; // The total amount of ETH that has exited the protocol, due to processed withdrawals.
  uint256 exitingETH; // The current amount of exiting ETH, priced at the time the withdrawal was created.
}

/**
 * @title UpgradeableRepriceSnapshot
 * @dev This struct is used inside a uint256 mapping, making it upgrade safe. We will be able to add additional fields to this struct and upgrade the contracts.
 */
struct UpgradeableRepriceSnapshot {
  RepriceSnapshotMeta meta; // An instance of RepriceSnapshotMeta containing metadata about the snapshot.
  RepriceSnapshotState state; // An instance of RepriceSnapshotState representing the state of the snapshot.
  uint256 rewardsPayableForFees; // The amount of rewards to be distributed among rswETH holders, node operators, and the Swell Treasury, resulting from changes to total reserves and total ETH deposited since the last snapshot.
  WithdrawSnapshotState withdrawState; // The state of withdrawals
}

library Repricing {
  function reserveAssets(
    BalancesSnapshot memory _balances
  ) internal pure returns (uint256) {
    return
      _balances.executionLayer +
      _balances.consensusLayerV3Validators +
      _balances.consensusLayerV2Validators +
      _balances.transitioning;
  }
}

File 45 of 62 : SwellLib.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.16;

/**
 * @title SwellLib
 * @author https://github.com/max-taylor
 * @notice This library contains roles, errors, events and functions that are widely used throughout the protocol
 */
library SwellLib {
  // ***** Roles *****
  /**
   * @dev The platform admin role
   */
  bytes32 public constant PLATFORM_ADMIN = keccak256("PLATFORM_ADMIN");

  /**
   * @dev The bot role
   */
  bytes32 public constant BOT = keccak256("BOT");

  /**
   * @dev The role used for the swETH.reprice method
   */
  bytes32 public constant REPRICER = keccak256("REPRICER");

  /**
   * @dev Used for checking all the pausing methods
   */
  bytes32 public constant PAUSER = keccak256("PAUSER");

  /**
   * @dev Used for checking all the unpausing methods
   */
  bytes32 public constant UNPAUSER = keccak256("UNPAUSER");

  /**
   * @dev Role used specifically in the deleteActiveValidators method
   */
  bytes32 public constant DELETE_ACTIVE_VALIDATORS =
    keccak256("DELETE_ACTIVE_VALIDATORS");

  /**
   * @dev Role used specifically in the processWithdrawals method
   */
  bytes32 public constant PROCESS_WITHDRAWALS =
    keccak256("PROCESS_WITHDRAWALS");

  /**
   * @dev Role used specifically in Eigen Layer Delegation
   */
  bytes32 public constant EIGENLAYER_DELEGATOR = keccak256("EIGENLAYER_DELEGATOR");

  /**
   * @dev Role used specifically in withdrawals from an Eigen Pod
   */
  bytes32 public constant EIGENLAYER_WITHDRAWALS = keccak256("EIGENLAYER_WITHDRAWALS");

  // ***** Errors *****
  /**
   * @dev Thrown when _checkZeroAddress is called with the zero address
   */
  error CannotBeZeroAddress();

  /**
   * @dev Thrown in some contracts when the contract call is received by the fallback method
   */
  error InvalidMethodCall();

  /**
   * @dev Thrown in some contracts when ETH is sent directly to the contract
   */
  error InvalidETHDeposit();

  /**
   * @dev Thrown when interacting with a method on the protocol that is disabled via the coreMethodsPaused bool
   */
  error CoreMethodsPaused();

  /**
   * @dev Thrown when interacting with a method on the protocol that is disabled via the botMethodsPaused bool
   */
  error BotMethodsPaused();

  /**
   * @dev Thrown when interacting with a method on the protocol that is disabled via the operatorMethodsPaused bool
   */
  error OperatorMethodsPaused();

  /**
   * @dev Thrown when interacting with a method on the protocol that is disabled via the withdrawalsPaused bool
   */
  error WithdrawalsPaused();

  /**
   * @dev Thrown when calling the withdrawERC20 method and the contracts balance is 0
   */
  error NoTokensToWithdraw();

  /**
   * @dev Thrown when attempting to deposit with referrer the same all calling address
   */
  error CannotReferSelf();

  // ************************************
  // ***** Internal Methods *****
  /**
   * @dev This helper is used throughout the protocol to guard against zero addresses being passed as parameters
   * @param _address The address to check if it is the zero address
   */
  function _checkZeroAddress(address _address) internal pure {
    if (_address == address(0)) {
      revert CannotBeZeroAddress();
    }
  }
}

File 46 of 62 : AggregatorV3Interface.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.16;

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

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

  function version() external view returns (uint256);

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

File 47 of 62 : IBeaconChainOracle.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;

/**
 * @title Interface for the BeaconStateOracle contract.
 * @author Layr Labs, Inc.
 * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service
 */
interface IBeaconChainOracle {
    /// @notice The block number to state root mapping.
    function timestampToBlockRoot(uint256 timestamp) external view returns (bytes32);
}

File 48 of 62 : IDelayedWithdrawalRouter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;

interface IDelayedWithdrawalRouter {
    // struct used to pack data into a single storage slot
    struct DelayedWithdrawal {
        uint224 amount;
        uint32 blockCreated;
    }

    // struct used to store a single users delayedWithdrawal data
    struct UserDelayedWithdrawals {
        uint256 delayedWithdrawalsCompleted;
        DelayedWithdrawal[] delayedWithdrawals;
    }

     /// @notice event for delayedWithdrawal creation
    event DelayedWithdrawalCreated(address podOwner, address recipient, uint256 amount, uint256 index);

    /// @notice event for the claiming of delayedWithdrawals
    event DelayedWithdrawalsClaimed(address recipient, uint256 amountClaimed, uint256 delayedWithdrawalsCompleted);

    /// @notice Emitted when the `withdrawalDelayBlocks` variable is modified from `previousValue` to `newValue`.
    event WithdrawalDelayBlocksSet(uint256 previousValue, uint256 newValue);

    /**
     * @notice Creates an delayed withdrawal for `msg.value` to the `recipient`.
     * @dev Only callable by the `podOwner`'s EigenPod contract.
     */
    function createDelayedWithdrawal(address podOwner, address recipient) external payable;

    /**
     * @notice Called in order to withdraw delayed withdrawals made to the `recipient` that have passed the `withdrawalDelayBlocks` period.
     * @param recipient The address to claim delayedWithdrawals for.
     * @param maxNumberOfWithdrawalsToClaim Used to limit the maximum number of withdrawals to loop through claiming.
     */
    function claimDelayedWithdrawals(address recipient, uint256 maxNumberOfWithdrawalsToClaim) external;

    /**
     * @notice Called in order to withdraw delayed withdrawals made to the caller that have passed the `withdrawalDelayBlocks` period.
     * @param maxNumberOfWithdrawalsToClaim Used to limit the maximum number of withdrawals to loop through claiming.
     */
    function claimDelayedWithdrawals(uint256 maxNumberOfWithdrawalsToClaim) external;

    /// @notice Owner-only function for modifying the value of the `withdrawalDelayBlocks` variable.
    function setWithdrawalDelayBlocks(uint256 newValue) external;

    /// @notice Getter function for the mapping `_userWithdrawals`
    function userWithdrawals(address user) external view returns (UserDelayedWithdrawals memory);

    /// @notice Getter function to get all delayedWithdrawals of the `user`
    function getUserDelayedWithdrawals(address user) external view returns (DelayedWithdrawal[] memory);

    /// @notice Getter function to get all delayedWithdrawals that are currently claimable by the `user`
    function getClaimableUserDelayedWithdrawals(address user) external view returns (DelayedWithdrawal[] memory);

    /// @notice Getter function for fetching the delayedWithdrawal at the `index`th entry from the `_userWithdrawals[user].delayedWithdrawals` array
    function userDelayedWithdrawalByIndex(address user, uint256 index) external view returns (DelayedWithdrawal memory);

    /// @notice Getter function for fetching the length of the delayedWithdrawals array of a specific user
    function userWithdrawalsLength(address user) external view returns (uint256);

    /// @notice Convenience function for checking whether or not the delayedWithdrawal at the `index`th entry from the `_userWithdrawals[user].delayedWithdrawals` array is currently claimable
    function canClaimDelayedWithdrawal(address user, uint256 index) external view returns (bool);

    /**
     * @notice Delay enforced by this contract for completing any delayedWithdrawal. Measured in blocks, and adjustable by this contract's owner,
     * up to a maximum of `MAX_WITHDRAWAL_DELAY_BLOCKS`. Minimum value is 0 (i.e. no delay enforced).
     */
    function withdrawalDelayBlocks() external view returns (uint256);
}

File 49 of 62 : IDelegationManager.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;

import "./IStrategy.sol";
import "./ISignatureUtils.sol";
import "./IStrategyManager.sol";

/**
 * @title DelegationManager
 * @author Layr Labs, Inc.
 * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service
 * @notice  This is the contract for delegation in EigenLayer. The main functionalities of this contract are
 * - enabling anyone to register as an operator in EigenLayer
 * - allowing operators to specify parameters related to stakers who delegate to them
 * - enabling any staker to delegate its stake to the operator of its choice (a given staker can only delegate to a single operator at a time)
 * - enabling a staker to undelegate its assets from the operator it is delegated to (performed as part of the withdrawal process, initiated through the StrategyManager)
 */
interface IDelegationManager is ISignatureUtils {
    // @notice Struct used for storing information about a single operator who has registered with EigenLayer
    struct OperatorDetails {
        // @notice address to receive the rewards that the operator earns via serving applications built on EigenLayer.
        address earningsReceiver;
        /**
         * @notice Address to verify signatures when a staker wishes to delegate to the operator, as well as controlling "forced undelegations".
         * @dev Signature verification follows these rules:
         * 1) If this address is left as address(0), then any staker will be free to delegate to the operator, i.e. no signature verification will be performed.
         * 2) If this address is an EOA (i.e. it has no code), then we follow standard ECDSA signature verification for delegations to the operator.
         * 3) If this address is a contract (i.e. it has code) then we forward a call to the contract and verify that it returns the correct EIP-1271 "magic value".
         */
        address delegationApprover;
        /**
         * @notice A minimum delay -- measured in blocks -- enforced between:
         * 1) the operator signalling their intent to register for a service, via calling `Slasher.optIntoSlashing`
         * and
         * 2) the operator completing registration for the service, via the service ultimately calling `Slasher.recordFirstStakeUpdate`
         * @dev note that for a specific operator, this value *cannot decrease*, i.e. if the operator wishes to modify their OperatorDetails,
         * then they are only allowed to either increase this value or keep it the same.
         */
        uint32 stakerOptOutWindowBlocks;
    }

    /**
     * @notice Abstract struct used in calculating an EIP712 signature for a staker to approve that they (the staker themselves) delegate to a specific operator.
     * @dev Used in computing the `STAKER_DELEGATION_TYPEHASH` and as a reference in the computation of the stakerDigestHash in the `delegateToBySignature` function.
     */
    struct StakerDelegation {
        // the staker who is delegating
        address staker;
        // the operator being delegated to
        address operator;
        // the staker's nonce
        uint256 nonce;
        // the expiration timestamp (UTC) of the signature
        uint256 expiry;
    }

    /**
     * @notice Abstract struct used in calculating an EIP712 signature for an operator's delegationApprover to approve that a specific staker delegate to the operator.
     * @dev Used in computing the `DELEGATION_APPROVAL_TYPEHASH` and as a reference in the computation of the approverDigestHash in the `_delegate` function.
     */
    struct DelegationApproval {
        // the staker who is delegating
        address staker;
        // the operator being delegated to
        address operator;
        // the operator's provided salt
        bytes32 salt;
        // the expiration timestamp (UTC) of the signature
        uint256 expiry;
    }

    /**
     * Struct type used to specify an existing queued withdrawal. Rather than storing the entire struct, only a hash is stored.
     * In functions that operate on existing queued withdrawals -- e.g. completeQueuedWithdrawal`, the data is resubmitted and the hash of the submitted
     * data is computed by `calculateWithdrawalRoot` and checked against the stored hash in order to confirm the integrity of the submitted data.
     */
    struct Withdrawal {
        // The address that originated the Withdrawal
        address staker;
        // The address that the staker was delegated to at the time that the Withdrawal was created
        address delegatedTo;
        // The address that can complete the Withdrawal + will receive funds when completing the withdrawal
        address withdrawer;
        // Nonce used to guarantee that otherwise identical withdrawals have unique hashes
        uint256 nonce;
        // Block number when the Withdrawal was created
        uint32 startBlock;
        // Array of strategies that the Withdrawal contains
        IStrategy[] strategies;
        // Array containing the amount of shares in each Strategy in the `strategies` array
        uint256[] shares;
    }

    struct QueuedWithdrawalParams {
        // Array of strategies that the QueuedWithdrawal contains
        IStrategy[] strategies;
        // Array containing the amount of shares in each Strategy in the `strategies` array
        uint256[] shares;
        // The address of the withdrawer
        address withdrawer;
    }

    // @notice Emitted when a new operator registers in EigenLayer and provides their OperatorDetails.
    event OperatorRegistered(address indexed operator, OperatorDetails operatorDetails);

    /// @notice Emitted when an operator updates their OperatorDetails to @param newOperatorDetails
    event OperatorDetailsModified(address indexed operator, OperatorDetails newOperatorDetails);

    /**
     * @notice Emitted when @param operator indicates that they are updating their MetadataURI string
     * @dev Note that these strings are *never stored in storage* and are instead purely emitted in events for off-chain indexing
     */
    event OperatorMetadataURIUpdated(address indexed operator, string metadataURI);

    /// @notice Emitted whenever an operator's shares are increased for a given strategy. Note that shares is the delta in the operator's shares.
    event OperatorSharesIncreased(address indexed operator, address staker, IStrategy strategy, uint256 shares);

    /// @notice Emitted whenever an operator's shares are decreased for a given strategy. Note that shares is the delta in the operator's shares.
    event OperatorSharesDecreased(address indexed operator, address staker, IStrategy strategy, uint256 shares);

    /// @notice Emitted when @param staker delegates to @param operator.
    event StakerDelegated(address indexed staker, address indexed operator);

    /// @notice Emitted when @param staker undelegates from @param operator.
    event StakerUndelegated(address indexed staker, address indexed operator);

    /// @notice Emitted when @param staker is undelegated via a call not originating from the staker themself
    event StakerForceUndelegated(address indexed staker, address indexed operator);

    /**
     * @notice Emitted when a new withdrawal is queued.
     * @param withdrawalRoot Is the hash of the `withdrawal`.
     * @param withdrawal Is the withdrawal itself.
     */
    event WithdrawalQueued(bytes32 withdrawalRoot, Withdrawal withdrawal);

    /// @notice Emitted when a queued withdrawal is completed
    event WithdrawalCompleted(bytes32 withdrawalRoot);

    /// @notice Emitted when a queued withdrawal is *migrated* from the StrategyManager to the DelegationManager
    event WithdrawalMigrated(bytes32 oldWithdrawalRoot, bytes32 newWithdrawalRoot);
    
    /// @notice Emitted when the `minWithdrawalDelayBlocks` variable is modified from `previousValue` to `newValue`.
    event MinWithdrawalDelayBlocksSet(uint256 previousValue, uint256 newValue);

    /// @notice Emitted when the `strategyWithdrawalDelayBlocks` variable is modified from `previousValue` to `newValue`.
    event StrategyWithdrawalDelayBlocksSet(IStrategy strategy, uint256 previousValue, uint256 newValue);

    /**
     * @notice Registers the caller as an operator in EigenLayer.
     * @param registeringOperatorDetails is the `OperatorDetails` for the operator.
     * @param metadataURI is a URI for the operator's metadata, i.e. a link providing more details on the operator.
     *
     * @dev Once an operator is registered, they cannot 'deregister' as an operator, and they will forever be considered "delegated to themself".
     * @dev This function will revert if the caller attempts to set their `earningsReceiver` to address(0).
     * @dev Note that the `metadataURI` is *never stored * and is only emitted in the `OperatorMetadataURIUpdated` event
     */
    function registerAsOperator(
        OperatorDetails calldata registeringOperatorDetails,
        string calldata metadataURI
    ) external;

    /**
     * @notice Updates an operator's stored `OperatorDetails`.
     * @param newOperatorDetails is the updated `OperatorDetails` for the operator, to replace their current OperatorDetails`.
     *
     * @dev The caller must have previously registered as an operator in EigenLayer.
     * @dev This function will revert if the caller attempts to set their `earningsReceiver` to address(0).
     */
    function modifyOperatorDetails(OperatorDetails calldata newOperatorDetails) external;

    /**
     * @notice Called by an operator to emit an `OperatorMetadataURIUpdated` event indicating the information has updated.
     * @param metadataURI The URI for metadata associated with an operator
     * @dev Note that the `metadataURI` is *never stored * and is only emitted in the `OperatorMetadataURIUpdated` event
     */
    function updateOperatorMetadataURI(string calldata metadataURI) external;

    /**
     * @notice Caller delegates their stake to an operator.
     * @param operator The account (`msg.sender`) is delegating its assets to for use in serving applications built on EigenLayer.
     * @param approverSignatureAndExpiry Verifies the operator approves of this delegation
     * @param approverSalt A unique single use value tied to an individual signature.
     * @dev The approverSignatureAndExpiry is used in the event that:
     *          1) the operator's `delegationApprover` address is set to a non-zero value.
     *                  AND
     *          2) neither the operator nor their `delegationApprover` is the `msg.sender`, since in the event that the operator
     *             or their delegationApprover is the `msg.sender`, then approval is assumed.
     * @dev In the event that `approverSignatureAndExpiry` is not checked, its content is ignored entirely; it's recommended to use an empty input
     * in this case to save on complexity + gas costs
     */
    function delegateTo(
        address operator,
        SignatureWithExpiry memory approverSignatureAndExpiry,
        bytes32 approverSalt
    ) external;

    /**
     * @notice Caller delegates a staker's stake to an operator with valid signatures from both parties.
     * @param staker The account delegating stake to an `operator` account
     * @param operator The account (`staker`) is delegating its assets to for use in serving applications built on EigenLayer.
     * @param stakerSignatureAndExpiry Signed data from the staker authorizing delegating stake to an operator
     * @param approverSignatureAndExpiry is a parameter that will be used for verifying that the operator approves of this delegation action in the event that:
     * @param approverSalt Is a salt used to help guarantee signature uniqueness. Each salt can only be used once by a given approver.
     *
     * @dev If `staker` is an EOA, then `stakerSignature` is verified to be a valid ECDSA stakerSignature from `staker`, indicating their intention for this action.
     * @dev If `staker` is a contract, then `stakerSignature` will be checked according to EIP-1271.
     * @dev the operator's `delegationApprover` address is set to a non-zero value.
     * @dev neither the operator nor their `delegationApprover` is the `msg.sender`, since in the event that the operator or their delegationApprover
     * is the `msg.sender`, then approval is assumed.
     * @dev This function will revert if the current `block.timestamp` is equal to or exceeds the expiry
     * @dev In the case that `approverSignatureAndExpiry` is not checked, its content is ignored entirely; it's recommended to use an empty input
     * in this case to save on complexity + gas costs
     */
    function delegateToBySignature(
        address staker,
        address operator,
        SignatureWithExpiry memory stakerSignatureAndExpiry,
        SignatureWithExpiry memory approverSignatureAndExpiry,
        bytes32 approverSalt
    ) external;

    /**
     * @notice Undelegates the staker from the operator who they are delegated to. Puts the staker into the "undelegation limbo" mode of the EigenPodManager
     * and queues a withdrawal of all of the staker's shares in the StrategyManager (to the staker), if necessary.
     * @param staker The account to be undelegated.
     * @return withdrawalRoot The root of the newly queued withdrawal, if a withdrawal was queued. Otherwise just bytes32(0).
     *
     * @dev Reverts if the `staker` is also an operator, since operators are not allowed to undelegate from themselves.
     * @dev Reverts if the caller is not the staker, nor the operator who the staker is delegated to, nor the operator's specified "delegationApprover"
     * @dev Reverts if the `staker` is already undelegated.
     */
    function undelegate(address staker) external returns (bytes32[] memory withdrawalRoot);

    /**
     * Allows a staker to withdraw some shares. Withdrawn shares/strategies are immediately removed
     * from the staker. If the staker is delegated, withdrawn shares/strategies are also removed from
     * their operator.
     *
     * All withdrawn shares/strategies are placed in a queue and can be fully withdrawn after a delay.
     */
    function queueWithdrawals(
        QueuedWithdrawalParams[] calldata queuedWithdrawalParams
    ) external returns (bytes32[] memory);

    /**
     * @notice Used to complete the specified `withdrawal`. The caller must match `withdrawal.withdrawer`
     * @param withdrawal The Withdrawal to complete.
     * @param tokens Array in which the i-th entry specifies the `token` input to the 'withdraw' function of the i-th Strategy in the `withdrawal.strategies` array.
     * This input can be provided with zero length if `receiveAsTokens` is set to 'false' (since in that case, this input will be unused)
     * @param middlewareTimesIndex is the index in the operator that the staker who triggered the withdrawal was delegated to's middleware times array
     * @param receiveAsTokens If true, the shares specified in the withdrawal will be withdrawn from the specified strategies themselves
     * and sent to the caller, through calls to `withdrawal.strategies[i].withdraw`. If false, then the shares in the specified strategies
     * will simply be transferred to the caller directly.
     * @dev middlewareTimesIndex should be calculated off chain before calling this function by finding the first index that satisfies `slasher.canWithdraw`
     * @dev beaconChainETHStrategy shares are non-transferrable, so if `receiveAsTokens = false` and `withdrawal.withdrawer != withdrawal.staker`, note that
     * any beaconChainETHStrategy shares in the `withdrawal` will be _returned to the staker_, rather than transferred to the withdrawer, unlike shares in
     * any other strategies, which will be transferred to the withdrawer.
     */
    function completeQueuedWithdrawal(
        Withdrawal calldata withdrawal,
        IERC20[] calldata tokens,
        uint256 middlewareTimesIndex,
        bool receiveAsTokens
    ) external;

    /**
     * @notice Array-ified version of `completeQueuedWithdrawal`.
     * Used to complete the specified `withdrawals`. The function caller must match `withdrawals[...].withdrawer`
     * @param withdrawals The Withdrawals to complete.
     * @param tokens Array of tokens for each Withdrawal. See `completeQueuedWithdrawal` for the usage of a single array.
     * @param middlewareTimesIndexes One index to reference per Withdrawal. See `completeQueuedWithdrawal` for the usage of a single index.
     * @param receiveAsTokens Whether or not to complete each withdrawal as tokens. See `completeQueuedWithdrawal` for the usage of a single boolean.
     * @dev See `completeQueuedWithdrawal` for relevant dev tags
     */
    function completeQueuedWithdrawals(
        Withdrawal[] calldata withdrawals,
        IERC20[][] calldata tokens,
        uint256[] calldata middlewareTimesIndexes,
        bool[] calldata receiveAsTokens
    ) external;

    /**
     * @notice Increases a staker's delegated share balance in a strategy.
     * @param staker The address to increase the delegated shares for their operator.
     * @param strategy The strategy in which to increase the delegated shares.
     * @param shares The number of shares to increase.
     *
     * @dev *If the staker is actively delegated*, then increases the `staker`'s delegated shares in `strategy` by `shares`. Otherwise does nothing.
     * @dev Callable only by the StrategyManager or EigenPodManager.
     */
    function increaseDelegatedShares(
        address staker,
        IStrategy strategy,
        uint256 shares
    ) external;

    /**
     * @notice Decreases a staker's delegated share balance in a strategy.
     * @param staker The address to increase the delegated shares for their operator.
     * @param strategy The strategy in which to decrease the delegated shares.
     * @param shares The number of shares to decrease.
     *
     * @dev *If the staker is actively delegated*, then decreases the `staker`'s delegated shares in `strategy` by `shares`. Otherwise does nothing.
     * @dev Callable only by the StrategyManager or EigenPodManager.
     */
    function decreaseDelegatedShares(
        address staker,
        IStrategy strategy,
        uint256 shares
    ) external;

    /**
     * @notice returns the address of the operator that `staker` is delegated to.
     * @notice Mapping: staker => operator whom the staker is currently delegated to.
     * @dev Note that returning address(0) indicates that the staker is not actively delegated to any operator.
     */
    function delegatedTo(address staker) external view returns (address);

    /**
     * @notice Returns the OperatorDetails struct associated with an `operator`.
     */
    function operatorDetails(address operator) external view returns (OperatorDetails memory);

    /*
     * @notice Returns the earnings receiver address for an operator
     */
    function earningsReceiver(address operator) external view returns (address);

    /**
     * @notice Returns the delegationApprover account for an operator
     */
    function delegationApprover(address operator) external view returns (address);

    /**
     * @notice Returns the stakerOptOutWindowBlocks for an operator
     */
    function stakerOptOutWindowBlocks(address operator) external view returns (uint256);

    /**
     * @notice Given array of strategies, returns array of shares for the operator
     */
    function getOperatorShares(
        address operator,
        IStrategy[] memory strategies
    ) external view returns (uint256[] memory);

    /**
     * @notice Given a list of strategies, return the minimum number of blocks that must pass to withdraw
     * from all the inputted strategies. Return value is >= minWithdrawalDelayBlocks as this is the global min withdrawal delay.
     * @param strategies The strategies to check withdrawal delays for
     */
    function getWithdrawalDelay(IStrategy[] calldata strategies) external view returns (uint256);

    /**
     * @notice returns the total number of shares in `strategy` that are delegated to `operator`.
     * @notice Mapping: operator => strategy => total number of shares in the strategy delegated to the operator.
     * @dev By design, the following invariant should hold for each Strategy:
     * (operator's shares in delegation manager) = sum (shares above zero of all stakers delegated to operator)
     * = sum (delegateable shares of all stakers delegated to the operator)
     */
    function operatorShares(address operator, IStrategy strategy) external view returns (uint256);

    /**
     * @notice Returns 'true' if `staker` *is* actively delegated, and 'false' otherwise.
     */
    function isDelegated(address staker) external view returns (bool);

    /**
     * @notice Returns true is an operator has previously registered for delegation.
     */
    function isOperator(address operator) external view returns (bool);

    /// @notice Mapping: staker => number of signed delegation nonces (used in `delegateToBySignature`) from the staker that the contract has already checked
    function stakerNonce(address staker) external view returns (uint256);

    /**
     * @notice Mapping: delegationApprover => 32-byte salt => whether or not the salt has already been used by the delegationApprover.
     * @dev Salts are used in the `delegateTo` and `delegateToBySignature` functions. Note that these functions only process the delegationApprover's
     * signature + the provided salt if the operator being delegated to has specified a nonzero address as their `delegationApprover`.
     */
    function delegationApproverSaltIsSpent(address _delegationApprover, bytes32 salt) external view returns (bool);

    /**
     * @notice Minimum delay enforced by this contract for completing queued withdrawals. Measured in blocks, and adjustable by this contract's owner,
     * up to a maximum of `MAX_WITHDRAWAL_DELAY_BLOCKS`. Minimum value is 0 (i.e. no delay enforced).
     * Note that strategies each have a separate withdrawal delay, which can be greater than this value. So the minimum number of blocks that must pass
     * to withdraw a strategy is MAX(minWithdrawalDelayBlocks, strategyWithdrawalDelayBlocks[strategy])
     */
    function minWithdrawalDelayBlocks() external view returns (uint256);

    /**
     * @notice Minimum delay enforced by this contract per Strategy for completing queued withdrawals. Measured in blocks, and adjustable by this contract's owner,
     * up to a maximum of `MAX_WITHDRAWAL_DELAY_BLOCKS`. Minimum value is 0 (i.e. no delay enforced).
     */
    function strategyWithdrawalDelayBlocks(IStrategy strategy) external view returns (uint256);

    /**
     * @notice Calculates the digestHash for a `staker` to sign to delegate to an `operator`
     * @param staker The signing staker
     * @param operator The operator who is being delegated to
     * @param expiry The desired expiry time of the staker's signature
     */
    function calculateCurrentStakerDelegationDigestHash(
        address staker,
        address operator,
        uint256 expiry
    ) external view returns (bytes32);

    /**
     * @notice Calculates the digest hash to be signed and used in the `delegateToBySignature` function
     * @param staker The signing staker
     * @param _stakerNonce The nonce of the staker. In practice we use the staker's current nonce, stored at `stakerNonce[staker]`
     * @param operator The operator who is being delegated to
     * @param expiry The desired expiry time of the staker's signature
     */
    function calculateStakerDelegationDigestHash(
        address staker,
        uint256 _stakerNonce,
        address operator,
        uint256 expiry
    ) external view returns (bytes32);

    /**
     * @notice Calculates the digest hash to be signed by the operator's delegationApprove and used in the `delegateTo` and `delegateToBySignature` functions.
     * @param staker The account delegating their stake
     * @param operator The account receiving delegated stake
     * @param _delegationApprover the operator's `delegationApprover` who will be signing the delegationHash (in general)
     * @param approverSalt A unique and single use value associated with the approver signature.
     * @param expiry Time after which the approver's signature becomes invalid
     */
    function calculateDelegationApprovalDigestHash(
        address staker,
        address operator,
        address _delegationApprover,
        bytes32 approverSalt,
        uint256 expiry
    ) external view returns (bytes32);

    /// @notice The EIP-712 typehash for the contract's domain
    function DOMAIN_TYPEHASH() external view returns (bytes32);

    /// @notice The EIP-712 typehash for the StakerDelegation struct used by the contract
    function STAKER_DELEGATION_TYPEHASH() external view returns (bytes32);

    /// @notice The EIP-712 typehash for the DelegationApproval struct used by the contract
    function DELEGATION_APPROVAL_TYPEHASH() external view returns (bytes32);

    /**
     * @notice Getter function for the current EIP-712 domain separator for this contract.
     *
     * @dev The domain separator will change in the event of a fork that changes the ChainID.
     * @dev By introducing a domain separator the DApp developers are guaranteed that there can be no signature collision.
     * for more detailed information please read EIP-712.
     */
    function domainSeparator() external view returns (bytes32);
    
    /// @notice Mapping: staker => cumulative number of queued withdrawals they have ever initiated.
    /// @dev This only increments (doesn't decrement), and is used to help ensure that otherwise identical withdrawals have unique hashes.
    function cumulativeWithdrawalsQueued(address staker) external view returns (uint256);

    /// @notice Returns the keccak256 hash of `withdrawal`.
    function calculateWithdrawalRoot(Withdrawal memory withdrawal) external pure returns (bytes32);

    function migrateQueuedWithdrawals(IStrategyManager.DeprecatedStruct_QueuedWithdrawal[] memory withdrawalsToQueue) external;
}

File 50 of 62 : IEigenPod.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;

import "../libraries/BeaconChainProofs.sol";
import "./IEigenPodManager.sol";
import "./IBeaconChainOracle.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/**
 * @title The implementation contract used for restaking beacon chain ETH on EigenLayer
 * @author Layr Labs, Inc.
 * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service
 * @notice The main functionalities are:
 * - creating new ETH validators with their withdrawal credentials pointed to this contract
 * - proving from beacon chain state roots that withdrawal credentials are pointed to this contract
 * - proving from beacon chain state roots the balances of ETH validators with their withdrawal credentials
 *   pointed to this contract
 * - updating aggregate balances in the EigenPodManager
 * - withdrawing eth when withdrawals are initiated
 * @dev Note that all beacon chain balances are stored as gwei within the beacon chain datastructures. We choose
 *   to account balances in terms of gwei in the EigenPod contract and convert to wei when making calls to other contracts
 */
interface IEigenPod {
    enum VALIDATOR_STATUS {
        INACTIVE, // doesnt exist
        ACTIVE, // staked on ethpos and withdrawal credentials are pointed to the EigenPod
        WITHDRAWN // withdrawn from the Beacon Chain
    }

    struct ValidatorInfo {
        // index of the validator in the beacon chain
        uint64 validatorIndex;
        // amount of beacon chain ETH restaked on EigenLayer in gwei
        uint64 restakedBalanceGwei;
        //timestamp of the validator's most recent balance update
        uint64 mostRecentBalanceUpdateTimestamp;
        // status of the validator
        VALIDATOR_STATUS status;
    }

    /**
     * @notice struct used to store amounts related to proven withdrawals in memory. Used to help
     * manage stack depth and optimize the number of external calls, when batching withdrawal operations.
     */
    struct VerifiedWithdrawal {
        // amount to send to a podOwner from a proven withdrawal
        uint256 amountToSendGwei;
        // difference in shares to be recorded in the eigenPodManager, as a result of the withdrawal
        int256 sharesDeltaGwei;
    }


    enum PARTIAL_WITHDRAWAL_CLAIM_STATUS {
        REDEEMED,
        PENDING,
        FAILED
    }

    /// @notice Emitted when an ETH validator stakes via this eigenPod
    event EigenPodStaked(bytes pubkey);

    /// @notice Emitted when an ETH validator's withdrawal credentials are successfully verified to be pointed to this eigenPod
    event ValidatorRestaked(uint40 validatorIndex);

    /// @notice Emitted when an ETH validator's  balance is proven to be updated.  Here newValidatorBalanceGwei
    //  is the validator's balance that is credited on EigenLayer.
    event ValidatorBalanceUpdated(uint40 validatorIndex, uint64 balanceTimestamp, uint64 newValidatorBalanceGwei);

    /// @notice Emitted when an ETH validator is prove to have withdrawn from the beacon chain
    event FullWithdrawalRedeemed(
        uint40 validatorIndex,
        uint64 withdrawalTimestamp,
        address indexed recipient,
        uint64 withdrawalAmountGwei
    );

    /// @notice Emitted when a partial withdrawal claim is successfully redeemed
    event PartialWithdrawalRedeemed(
        uint40 validatorIndex,
        uint64 withdrawalTimestamp,
        address indexed recipient,
        uint64 partialWithdrawalAmountGwei
    );

    /// @notice Emitted when restaked beacon chain ETH is withdrawn from the eigenPod.
    event RestakedBeaconChainETHWithdrawn(address indexed recipient, uint256 amount);

    /// @notice Emitted when podOwner enables restaking
    event RestakingActivated(address indexed podOwner);

    /// @notice Emitted when ETH is received via the `receive` fallback
    event NonBeaconChainETHReceived(uint256 amountReceived);

    /// @notice Emitted when ETH that was previously received via the `receive` fallback is withdrawn
    event NonBeaconChainETHWithdrawn(address indexed recipient, uint256 amountWithdrawn);


    /// @notice The max amount of eth, in gwei, that can be restaked per validator
    function MAX_RESTAKED_BALANCE_GWEI_PER_VALIDATOR() external view returns (uint64);

    /// @notice the amount of execution layer ETH in this contract that is staked in EigenLayer (i.e. withdrawn from beaconchain but not EigenLayer),
    function withdrawableRestakedExecutionLayerGwei() external view returns (uint64);

    /// @notice any ETH deposited into the EigenPod contract via the `receive` fallback function
    function nonBeaconChainETHBalanceWei() external view returns (uint256);

    /// @notice Used to initialize the pointers to contracts crucial to the pod's functionality, in beacon proxy construction from EigenPodManager
    function initialize(address owner) external;

    /// @notice Called by EigenPodManager when the owner wants to create another ETH validator.
    function stake(bytes calldata pubkey, bytes calldata signature, bytes32 depositDataRoot) external payable;

    /**
     * @notice Transfers `amountWei` in ether from this contract to the specified `recipient` address
     * @notice Called by EigenPodManager to withdrawBeaconChainETH that has been added to the EigenPod's balance due to a withdrawal from the beacon chain.
     * @dev The podOwner must have already proved sufficient withdrawals, so that this pod's `withdrawableRestakedExecutionLayerGwei` exceeds the
     * `amountWei` input (when converted to GWEI).
     * @dev Reverts if `amountWei` is not a whole Gwei amount
     */
    function withdrawRestakedBeaconChainETH(address recipient, uint256 amount) external;

    /// @notice The single EigenPodManager for EigenLayer
    function eigenPodManager() external view returns (IEigenPodManager);

    /// @notice The owner of this EigenPod
    function podOwner() external view returns (address);

    /// @notice an indicator of whether or not the podOwner has ever "fully restaked" by successfully calling `verifyCorrectWithdrawalCredentials`.
    function hasRestaked() external view returns (bool);

    /**
     * @notice The latest timestamp at which the pod owner withdrew the balance of the pod, via calling `withdrawBeforeRestaking`.
     * @dev This variable is only updated when the `withdrawBeforeRestaking` function is called, which can only occur before `hasRestaked` is set to true for this pod.
     * Proofs for this pod are only valid against Beacon Chain state roots corresponding to timestamps after the stored `mostRecentWithdrawalTimestamp`.
     */
    function mostRecentWithdrawalTimestamp() external view returns (uint64);

    /// @notice Returns the validatorInfo struct for the provided pubkeyHash
    function validatorPubkeyHashToInfo(bytes32 validatorPubkeyHash) external view returns (ValidatorInfo memory);

    /// @notice Returns the validatorInfo struct for the provided pubkey
    function validatorPubkeyToInfo(bytes calldata validatorPubkey) external view returns (ValidatorInfo memory);

    ///@notice mapping that tracks proven withdrawals
    function provenWithdrawal(bytes32 validatorPubkeyHash, uint64 slot) external view returns (bool);

    /// @notice This returns the status of a given validator
    function validatorStatus(bytes32 pubkeyHash) external view returns (VALIDATOR_STATUS);

    /// @notice This returns the status of a given validator pubkey
    function validatorStatus(bytes calldata validatorPubkey) external view returns (VALIDATOR_STATUS);

    /**
     * @notice This function verifies that the withdrawal credentials of validator(s) owned by the podOwner are pointed to
     * this contract. It also verifies the effective balance  of the validator.  It verifies the provided proof of the ETH validator against the beacon chain state
     * root, marks the validator as 'active' in EigenLayer, and credits the restaked ETH in Eigenlayer.
     * @param oracleTimestamp is the Beacon Chain timestamp whose state root the `proof` will be proven against.
     * @param validatorIndices is the list of indices of the validators being proven, refer to consensus specs
     * @param withdrawalCredentialProofs is an array of proofs, where each proof proves each ETH validator's balance and withdrawal credentials
     * against a beacon chain state root
     * @param validatorFields are the fields of the "Validator Container", refer to consensus specs
     * for details: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#validator
     */
    function verifyWithdrawalCredentials(
        uint64 oracleTimestamp,
        BeaconChainProofs.StateRootProof calldata stateRootProof,
        uint40[] calldata validatorIndices,
        bytes[] calldata withdrawalCredentialProofs,
        bytes32[][] calldata validatorFields
    )
        external;

    /**
     * @notice This function records an update (either increase or decrease) in the pod's balance in the StrategyManager.  
               It also verifies a merkle proof of the validator's current beacon chain balance.  
     * @param oracleTimestamp The oracleTimestamp whose state root the `proof` will be proven against.
     *        Must be within `VERIFY_BALANCE_UPDATE_WINDOW_SECONDS` of the current block.
     * @param validatorIndices is the list of indices of the validators being proven, refer to consensus specs 
     * @param validatorFieldsProofs proofs against the `beaconStateRoot` for each validator in `validatorFields`
     * @param validatorFields are the fields of the "Validator Container", refer to consensus specs
     * @dev For more details on the Beacon Chain spec, see: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#validator
     */
    function verifyBalanceUpdates(
        uint64 oracleTimestamp,
        uint40[] calldata validatorIndices,
        BeaconChainProofs.StateRootProof calldata stateRootProof,
        bytes[] calldata validatorFieldsProofs,
        bytes32[][] calldata validatorFields
    ) external;

    /**
     * @notice This function records full and partial withdrawals on behalf of one of the Ethereum validators for this EigenPod
     * @param oracleTimestamp is the timestamp of the oracle slot that the withdrawal is being proven against
     * @param withdrawalProofs is the information needed to check the veracity of the block numbers and withdrawals being proven
     * @param validatorFieldsProofs is the proof of the validator's fields' in the validator tree
     * @param withdrawalFields are the fields of the withdrawals being proven
     * @param validatorFields are the fields of the validators being proven
     */
    function verifyAndProcessWithdrawals(
        uint64 oracleTimestamp,
        BeaconChainProofs.StateRootProof calldata stateRootProof,
        BeaconChainProofs.WithdrawalProof[] calldata withdrawalProofs,
        bytes[] calldata validatorFieldsProofs,
        bytes32[][] calldata validatorFields,
        bytes32[][] calldata withdrawalFields
    ) external;

    /**
     * @notice Called by the pod owner to activate restaking by withdrawing
     * all existing ETH from the pod and preventing further withdrawals via
     * "withdrawBeforeRestaking()"
     */
    function activateRestaking() external;

    /// @notice Called by the pod owner to withdraw the balance of the pod when `hasRestaked` is set to false
    function withdrawBeforeRestaking() external;

    /// @notice Called by the pod owner to withdraw the nonBeaconChainETHBalanceWei
    function withdrawNonBeaconChainETHBalanceWei(address recipient, uint256 amountToWithdraw) external;

    /// @notice called by owner of a pod to remove any ERC20s deposited in the pod
    function recoverTokens(IERC20[] memory tokenList, uint256[] memory amountsToWithdraw, address recipient) external;
}

File 51 of 62 : IEigenPodManager.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;

import "@openzeppelin/contracts/proxy/beacon/IBeacon.sol";
import "./IETHPOSDeposit.sol";
import "./IStrategyManager.sol";
import "./IEigenPod.sol";
import "./IBeaconChainOracle.sol";
import "./IPausable.sol";
import "./ISlasher.sol";
import "./IStrategy.sol";

/**
 * @title Interface for factory that creates and manages solo staking pods that have their withdrawal credentials pointed to EigenLayer.
 * @author Layr Labs, Inc.
 * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service
 */

interface IEigenPodManager is IPausable {
    /// @notice Emitted to notify the update of the beaconChainOracle address
    event BeaconOracleUpdated(address indexed newOracleAddress);

    /// @notice Emitted to notify the deployment of an EigenPod
    event PodDeployed(address indexed eigenPod, address indexed podOwner);

    /// @notice Emitted to notify a deposit of beacon chain ETH recorded in the strategy manager
    event BeaconChainETHDeposited(address indexed podOwner, uint256 amount);

    /// @notice Emitted when `maxPods` value is updated from `previousValue` to `newValue`
    event MaxPodsUpdated(uint256 previousValue, uint256 newValue);

    /// @notice Emitted when the balance of an EigenPod is updated
    event PodSharesUpdated(address indexed podOwner, int256 sharesDelta);

    /// @notice Emitted when a withdrawal of beacon chain ETH is completed
    event BeaconChainETHWithdrawalCompleted(
        address indexed podOwner,
        uint256 shares,
        uint96 nonce,
        address delegatedAddress,
        address withdrawer,
        bytes32 withdrawalRoot
    );

    event DenebForkTimestampUpdated(uint64 newValue);

    /**
     * @notice Creates an EigenPod for the sender.
     * @dev Function will revert if the `msg.sender` already has an EigenPod.
     * @dev Returns EigenPod address 
     */
    function createPod() external returns (address);

    /**
     * @notice Stakes for a new beacon chain validator on the sender's EigenPod.
     * Also creates an EigenPod for the sender if they don't have one already.
     * @param pubkey The 48 bytes public key of the beacon chain validator.
     * @param signature The validator's signature of the deposit data.
     * @param depositDataRoot The root/hash of the deposit data for the validator's deposit.
     */
    function stake(bytes calldata pubkey, bytes calldata signature, bytes32 depositDataRoot) external payable;

    /**
     * @notice Changes the `podOwner`'s shares by `sharesDelta` and performs a call to the DelegationManager
     * to ensure that delegated shares are also tracked correctly
     * @param podOwner is the pod owner whose balance is being updated.
     * @param sharesDelta is the change in podOwner's beaconChainETHStrategy shares
     * @dev Callable only by the podOwner's EigenPod contract.
     * @dev Reverts if `sharesDelta` is not a whole Gwei amount
     */
    function recordBeaconChainETHBalanceUpdate(address podOwner, int256 sharesDelta) external;

    /**
     * @notice Updates the oracle contract that provides the beacon chain state root
     * @param newBeaconChainOracle is the new oracle contract being pointed to
     * @dev Callable only by the owner of this contract (i.e. governance)
     */
    function updateBeaconChainOracle(IBeaconChainOracle newBeaconChainOracle) external;

    /// @notice Returns the address of the `podOwner`'s EigenPod if it has been deployed.
    function ownerToPod(address podOwner) external view returns (IEigenPod);

    /// @notice Returns the address of the `podOwner`'s EigenPod (whether it is deployed yet or not).
    function getPod(address podOwner) external view returns (IEigenPod);

    /// @notice The ETH2 Deposit Contract
    function ethPOS() external view returns (IETHPOSDeposit);

    /// @notice Beacon proxy to which the EigenPods point
    function eigenPodBeacon() external view returns (IBeacon);

    /// @notice Oracle contract that provides updates to the beacon chain's state
    function beaconChainOracle() external view returns (IBeaconChainOracle);

    /// @notice Returns the beacon block root at `timestamp`. Reverts if the Beacon block root at `timestamp` has not yet been finalized.
    function getBlockRootAtTimestamp(uint64 timestamp) external view returns (bytes32);

    /// @notice EigenLayer's StrategyManager contract
    function strategyManager() external view returns (IStrategyManager);

    /// @notice EigenLayer's Slasher contract
    function slasher() external view returns (ISlasher);

    /// @notice Returns 'true' if the `podOwner` has created an EigenPod, and 'false' otherwise.
    function hasPod(address podOwner) external view returns (bool);

    /// @notice Returns the number of EigenPods that have been created
    function numPods() external view returns (uint256);

    /// @notice Returns the maximum number of EigenPods that can be created
    function maxPods() external view returns (uint256);

    /**
     * @notice Mapping from Pod owner owner to the number of shares they have in the virtual beacon chain ETH strategy.
     * @dev The share amount can become negative. This is necessary to accommodate the fact that a pod owner's virtual beacon chain ETH shares can
     * decrease between the pod owner queuing and completing a withdrawal.
     * When the pod owner's shares would otherwise increase, this "deficit" is decreased first _instead_.
     * Likewise, when a withdrawal is completed, this "deficit" is decreased and the withdrawal amount is decreased; We can think of this
     * as the withdrawal "paying off the deficit".
     */
    function podOwnerShares(address podOwner) external view returns (int256);

    /// @notice returns canonical, virtual beaconChainETH strategy
    function beaconChainETHStrategy() external view returns (IStrategy);

    /**
     * @notice Used by the DelegationManager to remove a pod owner's shares while they're in the withdrawal queue.
     * Simply decreases the `podOwner`'s shares by `shares`, down to a minimum of zero.
     * @dev This function reverts if it would result in `podOwnerShares[podOwner]` being less than zero, i.e. it is forbidden for this function to
     * result in the `podOwner` incurring a "share deficit". This behavior prevents a Staker from queuing a withdrawal which improperly removes excessive
     * shares from the operator to whom the staker is delegated.
     * @dev Reverts if `shares` is not a whole Gwei amount
     */
    function removeShares(address podOwner, uint256 shares) external;

    /**
     * @notice Increases the `podOwner`'s shares by `shares`, paying off deficit if possible.
     * Used by the DelegationManager to award a pod owner shares on exiting the withdrawal queue
     * @dev Returns the number of shares added to `podOwnerShares[podOwner]` above zero, which will be less than the `shares` input
     * in the event that the podOwner has an existing shares deficit (i.e. `podOwnerShares[podOwner]` starts below zero)
     * @dev Reverts if `shares` is not a whole Gwei amount
     */
    function addShares(address podOwner, uint256 shares) external returns (uint256);

    /**
     * @notice Used by the DelegationManager to complete a withdrawal, sending tokens to some destination address
     * @dev Prioritizes decreasing the podOwner's share deficit, if they have one
     * @dev Reverts if `shares` is not a whole Gwei amount
     */
    function withdrawSharesAsTokens(address podOwner, address destination, uint256 shares) external;

    /**
     * @notice the deneb hard fork timestamp used to determine which proof path to use for proving a withdrawal
     */
    function denebForkTimestamp() external view returns (uint64);

     /**
     * setting the deneb hard fork timestamp by the eigenPodManager owner
     * @dev this function is designed to be called twice.  Once, it is set to type(uint64).max 
     * prior to the actual deneb fork timestamp being set, and then the second time it is set 
     * to the actual deneb fork timestamp.
     */
    function setDenebForkTimestamp(uint64 newDenebForkTimestamp) external;

}

File 52 of 62 : IETHPOSDeposit.sol
// ┏━━━┓━┏┓━┏┓━━┏━━━┓━━┏━━━┓━━━━┏━━━┓━━━━━━━━━━━━━━━━━━━┏┓━━━━━┏━━━┓━━━━━━━━━┏┓━━━━━━━━━━━━━━┏┓━
// ┃┏━━┛┏┛┗┓┃┃━━┃┏━┓┃━━┃┏━┓┃━━━━┗┓┏┓┃━━━━━━━━━━━━━━━━━━┏┛┗┓━━━━┃┏━┓┃━━━━━━━━┏┛┗┓━━━━━━━━━━━━┏┛┗┓
// ┃┗━━┓┗┓┏┛┃┗━┓┗┛┏┛┃━━┃┃━┃┃━━━━━┃┃┃┃┏━━┓┏━━┓┏━━┓┏━━┓┏┓┗┓┏┛━━━━┃┃━┗┛┏━━┓┏━┓━┗┓┏┛┏━┓┏━━┓━┏━━┓┗┓┏┛
// ┃┏━━┛━┃┃━┃┏┓┃┏━┛┏┛━━┃┃━┃┃━━━━━┃┃┃┃┃┏┓┃┃┏┓┃┃┏┓┃┃━━┫┣┫━┃┃━━━━━┃┃━┏┓┃┏┓┃┃┏┓┓━┃┃━┃┏┛┗━┓┃━┃┏━┛━┃┃━
// ┃┗━━┓━┃┗┓┃┃┃┃┃┃┗━┓┏┓┃┗━┛┃━━━━┏┛┗┛┃┃┃━┫┃┗┛┃┃┗┛┃┣━━┃┃┃━┃┗┓━━━━┃┗━┛┃┃┗┛┃┃┃┃┃━┃┗┓┃┃━┃┗┛┗┓┃┗━┓━┃┗┓
// ┗━━━┛━┗━┛┗┛┗┛┗━━━┛┗┛┗━━━┛━━━━┗━━━┛┗━━┛┃┏━┛┗━━┛┗━━┛┗┛━┗━┛━━━━┗━━━┛┗━━┛┗┛┗┛━┗━┛┗┛━┗━━━┛┗━━┛━┗━┛
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┃┃━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┗┛━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

// SPDX-License-Identifier: CC0-1.0

pragma solidity >=0.5.0;

// This interface is designed to be compatible with the Vyper version.
/// @notice This is the Ethereum 2.0 deposit contract interface.
/// For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs
interface IETHPOSDeposit {
    /// @notice A processed deposit event.
    event DepositEvent(bytes pubkey, bytes withdrawal_credentials, bytes amount, bytes signature, bytes index);

    /// @notice Submit a Phase 0 DepositData object.
    /// @param pubkey A BLS12-381 public key.
    /// @param withdrawal_credentials Commitment to a public key for withdrawals.
    /// @param signature A BLS12-381 signature.
    /// @param deposit_data_root The SHA-256 hash of the SSZ-encoded DepositData object.
    /// Used as a protection against malformed input.
    function deposit(
        bytes calldata pubkey,
        bytes calldata withdrawal_credentials,
        bytes calldata signature,
        bytes32 deposit_data_root
    ) external payable;

    /// @notice Query the current deposit root hash.
    /// @return The deposit root hash.
    function get_deposit_root() external view returns (bytes32);

    /// @notice Query the current deposit count.
    /// @return The deposit count encoded as a little endian 64-bit number.
    function get_deposit_count() external view returns (bytes memory);
}

File 53 of 62 : IPausable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;

import "../interfaces/IPauserRegistry.sol";

/**
 * @title Adds pausability to a contract, with pausing & unpausing controlled by the `pauser` and `unpauser` of a PauserRegistry contract.
 * @author Layr Labs, Inc.
 * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service
 * @notice Contracts that inherit from this contract may define their own `pause` and `unpause` (and/or related) functions.
 * These functions should be permissioned as "onlyPauser" which defers to a `PauserRegistry` for determining access control.
 * @dev Pausability is implemented using a uint256, which allows up to 256 different single bit-flags; each bit can potentially pause different functionality.
 * Inspiration for this was taken from the NearBridge design here https://etherscan.io/address/0x3FEFc5A4B1c02f21cBc8D3613643ba0635b9a873#code.
 * For the `pause` and `unpause` functions we've implemented, if you pause, you can only flip (any number of) switches to on/1 (aka "paused"), and if you unpause,
 * you can only flip (any number of) switches to off/0 (aka "paused").
 * If you want a pauseXYZ function that just flips a single bit / "pausing flag", it will:
 * 1) 'bit-wise and' (aka `&`) a flag with the current paused state (as a uint256)
 * 2) update the paused state to this new value
 * @dev We note as well that we have chosen to identify flags by their *bit index* as opposed to their numerical value, so, e.g. defining `DEPOSITS_PAUSED = 3`
 * indicates specifically that if the *third bit* of `_paused` is flipped -- i.e. it is a '1' -- then deposits should be paused
 */

interface IPausable {
    /// @notice Emitted when the `pauserRegistry` is set to `newPauserRegistry`.
    event PauserRegistrySet(IPauserRegistry pauserRegistry, IPauserRegistry newPauserRegistry);

    /// @notice Emitted when the pause is triggered by `account`, and changed to `newPausedStatus`.
    event Paused(address indexed account, uint256 newPausedStatus);

    /// @notice Emitted when the pause is lifted by `account`, and changed to `newPausedStatus`.
    event Unpaused(address indexed account, uint256 newPausedStatus);
    
    /// @notice Address of the `PauserRegistry` contract that this contract defers to for determining access control (for pausing).
    function pauserRegistry() external view returns (IPauserRegistry);

    /**
     * @notice This function is used to pause an EigenLayer contract's functionality.
     * It is permissioned to the `pauser` address, which is expected to be a low threshold multisig.
     * @param newPausedStatus represents the new value for `_paused` to take, which means it may flip several bits at once.
     * @dev This function can only pause functionality, and thus cannot 'unflip' any bit in `_paused` from 1 to 0.
     */
    function pause(uint256 newPausedStatus) external;

    /**
     * @notice Alias for `pause(type(uint256).max)`.
     */
    function pauseAll() external;

    /**
     * @notice This function is used to unpause an EigenLayer contract's functionality.
     * It is permissioned to the `unpauser` address, which is expected to be a high threshold multisig or governance contract.
     * @param newPausedStatus represents the new value for `_paused` to take, which means it may flip several bits at once.
     * @dev This function can only unpause functionality, and thus cannot 'flip' any bit in `_paused` from 0 to 1.
     */
    function unpause(uint256 newPausedStatus) external;

    /// @notice Returns the current paused status as a uint256.
    function paused() external view returns (uint256);

    /// @notice Returns 'true' if the `indexed`th bit of `_paused` is 1, and 'false' otherwise
    function paused(uint8 index) external view returns (bool);

    /// @notice Allows the unpauser to set a new pauser registry
    function setPauserRegistry(IPauserRegistry newPauserRegistry) external;
}

File 54 of 62 : IPauserRegistry.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;

/**
 * @title Interface for the `PauserRegistry` contract.
 * @author Layr Labs, Inc.
 * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service
 */
interface IPauserRegistry {
    event PauserStatusChanged(address pauser, bool canPause);

    event UnpauserChanged(address previousUnpauser, address newUnpauser);
    
    /// @notice Mapping of addresses to whether they hold the pauser role.
    function isPauser(address pauser) external view returns (bool);

    /// @notice Unique address that holds the unpauser role. Capable of changing *both* the pauser and unpauser addresses.
    function unpauser() external view returns (address);
}

File 55 of 62 : ISignatureUtils.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;

/**
 * @title The interface for common signature utilities.
 * @author Layr Labs, Inc.
 * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service
 */
interface ISignatureUtils {
    // @notice Struct that bundles together a signature and an expiration time for the signature. Used primarily for stack management.
    struct SignatureWithExpiry {
        // the signature itself, formatted as a single bytes object
        bytes signature;
        // the expiration timestamp (UTC) of the signature
        uint256 expiry;
    }

    // @notice Struct that bundles together a signature, a salt for uniqueness, and an expiration time for the signature. Used primarily for stack management.
    struct SignatureWithSaltAndExpiry {
        // the signature itself, formatted as a single bytes object
        bytes signature;
        // the salt used to generate the signature
        bytes32 salt;
        // the expiration timestamp (UTC) of the signature
        uint256 expiry;
    }
}

File 56 of 62 : ISlasher.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;

import "./IStrategyManager.sol";
import "./IDelegationManager.sol";

/**
 * @title Interface for the primary 'slashing' contract for EigenLayer.
 * @author Layr Labs, Inc.
 * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service
 * @notice See the `Slasher` contract itself for implementation details.
 */
interface ISlasher {
    // struct used to store information about the current state of an operator's obligations to middlewares they are serving
    struct MiddlewareTimes {
        // The update block for the middleware whose most recent update was earliest, i.e. the 'stalest' update out of all middlewares the operator is serving
        uint32 stalestUpdateBlock;
        // The latest 'serveUntilBlock' from all of the middleware that the operator is serving
        uint32 latestServeUntilBlock;
    }

    // struct used to store details relevant to a single middleware that an operator has opted-in to serving
    struct MiddlewareDetails {
        // the block at which the contract begins being able to finalize the operator's registration with the service via calling `recordFirstStakeUpdate`
        uint32 registrationMayBeginAtBlock;
        // the block before which the contract is allowed to slash the user
        uint32 contractCanSlashOperatorUntilBlock;
        // the block at which the middleware's view of the operator's stake was most recently updated
        uint32 latestUpdateBlock;
    }

    /// @notice Emitted when a middleware times is added to `operator`'s array.
    event MiddlewareTimesAdded(
        address operator,
        uint256 index,
        uint32 stalestUpdateBlock,
        uint32 latestServeUntilBlock
    );

    /// @notice Emitted when `operator` begins to allow `contractAddress` to slash them.
    event OptedIntoSlashing(address indexed operator, address indexed contractAddress);

    /// @notice Emitted when `contractAddress` signals that it will no longer be able to slash `operator` after the `contractCanSlashOperatorUntilBlock`.
    event SlashingAbilityRevoked(
        address indexed operator,
        address indexed contractAddress,
        uint32 contractCanSlashOperatorUntilBlock
    );

    /**
     * @notice Emitted when `slashingContract` 'freezes' the `slashedOperator`.
     * @dev The `slashingContract` must have permission to slash the `slashedOperator`, i.e. `canSlash(slasherOperator, slashingContract)` must return 'true'.
     */
    event OperatorFrozen(address indexed slashedOperator, address indexed slashingContract);

    /// @notice Emitted when `previouslySlashedAddress` is 'unfrozen', allowing them to again move deposited funds within EigenLayer.
    event FrozenStatusReset(address indexed previouslySlashedAddress);

    /**
     * @notice Gives the `contractAddress` permission to slash the funds of the caller.
     * @dev Typically, this function must be called prior to registering for a middleware.
     */
    function optIntoSlashing(address contractAddress) external;

    /**
     * @notice Used for 'slashing' a certain operator.
     * @param toBeFrozen The operator to be frozen.
     * @dev Technically the operator is 'frozen' (hence the name of this function), and then subject to slashing pending a decision by a human-in-the-loop.
     * @dev The operator must have previously given the caller (which should be a contract) the ability to slash them, through a call to `optIntoSlashing`.
     */
    function freezeOperator(address toBeFrozen) external;

    /**
     * @notice Removes the 'frozen' status from each of the `frozenAddresses`
     * @dev Callable only by the contract owner (i.e. governance).
     */
    function resetFrozenStatus(address[] calldata frozenAddresses) external;

    /**
     * @notice this function is a called by middlewares during an operator's registration to make sure the operator's stake at registration
     *         is slashable until serveUntil
     * @param operator the operator whose stake update is being recorded
     * @param serveUntilBlock the block until which the operator's stake at the current block is slashable
     * @dev adds the middleware's slashing contract to the operator's linked list
     */
    function recordFirstStakeUpdate(address operator, uint32 serveUntilBlock) external;

    /**
     * @notice this function is a called by middlewares during a stake update for an operator (perhaps to free pending withdrawals)
     *         to make sure the operator's stake at updateBlock is slashable until serveUntil
     * @param operator the operator whose stake update is being recorded
     * @param updateBlock the block for which the stake update is being recorded
     * @param serveUntilBlock the block until which the operator's stake at updateBlock is slashable
     * @param insertAfter the element of the operators linked list that the currently updating middleware should be inserted after
     * @dev insertAfter should be calculated offchain before making the transaction that calls this. this is subject to race conditions,
     *      but it is anticipated to be rare and not detrimental.
     */
    function recordStakeUpdate(
        address operator,
        uint32 updateBlock,
        uint32 serveUntilBlock,
        uint256 insertAfter
    ) external;

    /**
     * @notice this function is a called by middlewares during an operator's deregistration to make sure the operator's stake at deregistration
     *         is slashable until serveUntil
     * @param operator the operator whose stake update is being recorded
     * @param serveUntilBlock the block until which the operator's stake at the current block is slashable
     * @dev removes the middleware's slashing contract to the operator's linked list and revokes the middleware's (i.e. caller's) ability to
     * slash `operator` once `serveUntil` is reached
     */
    function recordLastStakeUpdateAndRevokeSlashingAbility(address operator, uint32 serveUntilBlock) external;

    /// @notice The StrategyManager contract of EigenLayer
    function strategyManager() external view returns (IStrategyManager);

    /// @notice The DelegationManager contract of EigenLayer
    function delegation() external view returns (IDelegationManager);

    /**
     * @notice Used to determine whether `staker` is actively 'frozen'. If a staker is frozen, then they are potentially subject to
     * slashing of their funds, and cannot cannot deposit or withdraw from the strategyManager until the slashing process is completed
     * and the staker's status is reset (to 'unfrozen').
     * @param staker The staker of interest.
     * @return Returns 'true' if `staker` themselves has their status set to frozen, OR if the staker is delegated
     * to an operator who has their status set to frozen. Otherwise returns 'false'.
     */
    function isFrozen(address staker) external view returns (bool);

    /// @notice Returns true if `slashingContract` is currently allowed to slash `toBeSlashed`.
    function canSlash(address toBeSlashed, address slashingContract) external view returns (bool);

    /// @notice Returns the block until which `serviceContract` is allowed to slash the `operator`.
    function contractCanSlashOperatorUntilBlock(
        address operator,
        address serviceContract
    ) external view returns (uint32);

    /// @notice Returns the block at which the `serviceContract` last updated its view of the `operator`'s stake
    function latestUpdateBlock(address operator, address serviceContract) external view returns (uint32);

    /// @notice A search routine for finding the correct input value of `insertAfter` to `recordStakeUpdate` / `_updateMiddlewareList`.
    function getCorrectValueForInsertAfter(address operator, uint32 updateBlock) external view returns (uint256);

    /**
     * @notice Returns 'true' if `operator` can currently complete a withdrawal started at the `withdrawalStartBlock`, with `middlewareTimesIndex` used
     * to specify the index of a `MiddlewareTimes` struct in the operator's list (i.e. an index in `operatorToMiddlewareTimes[operator]`). The specified
     * struct is consulted as proof of the `operator`'s ability (or lack thereof) to complete the withdrawal.
     * This function will return 'false' if the operator cannot currently complete a withdrawal started at the `withdrawalStartBlock`, *or* in the event
     * that an incorrect `middlewareTimesIndex` is supplied, even if one or more correct inputs exist.
     * @param operator Either the operator who queued the withdrawal themselves, or if the withdrawing party is a staker who delegated to an operator,
     * this address is the operator *who the staker was delegated to* at the time of the `withdrawalStartBlock`.
     * @param withdrawalStartBlock The block number at which the withdrawal was initiated.
     * @param middlewareTimesIndex Indicates an index in `operatorToMiddlewareTimes[operator]` to consult as proof of the `operator`'s ability to withdraw
     * @dev The correct `middlewareTimesIndex` input should be computable off-chain.
     */
    function canWithdraw(
        address operator,
        uint32 withdrawalStartBlock,
        uint256 middlewareTimesIndex
    ) external returns (bool);

    /**
     * operator =>
     *  [
     *      (
     *          the least recent update block of all of the middlewares it's serving/served,
     *          latest time that the stake bonded at that update needed to serve until
     *      )
     *  ]
     */
    function operatorToMiddlewareTimes(
        address operator,
        uint256 arrayIndex
    ) external view returns (MiddlewareTimes memory);

    /// @notice Getter function for fetching `operatorToMiddlewareTimes[operator].length`
    function middlewareTimesLength(address operator) external view returns (uint256);

    /// @notice Getter function for fetching `operatorToMiddlewareTimes[operator][index].stalestUpdateBlock`.
    function getMiddlewareTimesIndexStalestUpdateBlock(address operator, uint32 index) external view returns (uint32);

    /// @notice Getter function for fetching `operatorToMiddlewareTimes[operator][index].latestServeUntil`.
    function getMiddlewareTimesIndexServeUntilBlock(address operator, uint32 index) external view returns (uint32);

    /// @notice Getter function for fetching `_operatorToWhitelistedContractsByUpdate[operator].size`.
    function operatorWhitelistedContractsLinkedListSize(address operator) external view returns (uint256);

    /// @notice Getter function for fetching a single node in the operator's linked list (`_operatorToWhitelistedContractsByUpdate[operator]`).
    function operatorWhitelistedContractsLinkedListEntry(
        address operator,
        address node
    ) external view returns (bool, uint256, uint256);
}

File 57 of 62 : IStrategy.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;

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

/**
 * @title Minimal interface for an `Strategy` contract.
 * @author Layr Labs, Inc.
 * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service
 * @notice Custom `Strategy` implementations may expand extensively on this interface.
 */
interface IStrategy {
    /**
     * @notice Used to deposit tokens into this Strategy
     * @param token is the ERC20 token being deposited
     * @param amount is the amount of token being deposited
     * @dev This function is only callable by the strategyManager contract. It is invoked inside of the strategyManager's
     * `depositIntoStrategy` function, and individual share balances are recorded in the strategyManager as well.
     * @return newShares is the number of new shares issued at the current exchange ratio.
     */
    function deposit(IERC20 token, uint256 amount) external returns (uint256);

    /**
     * @notice Used to withdraw tokens from this Strategy, to the `recipient`'s address
     * @param recipient is the address to receive the withdrawn funds
     * @param token is the ERC20 token being transferred out
     * @param amountShares is the amount of shares being withdrawn
     * @dev This function is only callable by the strategyManager contract. It is invoked inside of the strategyManager's
     * other functions, and individual share balances are recorded in the strategyManager as well.
     */
    function withdraw(address recipient, IERC20 token, uint256 amountShares) external;

    /**
     * @notice Used to convert a number of shares to the equivalent amount of underlying tokens for this strategy.
     * @notice In contrast to `sharesToUnderlyingView`, this function **may** make state modifications
     * @param amountShares is the amount of shares to calculate its conversion into the underlying token
     * @return The amount of underlying tokens corresponding to the input `amountShares`
     * @dev Implementation for these functions in particular may vary significantly for different strategies
     */
    function sharesToUnderlying(uint256 amountShares) external returns (uint256);

    /**
     * @notice Used to convert an amount of underlying tokens to the equivalent amount of shares in this strategy.
     * @notice In contrast to `underlyingToSharesView`, this function **may** make state modifications
     * @param amountUnderlying is the amount of `underlyingToken` to calculate its conversion into strategy shares
     * @return The amount of underlying tokens corresponding to the input `amountShares`
     * @dev Implementation for these functions in particular may vary significantly for different strategies
     */
    function underlyingToShares(uint256 amountUnderlying) external returns (uint256);

    /**
     * @notice convenience function for fetching the current underlying value of all of the `user`'s shares in
     * this strategy. In contrast to `userUnderlyingView`, this function **may** make state modifications
     */
    function userUnderlying(address user) external returns (uint256);

    /**
     * @notice convenience function for fetching the current total shares of `user` in this strategy, by
     * querying the `strategyManager` contract
     */
    function shares(address user) external view returns (uint256);

    /**
     * @notice Used to convert a number of shares to the equivalent amount of underlying tokens for this strategy.
     * @notice In contrast to `sharesToUnderlying`, this function guarantees no state modifications
     * @param amountShares is the amount of shares to calculate its conversion into the underlying token
     * @return The amount of shares corresponding to the input `amountUnderlying`
     * @dev Implementation for these functions in particular may vary significantly for different strategies
     */
    function sharesToUnderlyingView(uint256 amountShares) external view returns (uint256);

    /**
     * @notice Used to convert an amount of underlying tokens to the equivalent amount of shares in this strategy.
     * @notice In contrast to `underlyingToShares`, this function guarantees no state modifications
     * @param amountUnderlying is the amount of `underlyingToken` to calculate its conversion into strategy shares
     * @return The amount of shares corresponding to the input `amountUnderlying`
     * @dev Implementation for these functions in particular may vary significantly for different strategies
     */
    function underlyingToSharesView(uint256 amountUnderlying) external view returns (uint256);

    /**
     * @notice convenience function for fetching the current underlying value of all of the `user`'s shares in
     * this strategy. In contrast to `userUnderlying`, this function guarantees no state modifications
     */
    function userUnderlyingView(address user) external view returns (uint256);

    /// @notice The underlying token for shares in this Strategy
    function underlyingToken() external view returns (IERC20);

    /// @notice The total number of extant shares in this Strategy
    function totalShares() external view returns (uint256);

    /// @notice Returns either a brief string explaining the strategy's goal & purpose, or a link to metadata that explains in more detail.
    function explanation() external view returns (string memory);
}

File 58 of 62 : IStrategyManager.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;

import "./IStrategy.sol";
import "./ISlasher.sol";
import "./IDelegationManager.sol";
import "./IEigenPodManager.sol";

/**
 * @title Interface for the primary entrypoint for funds into EigenLayer.
 * @author Layr Labs, Inc.
 * @notice Terms of Service: https://docs.eigenlayer.xyz/overview/terms-of-service
 * @notice See the `StrategyManager` contract itself for implementation details.
 */
interface IStrategyManager {
    /**
     * @notice Emitted when a new deposit occurs on behalf of `staker`.
     * @param staker Is the staker who is depositing funds into EigenLayer.
     * @param strategy Is the strategy that `staker` has deposited into.
     * @param token Is the token that `staker` deposited.
     * @param shares Is the number of new shares `staker` has been granted in `strategy`.
     */
    event Deposit(address staker, IERC20 token, IStrategy strategy, uint256 shares);

    /// @notice Emitted when `thirdPartyTransfersForbidden` is updated for a strategy and value by the owner
    event UpdatedThirdPartyTransfersForbidden(IStrategy strategy, bool value);

    /// @notice Emitted when the `strategyWhitelister` is changed
    event StrategyWhitelisterChanged(address previousAddress, address newAddress);

    /// @notice Emitted when a strategy is added to the approved list of strategies for deposit
    event StrategyAddedToDepositWhitelist(IStrategy strategy);

    /// @notice Emitted when a strategy is removed from the approved list of strategies for deposit
    event StrategyRemovedFromDepositWhitelist(IStrategy strategy);

    /**
     * @notice Deposits `amount` of `token` into the specified `strategy`, with the resultant shares credited to `msg.sender`
     * @param strategy is the specified strategy where deposit is to be made,
     * @param token is the denomination in which the deposit is to be made,
     * @param amount is the amount of token to be deposited in the strategy by the staker
     * @return shares The amount of new shares in the `strategy` created as part of the action.
     * @dev The `msg.sender` must have previously approved this contract to transfer at least `amount` of `token` on their behalf.
     * @dev Cannot be called by an address that is 'frozen' (this function will revert if the `msg.sender` is frozen).
     *
     * WARNING: Depositing tokens that allow reentrancy (eg. ERC-777) into a strategy is not recommended.  This can lead to attack vectors
     *          where the token balance and corresponding strategy shares are not in sync upon reentrancy.
     */
    function depositIntoStrategy(IStrategy strategy, IERC20 token, uint256 amount) external returns (uint256 shares);

    /**
     * @notice Used for depositing an asset into the specified strategy with the resultant shares credited to `staker`,
     * who must sign off on the action.
     * Note that the assets are transferred out/from the `msg.sender`, not from the `staker`; this function is explicitly designed
     * purely to help one address deposit 'for' another.
     * @param strategy is the specified strategy where deposit is to be made,
     * @param token is the denomination in which the deposit is to be made,
     * @param amount is the amount of token to be deposited in the strategy by the staker
     * @param staker the staker that the deposited assets will be credited to
     * @param expiry the timestamp at which the signature expires
     * @param signature is a valid signature from the `staker`. either an ECDSA signature if the `staker` is an EOA, or data to forward
     * following EIP-1271 if the `staker` is a contract
     * @return shares The amount of new shares in the `strategy` created as part of the action.
     * @dev The `msg.sender` must have previously approved this contract to transfer at least `amount` of `token` on their behalf.
     * @dev A signature is required for this function to eliminate the possibility of griefing attacks, specifically those
     * targeting stakers who may be attempting to undelegate.
     * @dev Cannot be called if thirdPartyTransfersForbidden is set to true for this strategy
     *
     *  WARNING: Depositing tokens that allow reentrancy (eg. ERC-777) into a strategy is not recommended.  This can lead to attack vectors
     *          where the token balance and corresponding strategy shares are not in sync upon reentrancy
     */
    function depositIntoStrategyWithSignature(
        IStrategy strategy,
        IERC20 token,
        uint256 amount,
        address staker,
        uint256 expiry,
        bytes memory signature
    ) external returns (uint256 shares);

    /// @notice Used by the DelegationManager to remove a Staker's shares from a particular strategy when entering the withdrawal queue
    function removeShares(address staker, IStrategy strategy, uint256 shares) external;

    /// @notice Used by the DelegationManager to award a Staker some shares that have passed through the withdrawal queue
    function addShares(address staker, IERC20 token, IStrategy strategy, uint256 shares) external;
    
    /// @notice Used by the DelegationManager to convert withdrawn shares to tokens and send them to a recipient
    function withdrawSharesAsTokens(address recipient, IStrategy strategy, uint256 shares, IERC20 token) external;

    /// @notice Returns the current shares of `user` in `strategy`
    function stakerStrategyShares(address user, IStrategy strategy) external view returns (uint256 shares);

    /**
     * @notice Get all details on the staker's deposits and corresponding shares
     * @return (staker's strategies, shares in these strategies)
     */
    function getDeposits(address staker) external view returns (IStrategy[] memory, uint256[] memory);

    /// @notice Simple getter function that returns `stakerStrategyList[staker].length`.
    function stakerStrategyListLength(address staker) external view returns (uint256);

    /**
     * @notice Owner-only function that adds the provided Strategies to the 'whitelist' of strategies that stakers can deposit into
     * @param strategiesToWhitelist Strategies that will be added to the `strategyIsWhitelistedForDeposit` mapping (if they aren't in it already)
     * @param thirdPartyTransfersForbiddenValues bool values to set `thirdPartyTransfersForbidden` to for each strategy
     */
    function addStrategiesToDepositWhitelist(
        IStrategy[] calldata strategiesToWhitelist,
        bool[] calldata thirdPartyTransfersForbiddenValues
    ) external;

    /**
     * @notice Owner-only function that removes the provided Strategies from the 'whitelist' of strategies that stakers can deposit into
     * @param strategiesToRemoveFromWhitelist Strategies that will be removed to the `strategyIsWhitelistedForDeposit` mapping (if they are in it)
     */
    function removeStrategiesFromDepositWhitelist(IStrategy[] calldata strategiesToRemoveFromWhitelist) external;

    /// @notice Returns the single, central Delegation contract of EigenLayer
    function delegation() external view returns (IDelegationManager);

    /// @notice Returns the single, central Slasher contract of EigenLayer
    function slasher() external view returns (ISlasher);

    /// @notice Returns the EigenPodManager contract of EigenLayer
    function eigenPodManager() external view returns (IEigenPodManager);

    /// @notice Returns the address of the `strategyWhitelister`
    function strategyWhitelister() external view returns (address);

    /**
     * @notice Returns bool for whether or not `strategy` enables credit transfers. i.e enabling
     * depositIntoStrategyWithSignature calls or queueing withdrawals to a different address than the staker.
     */
    function thirdPartyTransfersForbidden(IStrategy strategy) external view returns (bool);

// LIMITED BACKWARDS-COMPATIBILITY FOR DEPRECATED FUNCTIONALITY
    // packed struct for queued withdrawals; helps deal with stack-too-deep errors
    struct DeprecatedStruct_WithdrawerAndNonce {
        address withdrawer;
        uint96 nonce;
    }

    /**
     * Struct type used to specify an existing queued withdrawal. Rather than storing the entire struct, only a hash is stored.
     * In functions that operate on existing queued withdrawals -- e.g. `startQueuedWithdrawalWaitingPeriod` or `completeQueuedWithdrawal`,
     * the data is resubmitted and the hash of the submitted data is computed by `calculateWithdrawalRoot` and checked against the
     * stored hash in order to confirm the integrity of the submitted data.
     */
    struct DeprecatedStruct_QueuedWithdrawal {
        IStrategy[] strategies;
        uint256[] shares;
        address staker;
        DeprecatedStruct_WithdrawerAndNonce withdrawerAndNonce;
        uint32 withdrawalStartBlock;
        address delegatedAddress;
    }

    function migrateQueuedWithdrawal(DeprecatedStruct_QueuedWithdrawal memory queuedWithdrawal) external returns (bool, bytes32);

    function calculateWithdrawalRoot(DeprecatedStruct_QueuedWithdrawal memory queuedWithdrawal) external pure returns (bytes32);
}

File 59 of 62 : BeaconChainProofs.sol
// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.0;

import "./Merkle.sol";
import "../libraries/Endian.sol";

//Utility library for parsing and PHASE0 beacon chain block headers
//SSZ Spec: https://github.com/ethereum/consensus-specs/blob/dev/ssz/simple-serialize.md#merkleization
//BeaconBlockHeader Spec: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#beaconblockheader
//BeaconState Spec: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#beaconstate
library BeaconChainProofs {
    // constants are the number of fields and the heights of the different merkle trees used in merkleizing beacon chain containers
    uint256 internal constant BEACON_BLOCK_HEADER_FIELD_TREE_HEIGHT = 3;

    uint256 internal constant BEACON_BLOCK_BODY_FIELD_TREE_HEIGHT = 4;

    uint256 internal constant BEACON_STATE_FIELD_TREE_HEIGHT = 5;

    uint256 internal constant VALIDATOR_FIELD_TREE_HEIGHT = 3;

    //Note: changed in the deneb hard fork from 4->5
    uint256 internal constant EXECUTION_PAYLOAD_HEADER_FIELD_TREE_HEIGHT_DENEB = 5;
    uint256 internal constant EXECUTION_PAYLOAD_HEADER_FIELD_TREE_HEIGHT_CAPELLA = 4;

    // SLOTS_PER_HISTORICAL_ROOT = 2**13, so tree height is 13
    uint256 internal constant BLOCK_ROOTS_TREE_HEIGHT = 13;

    //HISTORICAL_ROOTS_LIMIT = 2**24, so tree height is 24
    uint256 internal constant HISTORICAL_SUMMARIES_TREE_HEIGHT = 24;

    //Index of block_summary_root in historical_summary container
    uint256 internal constant BLOCK_SUMMARY_ROOT_INDEX = 0;

    // tree height for hash tree of an individual withdrawal container
    uint256 internal constant WITHDRAWAL_FIELD_TREE_HEIGHT = 2;

    uint256 internal constant VALIDATOR_TREE_HEIGHT = 40;

    // MAX_WITHDRAWALS_PER_PAYLOAD = 2**4, making tree height = 4
    uint256 internal constant WITHDRAWALS_TREE_HEIGHT = 4;

    //in beacon block body https://github.com/ethereum/consensus-specs/blob/dev/specs/capella/beacon-chain.md#beaconblockbody
    uint256 internal constant EXECUTION_PAYLOAD_INDEX = 9;

    // in beacon block header https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#beaconblockheader
    uint256 internal constant SLOT_INDEX = 0;
    uint256 internal constant STATE_ROOT_INDEX = 3;
    uint256 internal constant BODY_ROOT_INDEX = 4;
    // in beacon state https://github.com/ethereum/consensus-specs/blob/dev/specs/capella/beacon-chain.md#beaconstate
    uint256 internal constant VALIDATOR_TREE_ROOT_INDEX = 11;
    uint256 internal constant HISTORICAL_SUMMARIES_INDEX = 27;

    // in validator https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#validator
    uint256 internal constant VALIDATOR_PUBKEY_INDEX = 0;
    uint256 internal constant VALIDATOR_WITHDRAWAL_CREDENTIALS_INDEX = 1;
    uint256 internal constant VALIDATOR_BALANCE_INDEX = 2;
    uint256 internal constant VALIDATOR_WITHDRAWABLE_EPOCH_INDEX = 7;

    // in execution payload header
    uint256 internal constant TIMESTAMP_INDEX = 9;

    //in execution payload
    uint256 internal constant WITHDRAWALS_INDEX = 14;

    // in withdrawal
    uint256 internal constant WITHDRAWAL_VALIDATOR_INDEX_INDEX = 1;
    uint256 internal constant WITHDRAWAL_VALIDATOR_AMOUNT_INDEX = 3;

    //Misc Constants

    /// @notice The number of slots each epoch in the beacon chain
    uint64 internal constant SLOTS_PER_EPOCH = 32;

    /// @notice The number of seconds in a slot in the beacon chain
    uint64 internal constant SECONDS_PER_SLOT = 12;

    /// @notice Number of seconds per epoch: 384 == 32 slots/epoch * 12 seconds/slot 
    uint64 internal constant SECONDS_PER_EPOCH = SLOTS_PER_EPOCH * SECONDS_PER_SLOT;

    bytes8 internal constant UINT64_MASK = 0xffffffffffffffff;

    /// @notice This struct contains the merkle proofs and leaves needed to verify a partial/full withdrawal
    struct WithdrawalProof {
        bytes withdrawalProof;
        bytes slotProof;
        bytes executionPayloadProof;
        bytes timestampProof;
        bytes historicalSummaryBlockRootProof;
        uint64 blockRootIndex;
        uint64 historicalSummaryIndex;
        uint64 withdrawalIndex;
        bytes32 blockRoot;
        bytes32 slotRoot;
        bytes32 timestampRoot;
        bytes32 executionPayloadRoot;
    }

    /// @notice This struct contains the root and proof for verifying the state root against the oracle block root
    struct StateRootProof {
        bytes32 beaconStateRoot;
        bytes proof;
    }

    /**
     * @notice This function verifies merkle proofs of the fields of a certain validator against a beacon chain state root
     * @param validatorIndex the index of the proven validator
     * @param beaconStateRoot is the beacon chain state root to be proven against.
     * @param validatorFieldsProof is the data used in proving the validator's fields
     * @param validatorFields the claimed fields of the validator
     */
    function verifyValidatorFields(
        bytes32 beaconStateRoot,
        bytes32[] calldata validatorFields,
        bytes calldata validatorFieldsProof,
        uint40 validatorIndex
    ) internal view {
        require(
            validatorFields.length == 2 ** VALIDATOR_FIELD_TREE_HEIGHT,
            "BeaconChainProofs.verifyValidatorFields: Validator fields has incorrect length"
        );

        /**
         * Note: the length of the validator merkle proof is BeaconChainProofs.VALIDATOR_TREE_HEIGHT + 1.
         * There is an additional layer added by hashing the root with the length of the validator list
         */
        require(
            validatorFieldsProof.length == 32 * ((VALIDATOR_TREE_HEIGHT + 1) + BEACON_STATE_FIELD_TREE_HEIGHT),
            "BeaconChainProofs.verifyValidatorFields: Proof has incorrect length"
        );
        uint256 index = (VALIDATOR_TREE_ROOT_INDEX << (VALIDATOR_TREE_HEIGHT + 1)) | uint256(validatorIndex);
        // merkleize the validatorFields to get the leaf to prove
        bytes32 validatorRoot = Merkle.merkleizeSha256(validatorFields);

        // verify the proof of the validatorRoot against the beaconStateRoot
        require(
            Merkle.verifyInclusionSha256({
                proof: validatorFieldsProof,
                root: beaconStateRoot,
                leaf: validatorRoot,
                index: index
            }),
            "BeaconChainProofs.verifyValidatorFields: Invalid merkle proof"
        );
    }

    /**
     * @notice This function verifies the latestBlockHeader against the state root. the latestBlockHeader is
     * a tracked in the beacon state.
     * @param beaconStateRoot is the beacon chain state root to be proven against.
     * @param stateRootProof is the provided merkle proof
     * @param latestBlockRoot is hashtree root of the latest block header in the beacon state
     */
    function verifyStateRootAgainstLatestBlockRoot(
        bytes32 latestBlockRoot,
        bytes32 beaconStateRoot,
        bytes calldata stateRootProof
    ) internal view {
        require(
            stateRootProof.length == 32 * (BEACON_BLOCK_HEADER_FIELD_TREE_HEIGHT),
            "BeaconChainProofs.verifyStateRootAgainstLatestBlockRoot: Proof has incorrect length"
        );
        //Next we verify the slot against the blockRoot
        require(
            Merkle.verifyInclusionSha256({
                proof: stateRootProof,
                root: latestBlockRoot,
                leaf: beaconStateRoot,
                index: STATE_ROOT_INDEX
            }),
            "BeaconChainProofs.verifyStateRootAgainstLatestBlockRoot: Invalid latest block header root merkle proof"
        );
    }

    /**
     * @notice This function verifies the slot and the withdrawal fields for a given withdrawal
     * @param withdrawalProof is the provided set of merkle proofs
     * @param withdrawalFields is the serialized withdrawal container to be proven
     */
    function verifyWithdrawal(
        bytes32 beaconStateRoot,
        bytes32[] calldata withdrawalFields,
        WithdrawalProof calldata withdrawalProof,
        uint64 denebForkTimestamp
    ) internal view {
        require(
            withdrawalFields.length == 2 ** WITHDRAWAL_FIELD_TREE_HEIGHT,
            "BeaconChainProofs.verifyWithdrawal: withdrawalFields has incorrect length"
        );

        require(
            withdrawalProof.blockRootIndex < 2 ** BLOCK_ROOTS_TREE_HEIGHT,
            "BeaconChainProofs.verifyWithdrawal: blockRootIndex is too large"
        );
        require(
            withdrawalProof.withdrawalIndex < 2 ** WITHDRAWALS_TREE_HEIGHT,
            "BeaconChainProofs.verifyWithdrawal: withdrawalIndex is too large"
        );

        require(
            withdrawalProof.historicalSummaryIndex < 2 ** HISTORICAL_SUMMARIES_TREE_HEIGHT,
            "BeaconChainProofs.verifyWithdrawal: historicalSummaryIndex is too large"
        );

        //Note: post deneb hard fork, the number of exection payload header fields increased from 15->17, adding an extra level to the tree height
        uint256 executionPayloadHeaderFieldTreeHeight = (getWithdrawalTimestamp(withdrawalProof) < denebForkTimestamp) ? EXECUTION_PAYLOAD_HEADER_FIELD_TREE_HEIGHT_CAPELLA : EXECUTION_PAYLOAD_HEADER_FIELD_TREE_HEIGHT_DENEB;
        require(
            withdrawalProof.withdrawalProof.length ==
                32 * (executionPayloadHeaderFieldTreeHeight + WITHDRAWALS_TREE_HEIGHT + 1),
            "BeaconChainProofs.verifyWithdrawal: withdrawalProof has incorrect length"
        );
        require(
            withdrawalProof.executionPayloadProof.length ==
                32 * (BEACON_BLOCK_HEADER_FIELD_TREE_HEIGHT + BEACON_BLOCK_BODY_FIELD_TREE_HEIGHT),
            "BeaconChainProofs.verifyWithdrawal: executionPayloadProof has incorrect length"
        );
        require(
            withdrawalProof.slotProof.length == 32 * (BEACON_BLOCK_HEADER_FIELD_TREE_HEIGHT),
            "BeaconChainProofs.verifyWithdrawal: slotProof has incorrect length"
        );
        require(
            withdrawalProof.timestampProof.length == 32 * (executionPayloadHeaderFieldTreeHeight),
            "BeaconChainProofs.verifyWithdrawal: timestampProof has incorrect length"
        );

        require(
            withdrawalProof.historicalSummaryBlockRootProof.length ==
                32 *
                    (BEACON_STATE_FIELD_TREE_HEIGHT +
                        (HISTORICAL_SUMMARIES_TREE_HEIGHT + 1) +
                        1 +
                        (BLOCK_ROOTS_TREE_HEIGHT)),
            "BeaconChainProofs.verifyWithdrawal: historicalSummaryBlockRootProof has incorrect length"
        );
        /**
         * Note: Here, the "1" in "1 + (BLOCK_ROOTS_TREE_HEIGHT)" signifies that extra step of choosing the "block_root_summary" within the individual
         * "historical_summary". Everywhere else it signifies merkelize_with_mixin, where the length of an array is hashed with the root of the array,
         * but not here.
         */
        uint256 historicalBlockHeaderIndex = (HISTORICAL_SUMMARIES_INDEX <<
            ((HISTORICAL_SUMMARIES_TREE_HEIGHT + 1) + 1 + (BLOCK_ROOTS_TREE_HEIGHT))) |
            (uint256(withdrawalProof.historicalSummaryIndex) << (1 + (BLOCK_ROOTS_TREE_HEIGHT))) |
            (BLOCK_SUMMARY_ROOT_INDEX << (BLOCK_ROOTS_TREE_HEIGHT)) |
            uint256(withdrawalProof.blockRootIndex);

        require(
            Merkle.verifyInclusionSha256({
                proof: withdrawalProof.historicalSummaryBlockRootProof,
                root: beaconStateRoot,
                leaf: withdrawalProof.blockRoot,
                index: historicalBlockHeaderIndex
            }),
            "BeaconChainProofs.verifyWithdrawal: Invalid historicalsummary merkle proof"
        );

        //Next we verify the slot against the blockRoot
        require(
            Merkle.verifyInclusionSha256({
                proof: withdrawalProof.slotProof,
                root: withdrawalProof.blockRoot,
                leaf: withdrawalProof.slotRoot,
                index: SLOT_INDEX
            }),
            "BeaconChainProofs.verifyWithdrawal: Invalid slot merkle proof"
        );

        {
            // Next we verify the executionPayloadRoot against the blockRoot
            uint256 executionPayloadIndex = (BODY_ROOT_INDEX << (BEACON_BLOCK_BODY_FIELD_TREE_HEIGHT)) |
                EXECUTION_PAYLOAD_INDEX;
            require(
                Merkle.verifyInclusionSha256({
                    proof: withdrawalProof.executionPayloadProof,
                    root: withdrawalProof.blockRoot,
                    leaf: withdrawalProof.executionPayloadRoot,
                    index: executionPayloadIndex
                }),
                "BeaconChainProofs.verifyWithdrawal: Invalid executionPayload merkle proof"
            );
        }

        // Next we verify the timestampRoot against the executionPayload root
        require(
            Merkle.verifyInclusionSha256({
                proof: withdrawalProof.timestampProof,
                root: withdrawalProof.executionPayloadRoot,
                leaf: withdrawalProof.timestampRoot,
                index: TIMESTAMP_INDEX
            }),
            "BeaconChainProofs.verifyWithdrawal: Invalid timestamp merkle proof"
        );

        {
            /**
             * Next we verify the withdrawal fields against the executionPayloadRoot:
             * First we compute the withdrawal_index, then we merkleize the 
             * withdrawalFields container to calculate the withdrawalRoot.
             *
             * Note: Merkleization of the withdrawals root tree uses MerkleizeWithMixin, i.e., the length of the array is hashed with the root of
             * the array.  Thus we shift the WITHDRAWALS_INDEX over by WITHDRAWALS_TREE_HEIGHT + 1 and not just WITHDRAWALS_TREE_HEIGHT.
             */
            uint256 withdrawalIndex = (WITHDRAWALS_INDEX << (WITHDRAWALS_TREE_HEIGHT + 1)) |
                uint256(withdrawalProof.withdrawalIndex);
            bytes32 withdrawalRoot = Merkle.merkleizeSha256(withdrawalFields);
            require(
                Merkle.verifyInclusionSha256({
                    proof: withdrawalProof.withdrawalProof,
                    root: withdrawalProof.executionPayloadRoot,
                    leaf: withdrawalRoot,
                    index: withdrawalIndex
                }),
                "BeaconChainProofs.verifyWithdrawal: Invalid withdrawal merkle proof"
            );
        }
    }

    /**
     * @notice This function replicates the ssz hashing of a validator's pubkey, outlined below:
     *  hh := ssz.NewHasher()
     *  hh.PutBytes(validatorPubkey[:])
     *  validatorPubkeyHash := hh.Hash()
     *  hh.Reset()
     */
    function hashValidatorBLSPubkey(bytes memory validatorPubkey) internal pure returns (bytes32 pubkeyHash) {
        require(validatorPubkey.length == 48, "Input should be 48 bytes in length");
        return sha256(abi.encodePacked(validatorPubkey, bytes16(0)));
    }

    /**
     * @dev Retrieve the withdrawal timestamp
     */
    function getWithdrawalTimestamp(WithdrawalProof memory withdrawalProof) internal pure returns (uint64) {
        return
            Endian.fromLittleEndianUint64(withdrawalProof.timestampRoot);
    }

    /**
     * @dev Converts the withdrawal's slot to an epoch
     */
    function getWithdrawalEpoch(WithdrawalProof memory withdrawalProof) internal pure returns (uint64) {
        return
            Endian.fromLittleEndianUint64(withdrawalProof.slotRoot) / SLOTS_PER_EPOCH;
    }

    /**
     * Indices for validator fields (refer to consensus specs):
     * 0: pubkey
     * 1: withdrawal credentials
     * 2: effective balance
     * 3: slashed?
     * 4: activation elligibility epoch
     * 5: activation epoch
     * 6: exit epoch
     * 7: withdrawable epoch
     */

    /**
     * @dev Retrieves a validator's pubkey hash
     */
    function getPubkeyHash(bytes32[] memory validatorFields) internal pure returns (bytes32) {
        return 
            validatorFields[VALIDATOR_PUBKEY_INDEX];
    }

    function getWithdrawalCredentials(bytes32[] memory validatorFields) internal pure returns (bytes32) {
        return
            validatorFields[VALIDATOR_WITHDRAWAL_CREDENTIALS_INDEX];
    }

    /**
     * @dev Retrieves a validator's effective balance (in gwei)
     */
    function getEffectiveBalanceGwei(bytes32[] memory validatorFields) internal pure returns (uint64) {
        return 
            Endian.fromLittleEndianUint64(validatorFields[VALIDATOR_BALANCE_INDEX]);
    }

    /**
     * @dev Retrieves a validator's withdrawable epoch
     */
    function getWithdrawableEpoch(bytes32[] memory validatorFields) internal pure returns (uint64) {
        return 
            Endian.fromLittleEndianUint64(validatorFields[VALIDATOR_WITHDRAWABLE_EPOCH_INDEX]);
    }

    /**
     * Indices for withdrawal fields (refer to consensus specs):
     * 0: withdrawal index
     * 1: validator index
     * 2: execution address
     * 3: withdrawal amount
     */

    /**
     * @dev Retrieves a withdrawal's validator index
     */
    function getValidatorIndex(bytes32[] memory withdrawalFields) internal pure returns (uint40) {
        return 
            uint40(Endian.fromLittleEndianUint64(withdrawalFields[WITHDRAWAL_VALIDATOR_INDEX_INDEX]));
    }

    /**
     * @dev Retrieves a withdrawal's withdrawal amount (in gwei)
     */
    function getWithdrawalAmountGwei(bytes32[] memory withdrawalFields) internal pure returns (uint64) {
        return
            Endian.fromLittleEndianUint64(withdrawalFields[WITHDRAWAL_VALIDATOR_AMOUNT_INDEX]);
    }
}

File 60 of 62 : Endian.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

library Endian {
    /**
     * @notice Converts a little endian-formatted uint64 to a big endian-formatted uint64
     * @param lenum little endian-formatted uint64 input, provided as 'bytes32' type
     * @return n The big endian-formatted uint64
     * @dev Note that the input is formatted as a 'bytes32' type (i.e. 256 bits), but it is immediately truncated to a uint64 (i.e. 64 bits)
     * through a right-shift/shr operation.
     */
    function fromLittleEndianUint64(bytes32 lenum) internal pure returns (uint64 n) {
        // the number needs to be stored in little-endian encoding (ie in bytes 0-8)
        n = uint64(uint256(lenum >> 192));
        return
            (n >> 56) |
            ((0x00FF000000000000 & n) >> 40) |
            ((0x0000FF0000000000 & n) >> 24) |
            ((0x000000FF00000000 & n) >> 8) |
            ((0x00000000FF000000 & n) << 8) |
            ((0x0000000000FF0000 & n) << 24) |
            ((0x000000000000FF00 & n) << 40) |
            ((0x00000000000000FF & n) << 56);
    }
}

File 61 of 62 : Merkle.sol
// SPDX-License-Identifier: MIT
// Adapted from OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/MerkleProof.sol)

pragma solidity ^0.8.0;

/**
 * @dev These functions deal with verification of Merkle Tree proofs.
 *
 * The tree and the proofs can be generated using our
 * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
 * You will find a quickstart guide in the readme.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the merkle tree could be reinterpreted as a leaf value.
 * OpenZeppelin's JavaScript library generates merkle trees that are safe
 * against this attack out of the box.
 */
library Merkle {
    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. The tree is built assuming `leaf` is
     * the 0 indexed `index`'th leaf from the bottom left of the tree.
     *
     * Note this is for a Merkle tree using the keccak/sha3 hash function
     */
    function verifyInclusionKeccak(
        bytes memory proof,
        bytes32 root,
        bytes32 leaf,
        uint256 index
    ) internal pure returns (bool) {
        return processInclusionProofKeccak(proof, leaf, index) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. The tree is built assuming `leaf` is
     * the 0 indexed `index`'th leaf from the bottom left of the tree.
     *
     * _Available since v4.4._
     *
     * Note this is for a Merkle tree using the keccak/sha3 hash function
     */
    function processInclusionProofKeccak(
        bytes memory proof,
        bytes32 leaf,
        uint256 index
    ) internal pure returns (bytes32) {
        require(
            proof.length != 0 && proof.length % 32 == 0,
            "Merkle.processInclusionProofKeccak: proof length should be a non-zero multiple of 32"
        );
        bytes32 computedHash = leaf;
        for (uint256 i = 32; i <= proof.length; i += 32) {
            if (index % 2 == 0) {
                // if ith bit of index is 0, then computedHash is a left sibling
                assembly {
                    mstore(0x00, computedHash)
                    mstore(0x20, mload(add(proof, i)))
                    computedHash := keccak256(0x00, 0x40)
                    index := div(index, 2)
                }
            } else {
                // if ith bit of index is 1, then computedHash is a right sibling
                assembly {
                    mstore(0x00, mload(add(proof, i)))
                    mstore(0x20, computedHash)
                    computedHash := keccak256(0x00, 0x40)
                    index := div(index, 2)
                }
            }
        }
        return computedHash;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. The tree is built assuming `leaf` is
     * the 0 indexed `index`'th leaf from the bottom left of the tree.
     *
     * Note this is for a Merkle tree using the sha256 hash function
     */
    function verifyInclusionSha256(
        bytes memory proof,
        bytes32 root,
        bytes32 leaf,
        uint256 index
    ) internal view returns (bool) {
        return processInclusionProofSha256(proof, leaf, index) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. The tree is built assuming `leaf` is
     * the 0 indexed `index`'th leaf from the bottom left of the tree.
     *
     * _Available since v4.4._
     *
     * Note this is for a Merkle tree using the sha256 hash function
     */
    function processInclusionProofSha256(
        bytes memory proof,
        bytes32 leaf,
        uint256 index
    ) internal view returns (bytes32) {
        require(
            proof.length != 0 && proof.length % 32 == 0,
            "Merkle.processInclusionProofSha256: proof length should be a non-zero multiple of 32"
        );
        bytes32[1] memory computedHash = [leaf];
        for (uint256 i = 32; i <= proof.length; i += 32) {
            if (index % 2 == 0) {
                // if ith bit of index is 0, then computedHash is a left sibling
                assembly {
                    mstore(0x00, mload(computedHash))
                    mstore(0x20, mload(add(proof, i)))
                    if iszero(staticcall(sub(gas(), 2000), 2, 0x00, 0x40, computedHash, 0x20)) {
                        revert(0, 0)
                    }
                    index := div(index, 2)
                }
            } else {
                // if ith bit of index is 1, then computedHash is a right sibling
                assembly {
                    mstore(0x00, mload(add(proof, i)))
                    mstore(0x20, mload(computedHash))
                    if iszero(staticcall(sub(gas(), 2000), 2, 0x00, 0x40, computedHash, 0x20)) {
                        revert(0, 0)
                    }
                    index := div(index, 2)
                }
            }
        }
        return computedHash[0];
    }

    /**
     @notice this function returns the merkle root of a tree created from a set of leaves using sha256 as its hash function
     @param leaves the leaves of the merkle tree
     @return The computed Merkle root of the tree.
     @dev A pre-condition to this function is that leaves.length is a power of two.  If not, the function will merkleize the inputs incorrectly.
     */
    function merkleizeSha256(bytes32[] memory leaves) internal pure returns (bytes32) {
        //there are half as many nodes in the layer above the leaves
        uint256 numNodesInLayer = leaves.length / 2;
        //create a layer to store the internal nodes
        bytes32[] memory layer = new bytes32[](numNodesInLayer);
        //fill the layer with the pairwise hashes of the leaves
        for (uint256 i = 0; i < numNodesInLayer; i++) {
            layer[i] = sha256(abi.encodePacked(leaves[2 * i], leaves[2 * i + 1]));
        }
        //the next layer above has half as many nodes
        numNodesInLayer /= 2;
        //while we haven't computed the root
        while (numNodesInLayer != 0) {
            //overwrite the first numNodesInLayer nodes in layer with the pairwise hashes of their children
            for (uint256 i = 0; i < numNodesInLayer; i++) {
                layer[i] = sha256(abi.encodePacked(layer[2 * i], layer[2 * i + 1]));
            }
            //the next layer above has half as many nodes
            numNodesInLayer /= 2;
        }
        //the first node in the layer is the root
        return layer[0];
    }
}

File 62 of 62 : IPoRAddresses.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;

/**
 * @title Chainlink Proof-of-Reserve address list interface.
 * @notice This interface enables Chainlink nodes to get the list addresses to be used in a PoR feed. A single
 * contract that implements this interface can only store an address list for a single PoR feed.
 * @dev All functions in this interface are expected to be called off-chain, so gas usage is not a big concern.
 * This makes it possible to store addresses in optimized data types and convert them to human-readable strings
 * in `getPoRAddressList()`.
 */
interface IPoRAddresses {
  /**
   * @notice Get total number of addresses in the list.
   * @return The array length
   */
  function getPoRAddressListLength() external view returns (uint256);

  /**
   * @notice Get a batch of human-readable addresses from the address list.
   * @dev Due to limitations of gas usage in off-chain calls, we need to support fetching the addresses in batches.
   * EVM addresses need to be converted to human-readable strings. The address strings need to be in the same format
   * that would be used when querying the balance of that address.
   * @param startIndex The index of the first address in the batch.
   * @param endIndex The index of the last address in the batch. If `endIndex > getPoRAddressListLength()-1`,
   * endIndex need to default to `getPoRAddressListLength()-1`. If `endIndex < startIndex`, the result would be an
   * empty array.
   * @return Array of addresses as strings.
   */
  function getPoRAddressList(
    uint256 startIndex,
    uint256 endIndex
  ) external view returns (string[] memory);
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "metadata": {
    "useLiteralContent": true
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"BotMethodsPaused","type":"error"},{"inputs":[],"name":"CannotBeZeroAddress","type":"error"},{"inputs":[],"name":"CannotComputeReferencePriceWithZeroRswETHSupply","type":"error"},{"inputs":[],"name":"InvalidMethodCall","type":"error"},{"inputs":[],"name":"NoTokensToWithdraw","type":"error"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"}],"name":"PRBMath_MulDiv18_Overflow","type":"error"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"},{"internalType":"uint256","name":"denominator","type":"uint256"}],"name":"PRBMath_MulDiv_Overflow","type":"error"},{"inputs":[],"name":"ProcessWithdrawalsExitingETHMustMonotonicallyIncrease","type":"error"},{"inputs":[],"name":"ProcessWithdrawalsTotalETHExitedMismatch","type":"error"},{"inputs":[{"internalType":"uint256","name":"referencePriceDiff","type":"uint256"},{"internalType":"uint256","name":"maximumReferencePriceDiffPercentage","type":"uint256"}],"name":"ReferencePriceDiffTooHigh","type":"error"},{"inputs":[],"name":"RepriceBlockAtSnapshotDidNotIncrease","type":"error"},{"inputs":[{"internalType":"uint256","name":"snapshotStalenessInBlocks","type":"uint256"},{"internalType":"uint256","name":"maximumRepriceBlockAtSnapshotStaleness","type":"uint256"}],"name":"RepriceBlockAtSnapshotIsStale","type":"error"},{"inputs":[{"internalType":"uint256","name":"snapshotBlockNumber","type":"uint256"},{"internalType":"uint256","name":"currentBlockNumber","type":"uint256"}],"name":"RepriceBlockAtSnapshotTooHigh","type":"error"},{"inputs":[{"internalType":"uint256","name":"blockOfLastSnapshotSupplied","type":"uint256"},{"internalType":"uint256","name":"blockOfLastSnapshotOnChain","type":"uint256"}],"name":"RepriceBlockOfLastSnapshotMismatch","type":"error"},{"inputs":[],"name":"RepriceSlotDidNotIncrease","type":"error"},{"inputs":[],"name":"RepriceTimestampDidNotIncrease","type":"error"},{"inputs":[{"internalType":"uint256","name":"snapshotTimestamp","type":"uint256"},{"internalType":"uint256","name":"blockTimestamp","type":"uint256"}],"name":"RepriceTimestampTooHigh","type":"error"},{"inputs":[{"internalType":"uint256","name":"v3ReservesExternalPoRDiff","type":"uint256"},{"internalType":"uint256","name":"maximumV3ReservesExternalPoRDiff","type":"uint256"}],"name":"RepriceV3ReservesExternalPoRDifferentialTooHigh","type":"error"},{"inputs":[{"internalType":"uint256","name":"latestRoundDataTime","type":"uint256"},{"internalType":"uint256","name":"secondsSinceExpiry","type":"uint256"}],"name":"RoundDataIsStale","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldAddress","type":"address"},{"indexed":false,"internalType":"address","name":"newAddress","type":"address"}],"name":"ExternalV3ReservesPoROracleAddressUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_oldMaximumReferencePriceDiffPercentage","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_newMaximumReferencePriceDiffPercentage","type":"uint256"}],"name":"MaximumReferencePriceDiffPercentageUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_oldMaximumRepriceBlockAtSnapshotStaleness","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_newMaximumRepriceBlockAtSnapshotStaleness","type":"uint256"}],"name":"MaximumRepriceBlockAtSnapshotStalenessUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_oldMaximumRepriceV3ReservesExternalPoRDiffPercentage","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_newMaximumRepriceV3ReservesExternalPoRDiffPercentage","type":"uint256"}],"name":"MaximumRepriceV3ReservesExternalPoRDiffPercentageUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_oldMaximumRoundDataStalenessTime","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_newMaximumRoundDataStalenessTime","type":"uint256"}],"name":"MaximumRoundDataStalenessTimeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"blockAtSnapshot","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"elBalance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"clV3Balance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"clV2Balance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"transitioningBalance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newETHReserves","type":"uint256"}],"name":"ReservesRecorded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"blockAtSnapshot","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"elBalance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"clV3Balance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"clV2Balance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"transitioningBalance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newETHReserves","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"reserveAssets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"exitingETH","type":"uint256"}],"name":"ReservesRecordedV2","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"blockAtSnapshot","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"blockOfLastSnapshot","type":"uint256"},{"indexed":false,"internalType":"int256","name":"reservesChange","type":"int256"},{"indexed":false,"internalType":"uint256","name":"ethDepositsChange","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rewardsPayableForFees","type":"uint256"}],"name":"RewardsCalculated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"blockAtSnapshot","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"blockOfLastSnapshot","type":"uint256"},{"indexed":false,"internalType":"int256","name":"reserveAssetsChange","type":"int256"},{"indexed":false,"internalType":"uint256","name":"ethDepositsChange","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rewardsPayableForFees","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"ethExitedChange","type":"uint256"}],"name":"RewardsCalculatedV2","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"blockNumber","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"slot","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"reportTimestamp","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalETHDeposited","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rswETHTotalSupply","type":"uint256"}],"name":"SnapshotSubmitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"blockNumber","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"slot","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"reportTimestamp","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalETHDeposited","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rswETHTotalSupply","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalETHExited","type":"uint256"}],"name":"SnapshotSubmittedV2","type":"event"},{"stateMutability":"nonpayable","type":"fallback"},{"inputs":[],"name":"AccessControlManager","outputs":[{"internalType":"contract IAccessControlManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ExternalV3ReservesPoROracle","outputs":[{"internalType":"contract AggregatorV3Interface","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"components":[{"internalType":"uint256","name":"blockNumber","type":"uint256"},{"internalType":"uint256","name":"blockOfLastSnapshot","type":"uint256"},{"internalType":"uint256","name":"slot","type":"uint256"},{"internalType":"uint256","name":"timestamp","type":"uint256"}],"internalType":"struct RepriceSnapshotMeta","name":"meta","type":"tuple"},{"components":[{"internalType":"uint256","name":"totalETHDeposited","type":"uint256"},{"internalType":"uint256","name":"rswETHTotalSupply","type":"uint256"},{"components":[{"internalType":"uint256","name":"executionLayer","type":"uint256"},{"internalType":"uint256","name":"consensusLayerV3Validators","type":"uint256"},{"internalType":"uint256","name":"consensusLayerV2Validators","type":"uint256"},{"internalType":"uint256","name":"transitioning","type":"uint256"}],"internalType":"struct BalancesSnapshot","name":"balances","type":"tuple"}],"internalType":"struct RepriceSnapshotState","name":"state","type":"tuple"},{"internalType":"uint256","name":"rewardsPayableForFees","type":"uint256"},{"components":[{"internalType":"uint256","name":"totalETHExited","type":"uint256"},{"internalType":"uint256","name":"exitingETH","type":"uint256"}],"internalType":"struct WithdrawSnapshotState","name":"withdrawState","type":"tuple"}],"internalType":"struct UpgradeableRepriceSnapshot","name":"_snapshot","type":"tuple"}],"name":"assertRepricingSnapshotValidity","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IAccessControlManager","name":"_accessControlManager","type":"address"},{"internalType":"contract AggregatorV3Interface","name":"_externalV3ReservesPoROracle","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"lastRepriceSnapshot","outputs":[{"components":[{"components":[{"internalType":"uint256","name":"blockNumber","type":"uint256"},{"internalType":"uint256","name":"blockOfLastSnapshot","type":"uint256"},{"internalType":"uint256","name":"slot","type":"uint256"},{"internalType":"uint256","name":"timestamp","type":"uint256"}],"internalType":"struct RepriceSnapshotMeta","name":"meta","type":"tuple"},{"components":[{"internalType":"uint256","name":"totalETHDeposited","type":"uint256"},{"internalType":"uint256","name":"rswETHTotalSupply","type":"uint256"},{"components":[{"internalType":"uint256","name":"executionLayer","type":"uint256"},{"internalType":"uint256","name":"consensusLayerV3Validators","type":"uint256"},{"internalType":"uint256","name":"consensusLayerV2Validators","type":"uint256"},{"internalType":"uint256","name":"transitioning","type":"uint256"}],"internalType":"struct BalancesSnapshot","name":"balances","type":"tuple"}],"internalType":"struct RepriceSnapshotState","name":"state","type":"tuple"},{"internalType":"uint256","name":"rewardsPayableForFees","type":"uint256"},{"components":[{"internalType":"uint256","name":"totalETHExited","type":"uint256"},{"internalType":"uint256","name":"exitingETH","type":"uint256"}],"internalType":"struct WithdrawSnapshotState","name":"withdrawState","type":"tuple"}],"internalType":"struct UpgradeableRepriceSnapshot","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maximumReferencePriceDiffPercentage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maximumRepriceBlockAtSnapshotStaleness","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maximumRepriceV3ReservesExternalPoRDiffPercentage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maximumRoundDataStalenessTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_newAddress","type":"address"}],"name":"setExternalV3ReservesPoROracleAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newMaximumReferencePriceDiffPercentage","type":"uint256"}],"name":"setMaximumReferencePriceDiffPercentage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maximumRepriceBlockAtSnapshotStaleness","type":"uint256"}],"name":"setMaximumRepriceBlockAtSnapshotStaleness","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newMaximumRepriceV3ReservesExternalPoRDiffPercentage","type":"uint256"}],"name":"setMaximumRepriceV3ReservesExternalPoRDiffPercentage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newMaximumRoundDataStalenessTime","type":"uint256"}],"name":"setMaximumRoundDataStalenessTime","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"components":[{"internalType":"uint256","name":"blockNumber","type":"uint256"},{"internalType":"uint256","name":"blockOfLastSnapshot","type":"uint256"},{"internalType":"uint256","name":"slot","type":"uint256"},{"internalType":"uint256","name":"timestamp","type":"uint256"}],"internalType":"struct RepriceSnapshotMeta","name":"meta","type":"tuple"},{"components":[{"internalType":"uint256","name":"totalETHDeposited","type":"uint256"},{"internalType":"uint256","name":"rswETHTotalSupply","type":"uint256"},{"components":[{"internalType":"uint256","name":"executionLayer","type":"uint256"},{"internalType":"uint256","name":"consensusLayerV3Validators","type":"uint256"},{"internalType":"uint256","name":"consensusLayerV2Validators","type":"uint256"},{"internalType":"uint256","name":"transitioning","type":"uint256"}],"internalType":"struct BalancesSnapshot","name":"balances","type":"tuple"}],"internalType":"struct RepriceSnapshotState","name":"state","type":"tuple"},{"internalType":"uint256","name":"rewardsPayableForFees","type":"uint256"},{"components":[{"internalType":"uint256","name":"totalETHExited","type":"uint256"},{"internalType":"uint256","name":"exitingETH","type":"uint256"}],"internalType":"struct WithdrawSnapshotState","name":"withdrawState","type":"tuple"}],"internalType":"struct UpgradeableRepriceSnapshot","name":"_snapshot","type":"tuple"}],"name":"submitSnapshot","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"activeValidatorsToDelete","type":"bytes[]"},{"components":[{"components":[{"internalType":"uint256","name":"blockNumber","type":"uint256"},{"internalType":"uint256","name":"blockOfLastSnapshot","type":"uint256"},{"internalType":"uint256","name":"slot","type":"uint256"},{"internalType":"uint256","name":"timestamp","type":"uint256"}],"internalType":"struct RepriceSnapshotMeta","name":"meta","type":"tuple"},{"components":[{"internalType":"uint256","name":"totalETHDeposited","type":"uint256"},{"internalType":"uint256","name":"rswETHTotalSupply","type":"uint256"},{"components":[{"internalType":"uint256","name":"executionLayer","type":"uint256"},{"internalType":"uint256","name":"consensusLayerV3Validators","type":"uint256"},{"internalType":"uint256","name":"consensusLayerV2Validators","type":"uint256"},{"internalType":"uint256","name":"transitioning","type":"uint256"}],"internalType":"struct BalancesSnapshot","name":"balances","type":"tuple"}],"internalType":"struct RepriceSnapshotState","name":"state","type":"tuple"},{"internalType":"uint256","name":"rewardsPayableForFees","type":"uint256"},{"components":[{"internalType":"uint256","name":"totalETHExited","type":"uint256"},{"internalType":"uint256","name":"exitingETH","type":"uint256"}],"internalType":"struct WithdrawSnapshotState","name":"withdrawState","type":"tuple"}],"internalType":"struct UpgradeableRepriceSnapshot","name":"_snapshot","type":"tuple"},{"internalType":"uint256","name":"lastTokenIDToProcess","type":"uint256"}],"name":"submitSnapshotV2","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IERC20","name":"_token","type":"address"}],"name":"withdrawERC20","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60806040523480156200001157600080fd5b506200001c62000022565b620000e4565b600054610100900460ff16156200008f5760405162461bcd60e51b815260206004820152602760248201527f496e697469616c697a61626c653a20636f6e747261637420697320696e697469604482015266616c697a696e6760c81b606482015260840160405180910390fd5b60005460ff9081161015620000e2576000805460ff191660ff9081179091556040519081527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b565b612ee680620000f46000396000f3fe608060405234801561001057600080fd5b506004361061010b5760003560e01c8063a37a108c116100a2578063e3cd0a5211610071578063e3cd0a52146102a2578063ed5cb56e146102b5578063f4f3b200146102c8578063f5ba9868146102db578063f9789a9b146102e45761010b565b8063a37a108c146101da578063b5facea7146101ed578063c64eb0991461027c578063e3858f3c1461028f5761010b565b806362367e2a116100de57806362367e2a1461017057806364370336146101835780638a6303a214610196578063902340a1146101a95761010b565b806301ee696714610123578063485cc95514610138578063499914471461014b57806352203ce614610167575b60405162393b6d60e11b815260040160405180910390fd5b61013661013136600461284a565b6102ed565b005b610136610146366004612878565b6103a6565b610154600f5481565b6040519081526020015b60405180910390f35b61015460105481565b61013661017e36600461284a565b610502565b6101366101913660046128ca565b6105bb565b6101366101a436600461284a565b610ba5565b6000546101c2906201000090046001600160a01b031681565b6040516001600160a01b03909116815260200161015e565b6001546101c2906001600160a01b031681565b6101f5610c5e565b604080518251805182526020808201518184015281840151838501526060918201518284015280850151805160808501528082015160a0850152840151805160c08501528082015160e0850152808501516101008501528201516101208401529284015161014083015290920151805161016084015201516101808201526101a00161015e565b61013661028a366004612959565b610dd4565b61013661029d366004612976565b610eb5565b6101366102b036600461284a565b611261565b6101366102c3366004612976565b61131a565b6101366102d6366004612959565b61133c565b61015460035481565b61015460025481565b6000546040516312d9a6ad60e01b8152600080516020612e9183398151915260048201819052336024830152916201000090046001600160a01b0316906312d9a6ad9060440160006040518083038186803b15801561034b57600080fd5b505afa15801561035f573d6000803e3d6000fd5b505060035460408051918252602082018690527ff195b2042e99ddbf5a71f9e8ae63725cfe53aea0f4cbabee398d49c5b213d2e0935001905060405180910390a150600355565b600054610100900460ff16158080156103c65750600054600160ff909116105b806103e05750303b1580156103e0575060005460ff166001145b6104485760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084015b60405180910390fd5b6000805460ff19166001179055801561046b576000805461ff0019166101001790555b8261047581611454565b506000805462010000600160b01b031916620100006001600160a01b038681169190910291909117909155600180546001600160a01b03191691841691909117905580156104fd576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050565b6000546040516312d9a6ad60e01b8152600080516020612e9183398151915260048201819052336024830152916201000090046001600160a01b0316906312d9a6ad9060440160006040518083038186803b15801561056057600080fd5b505afa158015610574573d6000803e3d6000fd5b505060105460408051918252602082018690527f0c321e1849c7892310b9794926ef4c7978aef6b5c9f557ff3fa16bb0ab7ca8d3935001905060405180910390a150601055565b6000546040516312d9a6ad60e01b81527f902cbe3a02736af9827fb6a90bada39e955c0941e08f0c63b3a662a7b17a4e2b60048201819052336024830152916201000090046001600160a01b0316906312d9a6ad9060440160006040518083038186803b15801561062b57600080fd5b505afa15801561063f573d6000803e3d6000fd5b50505050600060029054906101000a90046001600160a01b03166001600160a01b031663d19a85026040518163ffffffff1660e01b8152600401602060405180830381865afa158015610696573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106ba9190612993565b156106d85760405163e014c4ff60e01b815260040160405180910390fd5b60006106e261147e565b90506106fc6106f636869003860186612aff565b8261159f565b84156107d957600060029054906101000a90046001600160a01b03166001600160a01b0316639ffaaa3b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610755573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107799190612b5d565b6001600160a01b031663eda74e7187876040518363ffffffff1660e01b81526004016107a6929190612ba3565b600060405180830381600087803b1580156107c057600080fd5b505af11580156107d4573d6000803e3d6000fd5b505050505b60008060029054906101000a90046001600160a01b03166001600160a01b031663780b44bd6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561082d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108519190612b5d565b6001600160a01b031663a7b9544e6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561088e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108b29190612c3f565b905060006108e46108cb36889003880160808901612c58565b6108de3689900389016101608a01612c74565b85611959565b90506108ef86611dd1565b60008060029054906101000a90046001600160a01b03166001600160a01b031663780b44bd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610943573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109679190612b5d565b6001600160a01b031663a7b9544e6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156109a4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109c89190612c3f565b90506109d7818360105461212a565b80831115610a4857600060029054906101000a90046001600160a01b03166001600160a01b0316633e8a0bc96040518163ffffffff1660e01b8152600401600060405180830381600087803b158015610a2f57600080fd5b505af1158015610a43573d6000803e3d6000fd5b505050505b600060029054906101000a90046001600160a01b03166001600160a01b031663e9f2838e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a9b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610abf9190612993565b610b9a57600060029054906101000a90046001600160a01b03166001600160a01b031663fb2b37ff6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b16573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b3a9190612b5d565b6001600160a01b031663152fcb0c876040518263ffffffff1660e01b8152600401610b6791815260200190565b600060405180830381600087803b158015610b8157600080fd5b505af1158015610b95573d6000803e3d6000fd5b505050505b505050505050505050565b6000546040516312d9a6ad60e01b8152600080516020612e9183398151915260048201819052336024830152916201000090046001600160a01b0316906312d9a6ad9060440160006040518083038186803b158015610c0357600080fd5b505afa158015610c17573d6000803e3d6000fd5b505060025460408051918252602082018690527f404abf8471af23a3d142cf0106bdaf9f2d6315da3821b918f5d020f84cb5badd935001905060405180910390a150600255565b610c66612795565b600080516020612e718339815191528054600003610d1e5750506040805161010081018252600454608080830191825260055460a084015260065460c084015260075460e0840152908252825160608082018552600854825260095460208381019190915285519384018652600a548452600b5484820152600c5484870152600d54848301528286019390935282840191909152600e5483850152835180850190945260008085529184019190915281019190915290565b604080516101008101825282546080808301918252600185015460a0840152600285015460c0840152600385015460e084015290825282516060808201855260048601548252600586015460208381019190915285519384018652600687015484526007870154848201526008870154848701526009870154848301528286019390935282840191909152600a850154838501528351808501909452600b8501548452600c909401549083015291820152919050565b6000546040516312d9a6ad60e01b8152600080516020612e9183398151915260048201819052336024830152916201000090046001600160a01b0316906312d9a6ad9060440160006040518083038186803b158015610e3257600080fd5b505afa158015610e46573d6000803e3d6000fd5b5050600154604080516001600160a01b03928316815291861660208301527ffa8d209167610f942a538ba5f5270247506741005c83629661c2479908888597935001905060405180910390a150600180546001600160a01b0319166001600160a01b0392909216919091179055565b6000546040516312d9a6ad60e01b81527f902cbe3a02736af9827fb6a90bada39e955c0941e08f0c63b3a662a7b17a4e2b60048201819052336024830152916201000090046001600160a01b0316906312d9a6ad9060440160006040518083038186803b158015610f2557600080fd5b505afa158015610f39573d6000803e3d6000fd5b50505050600060029054906101000a90046001600160a01b03166001600160a01b031663d19a85026040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f90573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fb49190612993565b15610fd25760405163e014c4ff60e01b815260040160405180910390fd5b6000610fdc61147e565b9050610ff06106f636859003850185612aff565b60008060029054906101000a90046001600160a01b03166001600160a01b031663780b44bd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611044573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110689190612b5d565b6001600160a01b031663a7b9544e6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156110a5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110c99190612c3f565b905060006110f56110e236879003870160808801612c58565b6108de3688900388016101608901612c74565b905061110085611dd1565b60008060029054906101000a90046001600160a01b03166001600160a01b031663780b44bd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611154573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111789190612b5d565b6001600160a01b031663a7b9544e6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111b5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111d99190612c3f565b90506111e8818360105461212a565b8083111561125957600060029054906101000a90046001600160a01b03166001600160a01b0316633e8a0bc96040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561124057600080fd5b505af1158015611254573d6000803e3d6000fd5b505050505b505050505050565b6000546040516312d9a6ad60e01b8152600080516020612e9183398151915260048201819052336024830152916201000090046001600160a01b0316906312d9a6ad9060440160006040518083038186803b1580156112bf57600080fd5b505afa1580156112d3573d6000803e3d6000fd5b5050600f5460408051918252602082018690527fa0b159927b01ec3f4c8131cea15e91bc677386effae96db38e291a16ee827227935001905060405180910390a150600f55565b600061132461147e565b90506113386106f636849003840184612aff565b5050565b6000546040516312d9a6ad60e01b8152600080516020612e9183398151915260048201819052336024830152916201000090046001600160a01b0316906312d9a6ad9060440160006040518083038186803b15801561139a57600080fd5b505afa1580156113ae573d6000803e3d6000fd5b50506040516370a0823160e01b8152306004820152600092506001600160a01b03851691506370a0823190602401602060405180830381865afa1580156113f9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061141d9190612c3f565b90508060000361144057604051637dd28aa760e11b815260040160405180910390fd5b6104fd6001600160a01b03841633836121d5565b6001600160a01b03811661147b57604051631e7d738760e21b815260040160405180910390fd5b50565b60408051808201909152600080825260208201526001546001600160a01b03166114ba5750604080518082019091526000808252602082015290565b600080600160009054906101000a90046001600160a01b03166001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa158015611510573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115349190612caf565b509350509250506000600f548261154b9190612d15565b90508042111561158257816115608242612d28565b60405163075583d760e41b81526004810192909252602482015260440161043f565b505060408051808201909152600181526020810191909152919050565b600080516020612e71833981519152805480156000816115bf57826115c3565b6004545b86516020015190915081146115fc578551602001516040516315779e1b60e01b815260048101919091526024810182905260440161043f565b855180516020909101511061162457604051635be8fe8360e01b815260040160405180910390fd5b600082611635576002850154611639565b6006545b9050808760000151604001511161166357604051633433744960e21b815260040160405180910390fd5b600083611674576003860154611678565b6007545b905080886000015160600151116116a257604051633b740eeb60e01b815260040160405180910390fd5b87516060015142116116d7578751606001516040516325d5157b60e21b8152600481019190915242602482015260440161043f565b875151431161170657875151604051630526066d60e51b8152600481019190915243602482015260440161043f565b8751516000906117169043612d28565b6002549091508082111561174757604051631dbbad5f60e21b8152600481018390526024810182905260440161043f565b60008060029054906101000a90046001600160a01b03166001600160a01b031663fb2b37ff6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561179b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117bf9190612b5d565b90508a6060015160000151816001600160a01b0316639490ab496040518163ffffffff1660e01b8152600401602060405180830381865afa158015611808573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061182c9190612c3f565b1461184a576040516341a6eae760e01b815260040160405180910390fd5b8a6060015160200151816001600160a01b0316638545f6896040518163ffffffff1660e01b8152600401602060405180830381865afa158015611891573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118b59190612c3f565b10156118d45760405163ee528c4760e01b815260040160405180910390fd5b89516118e7575050505050505050505050565b60006119038c6020015160400151602001518c60200151612227565b90506000670de0b6b3a76400006003548d602001516119229190612d3b565b61192c9190612d70565b905080821115610b955760405163cc2a2e9560e01b8152600481018390526024810182905260440161043f565b60008060008060029054906101000a90046001600160a01b03166001600160a01b031663780b44bd6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156119b0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119d49190612b5d565b90506000816001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a16573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a3a9190612c3f565b905080600003611a5d576040516306cd05dd60e41b815260040160405180910390fd5b80876020018181525050816001600160a01b0316630f0104666040518163ffffffff1660e01b8152600401602060405180830381865afa158015611aa5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ac99190612c3f565b826001600160a01b03166316b716d96040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b07573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b2b9190612c3f565b611b359190612d15565b9250816001600160a01b0316637b2c90706040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b75573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b999190612c3f565b87525050600080546040805163fb2b37ff60e01b81529051620100009092046001600160a01b03169163fb2b37ff916004808201926020929091908290030181865afa158015611bed573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c119190612b5d565b9050806001600160a01b0316639490ab496040518163ffffffff1660e01b8152600401602060405180830381865afa158015611c51573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c759190612c3f565b856000018181525050806001600160a01b0316638545f6896040518163ffffffff1660e01b8152600401602060405180830381865afa158015611cbc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ce09190612c3f565b602086015250825115611cfd576020808401516040870151909101525b6000611d0c8660400151612255565b90506000806000806000611d21868c8c612289565b9194509250905080611d338385612d92565b611d3d9190612db9565b93505050506000811315611d4f578091505b50600080876020015184611d639190612d28565b90506000611d7386855b90612384565b90506000611d9f611d8a611d878486612d28565b90565b611d9984611d6d8f6020015190565b90612393565b9050611dc0611d87611dba838e60200151611d879190612d15565b85611d99565b9750505050505050505b9392505050565b6000611ded611de836849003840160c08501612de1565b612255565b6040805184820135815260608086013560208301526080808701358385015260a080880135928401929092526101608701359083015291519293508435927f117ef17ee1efd4615c6c3cdc3d846b3e3c721357f3f9bdae2cac7c125b15b9ea929181900390910190a281357f065c2d0865d0a176d73094316d4809db64290ccf790ed5f2c25edc3e19ef56b660c084013560e0850135610100860135610120870135611e9e61018089013588612d28565b604080519586526020860194909452928401919091526060830152608082015260a0810184905261018085013560c082015260e00160405180910390a2602082013515611f7c5760008080611f1784611eff36889003880160808901612c58565b611f123689900389016101608a01612c74565b612289565b604080516020808b01358252810185905290810183905261014089013560608201526080810182905292955090935091508535907f03f848ac9bef13b51657bd5a8a209708dab4dd1e70a8c63fb3a0f44e8e2d79879060a00160405180910390a25050505b61014082013560a0830135600082611f9961018087013586612d28565b611fa39190612d28565b9050600060029054906101000a90046001600160a01b03166001600160a01b031663780b44bd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611ff8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061201c9190612b5d565b604051631cd0aef560e21b81526004810183905260248101859052604481018490526001600160a01b039190911690637342bbd490606401600060405180830381600087803b15801561206e57600080fd5b505af1158015612082573d6000803e3d6000fd5b50505050600061209d600080516020612e7183398151915290565b863581556020870135600182015560408701356002820155606087013560038201556080870135600482015560a0870135600582015560c0870135600682015560e0870135600782015561010087013560088201556101208701356009820155610140870135600a820155610160870135600b82015561018090960135600c909601959095555050505050565b60006121368484612227565b90506000670de0b6b3a764000061214d8487612d3b565b6121579190612d70565b90508082111561218457604051638415f57960e01b8152600481018390526024810184905260440161043f565b670de0b6b3a76400006121978486612d3b565b6121a19190612d70565b9050808211156121ce57604051638415f57960e01b8152600481018390526024810184905260440161043f565b5050505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b1790526104fd9084906123ab565b6000818310156122425761223b8383612d28565b905061224f565b61224c8284612d28565b90505b92915050565b600081606001518260400151836020015184600001516122759190612d15565b61227f9190612d15565b61224f9190612d15565b6000808080600080516020612e718339815191528054909150156000816122e957604080516080810182526006850154815260078501546020820152600885015491810191909152600984015460608201526122e490612255565b61231b565b60408051608081018252600a548152600b546020820152600c5491810191909152600d54606082015261231b90612255565b9050612327818a612d92565b955060008261233a57600484015461233e565b6008545b895190915061234e908290612d28565b955060008361236157600b850154612364565b60005b8951909150612374908290612d28565b9550505050505093509350939050565b600061224c611d87848461247d565b600061224c611d8784670de0b6b3a764000085612531565b6000612400826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166126059092919063ffffffff16565b8051909150156104fd578080602001905181019061241e9190612993565b6104fd5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161043f565b60008080600019848609848602925082811083820303915050670de0b6b3a764000081106124c857604051635173648d60e01b8152600481018690526024810185905260440161043f565b6000670de0b6b3a76400008587099050816000036124f4575050670de0b6b3a76400009004905061224f565b620400008184030492109003600160ee1b02177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac1066902905092915050565b600080806000198587098587029250828110838203039150508060000361256b5783828161256157612561612d5a565b0492505050611dca565b83811061259c57604051630c740aef60e31b815260048101879052602481018690526044810185905260640161043f565b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b6060612614848460008561261c565b949350505050565b60608247101561267d5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b606482015260840161043f565b600080866001600160a01b031685876040516126999190612e21565b60006040518083038185875af1925050503d80600081146126d6576040519150601f19603f3d011682016040523d82523d6000602084013e6126db565b606091505b50915091506126ec878383876126f7565b979650505050505050565b6060831561276657825160000361275f576001600160a01b0385163b61275f5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161043f565b5081612614565b612614838381511561277b5781518083602001fd5b8060405162461bcd60e51b815260040161043f9190612e3d565b60405180608001604052806127cb6040518060800160405280600081526020016000815260200160008152602001600081525090565b81526020016127d8612806565b815260200160008152602001612801604051806040016040528060008152602001600081525090565b905290565b604051806060016040528060008152602001600081526020016128016040518060800160405280600081526020016000815260200160008152602001600081525090565b60006020828403121561285c57600080fd5b5035919050565b6001600160a01b038116811461147b57600080fd5b6000806040838503121561288b57600080fd5b823561289681612863565b915060208301356128a681612863565b809150509250929050565b60006101a082840312156128c457600080fd5b50919050565b6000806000806101e085870312156128e157600080fd5b843567ffffffffffffffff808211156128f957600080fd5b818701915087601f83011261290d57600080fd5b81358181111561291c57600080fd5b8860208260051b850101111561293157600080fd5b6020928301965094506129489188915087016128b1565b939692955092936101c00135925050565b60006020828403121561296b57600080fd5b8135611dca81612863565b60006101a0828403121561298957600080fd5b61224c83836128b1565b6000602082840312156129a557600080fd5b81518015158114611dca57600080fd5b6040516080810167ffffffffffffffff811182821017156129e657634e487b7160e01b600052604160045260246000fd5b60405290565b6000608082840312156129fe57600080fd5b612a066129b5565b90508135815260208201356020820152604082013560408201526060820135606082015292915050565b600060c08284031215612a4257600080fd5b6040516060810181811067ffffffffffffffff82111715612a7357634e487b7160e01b600052604160045260246000fd5b80604052508091508235815260208301356020820152612a9684604085016129ec565b60408201525092915050565b600060408284031215612ab457600080fd5b6040516040810181811067ffffffffffffffff82111715612ae557634e487b7160e01b600052604160045260246000fd5b604052823581526020928301359281019290925250919050565b60006101a08284031215612b1257600080fd5b612b1a6129b5565b612b2484846129ec565b8152612b338460808501612a30565b60208201526101408301356040820152612b51846101608501612aa2565b60608201529392505050565b600060208284031215612b6f57600080fd5b8151611dca81612863565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b60208082528181018390526000906040600585901b8401810190840186845b87811015612c3257868403603f190183528135368a9003601e19018112612be857600080fd5b8901858101903567ffffffffffffffff811115612c0457600080fd5b803603821315612c1357600080fd5b612c1e868284612b7a565b955050509184019190840190600101612bc2565b5091979650505050505050565b600060208284031215612c5157600080fd5b5051919050565b600060c08284031215612c6a57600080fd5b61224c8383612a30565b600060408284031215612c8657600080fd5b61224c8383612aa2565b805169ffffffffffffffffffff81168114612caa57600080fd5b919050565b600080600080600060a08688031215612cc757600080fd5b612cd086612c90565b9450602086015193506040860151925060608601519150612cf360808701612c90565b90509295509295909350565b634e487b7160e01b600052601160045260246000fd5b8082018082111561224f5761224f612cff565b8181038181111561224f5761224f612cff565b6000816000190483118215151615612d5557612d55612cff565b500290565b634e487b7160e01b600052601260045260246000fd5b600082612d8d57634e487b7160e01b600052601260045260246000fd5b500490565b8181036000831280158383131683831282161715612db257612db2612cff565b5092915050565b8082018281126000831280158216821582161715612dd957612dd9612cff565b505092915050565b600060808284031215612df357600080fd5b61224c83836129ec565b60005b83811015612e18578181015183820152602001612e00565b50506000910152565b60008251612e33818460208701612dfd565b9190910192915050565b6020815260008251806020840152612e5c816040850160208701612dfd565b601f01601f1916919091016040019291505056fea87c151ce721c42ba6f4f50ed70b1199b1c50a4b49cd628dd1b880634e673f434ff52032f36e32ac782042a01802e20394d4255c84a3c046490be98ab632691ba26469706673582212206b2b00abceb09a04e580a6c9f2c9c13b91065cac5b83e4b0280ba389a224dae264736f6c63430008100033

Deployed Bytecode

0x608060405234801561001057600080fd5b506004361061010b5760003560e01c8063a37a108c116100a2578063e3cd0a5211610071578063e3cd0a52146102a2578063ed5cb56e146102b5578063f4f3b200146102c8578063f5ba9868146102db578063f9789a9b146102e45761010b565b8063a37a108c146101da578063b5facea7146101ed578063c64eb0991461027c578063e3858f3c1461028f5761010b565b806362367e2a116100de57806362367e2a1461017057806364370336146101835780638a6303a214610196578063902340a1146101a95761010b565b806301ee696714610123578063485cc95514610138578063499914471461014b57806352203ce614610167575b60405162393b6d60e11b815260040160405180910390fd5b61013661013136600461284a565b6102ed565b005b610136610146366004612878565b6103a6565b610154600f5481565b6040519081526020015b60405180910390f35b61015460105481565b61013661017e36600461284a565b610502565b6101366101913660046128ca565b6105bb565b6101366101a436600461284a565b610ba5565b6000546101c2906201000090046001600160a01b031681565b6040516001600160a01b03909116815260200161015e565b6001546101c2906001600160a01b031681565b6101f5610c5e565b604080518251805182526020808201518184015281840151838501526060918201518284015280850151805160808501528082015160a0850152840151805160c08501528082015160e0850152808501516101008501528201516101208401529284015161014083015290920151805161016084015201516101808201526101a00161015e565b61013661028a366004612959565b610dd4565b61013661029d366004612976565b610eb5565b6101366102b036600461284a565b611261565b6101366102c3366004612976565b61131a565b6101366102d6366004612959565b61133c565b61015460035481565b61015460025481565b6000546040516312d9a6ad60e01b8152600080516020612e9183398151915260048201819052336024830152916201000090046001600160a01b0316906312d9a6ad9060440160006040518083038186803b15801561034b57600080fd5b505afa15801561035f573d6000803e3d6000fd5b505060035460408051918252602082018690527ff195b2042e99ddbf5a71f9e8ae63725cfe53aea0f4cbabee398d49c5b213d2e0935001905060405180910390a150600355565b600054610100900460ff16158080156103c65750600054600160ff909116105b806103e05750303b1580156103e0575060005460ff166001145b6104485760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084015b60405180910390fd5b6000805460ff19166001179055801561046b576000805461ff0019166101001790555b8261047581611454565b506000805462010000600160b01b031916620100006001600160a01b038681169190910291909117909155600180546001600160a01b03191691841691909117905580156104fd576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050565b6000546040516312d9a6ad60e01b8152600080516020612e9183398151915260048201819052336024830152916201000090046001600160a01b0316906312d9a6ad9060440160006040518083038186803b15801561056057600080fd5b505afa158015610574573d6000803e3d6000fd5b505060105460408051918252602082018690527f0c321e1849c7892310b9794926ef4c7978aef6b5c9f557ff3fa16bb0ab7ca8d3935001905060405180910390a150601055565b6000546040516312d9a6ad60e01b81527f902cbe3a02736af9827fb6a90bada39e955c0941e08f0c63b3a662a7b17a4e2b60048201819052336024830152916201000090046001600160a01b0316906312d9a6ad9060440160006040518083038186803b15801561062b57600080fd5b505afa15801561063f573d6000803e3d6000fd5b50505050600060029054906101000a90046001600160a01b03166001600160a01b031663d19a85026040518163ffffffff1660e01b8152600401602060405180830381865afa158015610696573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106ba9190612993565b156106d85760405163e014c4ff60e01b815260040160405180910390fd5b60006106e261147e565b90506106fc6106f636869003860186612aff565b8261159f565b84156107d957600060029054906101000a90046001600160a01b03166001600160a01b0316639ffaaa3b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610755573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107799190612b5d565b6001600160a01b031663eda74e7187876040518363ffffffff1660e01b81526004016107a6929190612ba3565b600060405180830381600087803b1580156107c057600080fd5b505af11580156107d4573d6000803e3d6000fd5b505050505b60008060029054906101000a90046001600160a01b03166001600160a01b031663780b44bd6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561082d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108519190612b5d565b6001600160a01b031663a7b9544e6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561088e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108b29190612c3f565b905060006108e46108cb36889003880160808901612c58565b6108de3689900389016101608a01612c74565b85611959565b90506108ef86611dd1565b60008060029054906101000a90046001600160a01b03166001600160a01b031663780b44bd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610943573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109679190612b5d565b6001600160a01b031663a7b9544e6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156109a4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109c89190612c3f565b90506109d7818360105461212a565b80831115610a4857600060029054906101000a90046001600160a01b03166001600160a01b0316633e8a0bc96040518163ffffffff1660e01b8152600401600060405180830381600087803b158015610a2f57600080fd5b505af1158015610a43573d6000803e3d6000fd5b505050505b600060029054906101000a90046001600160a01b03166001600160a01b031663e9f2838e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a9b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610abf9190612993565b610b9a57600060029054906101000a90046001600160a01b03166001600160a01b031663fb2b37ff6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b16573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b3a9190612b5d565b6001600160a01b031663152fcb0c876040518263ffffffff1660e01b8152600401610b6791815260200190565b600060405180830381600087803b158015610b8157600080fd5b505af1158015610b95573d6000803e3d6000fd5b505050505b505050505050505050565b6000546040516312d9a6ad60e01b8152600080516020612e9183398151915260048201819052336024830152916201000090046001600160a01b0316906312d9a6ad9060440160006040518083038186803b158015610c0357600080fd5b505afa158015610c17573d6000803e3d6000fd5b505060025460408051918252602082018690527f404abf8471af23a3d142cf0106bdaf9f2d6315da3821b918f5d020f84cb5badd935001905060405180910390a150600255565b610c66612795565b600080516020612e718339815191528054600003610d1e5750506040805161010081018252600454608080830191825260055460a084015260065460c084015260075460e0840152908252825160608082018552600854825260095460208381019190915285519384018652600a548452600b5484820152600c5484870152600d54848301528286019390935282840191909152600e5483850152835180850190945260008085529184019190915281019190915290565b604080516101008101825282546080808301918252600185015460a0840152600285015460c0840152600385015460e084015290825282516060808201855260048601548252600586015460208381019190915285519384018652600687015484526007870154848201526008870154848701526009870154848301528286019390935282840191909152600a850154838501528351808501909452600b8501548452600c909401549083015291820152919050565b6000546040516312d9a6ad60e01b8152600080516020612e9183398151915260048201819052336024830152916201000090046001600160a01b0316906312d9a6ad9060440160006040518083038186803b158015610e3257600080fd5b505afa158015610e46573d6000803e3d6000fd5b5050600154604080516001600160a01b03928316815291861660208301527ffa8d209167610f942a538ba5f5270247506741005c83629661c2479908888597935001905060405180910390a150600180546001600160a01b0319166001600160a01b0392909216919091179055565b6000546040516312d9a6ad60e01b81527f902cbe3a02736af9827fb6a90bada39e955c0941e08f0c63b3a662a7b17a4e2b60048201819052336024830152916201000090046001600160a01b0316906312d9a6ad9060440160006040518083038186803b158015610f2557600080fd5b505afa158015610f39573d6000803e3d6000fd5b50505050600060029054906101000a90046001600160a01b03166001600160a01b031663d19a85026040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f90573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fb49190612993565b15610fd25760405163e014c4ff60e01b815260040160405180910390fd5b6000610fdc61147e565b9050610ff06106f636859003850185612aff565b60008060029054906101000a90046001600160a01b03166001600160a01b031663780b44bd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611044573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110689190612b5d565b6001600160a01b031663a7b9544e6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156110a5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110c99190612c3f565b905060006110f56110e236879003870160808801612c58565b6108de3688900388016101608901612c74565b905061110085611dd1565b60008060029054906101000a90046001600160a01b03166001600160a01b031663780b44bd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611154573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111789190612b5d565b6001600160a01b031663a7b9544e6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111b5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111d99190612c3f565b90506111e8818360105461212a565b8083111561125957600060029054906101000a90046001600160a01b03166001600160a01b0316633e8a0bc96040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561124057600080fd5b505af1158015611254573d6000803e3d6000fd5b505050505b505050505050565b6000546040516312d9a6ad60e01b8152600080516020612e9183398151915260048201819052336024830152916201000090046001600160a01b0316906312d9a6ad9060440160006040518083038186803b1580156112bf57600080fd5b505afa1580156112d3573d6000803e3d6000fd5b5050600f5460408051918252602082018690527fa0b159927b01ec3f4c8131cea15e91bc677386effae96db38e291a16ee827227935001905060405180910390a150600f55565b600061132461147e565b90506113386106f636849003840184612aff565b5050565b6000546040516312d9a6ad60e01b8152600080516020612e9183398151915260048201819052336024830152916201000090046001600160a01b0316906312d9a6ad9060440160006040518083038186803b15801561139a57600080fd5b505afa1580156113ae573d6000803e3d6000fd5b50506040516370a0823160e01b8152306004820152600092506001600160a01b03851691506370a0823190602401602060405180830381865afa1580156113f9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061141d9190612c3f565b90508060000361144057604051637dd28aa760e11b815260040160405180910390fd5b6104fd6001600160a01b03841633836121d5565b6001600160a01b03811661147b57604051631e7d738760e21b815260040160405180910390fd5b50565b60408051808201909152600080825260208201526001546001600160a01b03166114ba5750604080518082019091526000808252602082015290565b600080600160009054906101000a90046001600160a01b03166001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa158015611510573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115349190612caf565b509350509250506000600f548261154b9190612d15565b90508042111561158257816115608242612d28565b60405163075583d760e41b81526004810192909252602482015260440161043f565b505060408051808201909152600181526020810191909152919050565b600080516020612e71833981519152805480156000816115bf57826115c3565b6004545b86516020015190915081146115fc578551602001516040516315779e1b60e01b815260048101919091526024810182905260440161043f565b855180516020909101511061162457604051635be8fe8360e01b815260040160405180910390fd5b600082611635576002850154611639565b6006545b9050808760000151604001511161166357604051633433744960e21b815260040160405180910390fd5b600083611674576003860154611678565b6007545b905080886000015160600151116116a257604051633b740eeb60e01b815260040160405180910390fd5b87516060015142116116d7578751606001516040516325d5157b60e21b8152600481019190915242602482015260440161043f565b875151431161170657875151604051630526066d60e51b8152600481019190915243602482015260440161043f565b8751516000906117169043612d28565b6002549091508082111561174757604051631dbbad5f60e21b8152600481018390526024810182905260440161043f565b60008060029054906101000a90046001600160a01b03166001600160a01b031663fb2b37ff6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561179b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117bf9190612b5d565b90508a6060015160000151816001600160a01b0316639490ab496040518163ffffffff1660e01b8152600401602060405180830381865afa158015611808573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061182c9190612c3f565b1461184a576040516341a6eae760e01b815260040160405180910390fd5b8a6060015160200151816001600160a01b0316638545f6896040518163ffffffff1660e01b8152600401602060405180830381865afa158015611891573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118b59190612c3f565b10156118d45760405163ee528c4760e01b815260040160405180910390fd5b89516118e7575050505050505050505050565b60006119038c6020015160400151602001518c60200151612227565b90506000670de0b6b3a76400006003548d602001516119229190612d3b565b61192c9190612d70565b905080821115610b955760405163cc2a2e9560e01b8152600481018390526024810182905260440161043f565b60008060008060029054906101000a90046001600160a01b03166001600160a01b031663780b44bd6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156119b0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119d49190612b5d565b90506000816001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a16573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a3a9190612c3f565b905080600003611a5d576040516306cd05dd60e41b815260040160405180910390fd5b80876020018181525050816001600160a01b0316630f0104666040518163ffffffff1660e01b8152600401602060405180830381865afa158015611aa5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ac99190612c3f565b826001600160a01b03166316b716d96040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b07573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b2b9190612c3f565b611b359190612d15565b9250816001600160a01b0316637b2c90706040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b75573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b999190612c3f565b87525050600080546040805163fb2b37ff60e01b81529051620100009092046001600160a01b03169163fb2b37ff916004808201926020929091908290030181865afa158015611bed573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c119190612b5d565b9050806001600160a01b0316639490ab496040518163ffffffff1660e01b8152600401602060405180830381865afa158015611c51573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c759190612c3f565b856000018181525050806001600160a01b0316638545f6896040518163ffffffff1660e01b8152600401602060405180830381865afa158015611cbc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ce09190612c3f565b602086015250825115611cfd576020808401516040870151909101525b6000611d0c8660400151612255565b90506000806000806000611d21868c8c612289565b9194509250905080611d338385612d92565b611d3d9190612db9565b93505050506000811315611d4f578091505b50600080876020015184611d639190612d28565b90506000611d7386855b90612384565b90506000611d9f611d8a611d878486612d28565b90565b611d9984611d6d8f6020015190565b90612393565b9050611dc0611d87611dba838e60200151611d879190612d15565b85611d99565b9750505050505050505b9392505050565b6000611ded611de836849003840160c08501612de1565b612255565b6040805184820135815260608086013560208301526080808701358385015260a080880135928401929092526101608701359083015291519293508435927f117ef17ee1efd4615c6c3cdc3d846b3e3c721357f3f9bdae2cac7c125b15b9ea929181900390910190a281357f065c2d0865d0a176d73094316d4809db64290ccf790ed5f2c25edc3e19ef56b660c084013560e0850135610100860135610120870135611e9e61018089013588612d28565b604080519586526020860194909452928401919091526060830152608082015260a0810184905261018085013560c082015260e00160405180910390a2602082013515611f7c5760008080611f1784611eff36889003880160808901612c58565b611f123689900389016101608a01612c74565b612289565b604080516020808b01358252810185905290810183905261014089013560608201526080810182905292955090935091508535907f03f848ac9bef13b51657bd5a8a209708dab4dd1e70a8c63fb3a0f44e8e2d79879060a00160405180910390a25050505b61014082013560a0830135600082611f9961018087013586612d28565b611fa39190612d28565b9050600060029054906101000a90046001600160a01b03166001600160a01b031663780b44bd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611ff8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061201c9190612b5d565b604051631cd0aef560e21b81526004810183905260248101859052604481018490526001600160a01b039190911690637342bbd490606401600060405180830381600087803b15801561206e57600080fd5b505af1158015612082573d6000803e3d6000fd5b50505050600061209d600080516020612e7183398151915290565b863581556020870135600182015560408701356002820155606087013560038201556080870135600482015560a0870135600582015560c0870135600682015560e0870135600782015561010087013560088201556101208701356009820155610140870135600a820155610160870135600b82015561018090960135600c909601959095555050505050565b60006121368484612227565b90506000670de0b6b3a764000061214d8487612d3b565b6121579190612d70565b90508082111561218457604051638415f57960e01b8152600481018390526024810184905260440161043f565b670de0b6b3a76400006121978486612d3b565b6121a19190612d70565b9050808211156121ce57604051638415f57960e01b8152600481018390526024810184905260440161043f565b5050505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b1790526104fd9084906123ab565b6000818310156122425761223b8383612d28565b905061224f565b61224c8284612d28565b90505b92915050565b600081606001518260400151836020015184600001516122759190612d15565b61227f9190612d15565b61224f9190612d15565b6000808080600080516020612e718339815191528054909150156000816122e957604080516080810182526006850154815260078501546020820152600885015491810191909152600984015460608201526122e490612255565b61231b565b60408051608081018252600a548152600b546020820152600c5491810191909152600d54606082015261231b90612255565b9050612327818a612d92565b955060008261233a57600484015461233e565b6008545b895190915061234e908290612d28565b955060008361236157600b850154612364565b60005b8951909150612374908290612d28565b9550505050505093509350939050565b600061224c611d87848461247d565b600061224c611d8784670de0b6b3a764000085612531565b6000612400826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166126059092919063ffffffff16565b8051909150156104fd578080602001905181019061241e9190612993565b6104fd5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161043f565b60008080600019848609848602925082811083820303915050670de0b6b3a764000081106124c857604051635173648d60e01b8152600481018690526024810185905260440161043f565b6000670de0b6b3a76400008587099050816000036124f4575050670de0b6b3a76400009004905061224f565b620400008184030492109003600160ee1b02177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac1066902905092915050565b600080806000198587098587029250828110838203039150508060000361256b5783828161256157612561612d5a565b0492505050611dca565b83811061259c57604051630c740aef60e31b815260048101879052602481018690526044810185905260640161043f565b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b6060612614848460008561261c565b949350505050565b60608247101561267d5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b606482015260840161043f565b600080866001600160a01b031685876040516126999190612e21565b60006040518083038185875af1925050503d80600081146126d6576040519150601f19603f3d011682016040523d82523d6000602084013e6126db565b606091505b50915091506126ec878383876126f7565b979650505050505050565b6060831561276657825160000361275f576001600160a01b0385163b61275f5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161043f565b5081612614565b612614838381511561277b5781518083602001fd5b8060405162461bcd60e51b815260040161043f9190612e3d565b60405180608001604052806127cb6040518060800160405280600081526020016000815260200160008152602001600081525090565b81526020016127d8612806565b815260200160008152602001612801604051806040016040528060008152602001600081525090565b905290565b604051806060016040528060008152602001600081526020016128016040518060800160405280600081526020016000815260200160008152602001600081525090565b60006020828403121561285c57600080fd5b5035919050565b6001600160a01b038116811461147b57600080fd5b6000806040838503121561288b57600080fd5b823561289681612863565b915060208301356128a681612863565b809150509250929050565b60006101a082840312156128c457600080fd5b50919050565b6000806000806101e085870312156128e157600080fd5b843567ffffffffffffffff808211156128f957600080fd5b818701915087601f83011261290d57600080fd5b81358181111561291c57600080fd5b8860208260051b850101111561293157600080fd5b6020928301965094506129489188915087016128b1565b939692955092936101c00135925050565b60006020828403121561296b57600080fd5b8135611dca81612863565b60006101a0828403121561298957600080fd5b61224c83836128b1565b6000602082840312156129a557600080fd5b81518015158114611dca57600080fd5b6040516080810167ffffffffffffffff811182821017156129e657634e487b7160e01b600052604160045260246000fd5b60405290565b6000608082840312156129fe57600080fd5b612a066129b5565b90508135815260208201356020820152604082013560408201526060820135606082015292915050565b600060c08284031215612a4257600080fd5b6040516060810181811067ffffffffffffffff82111715612a7357634e487b7160e01b600052604160045260246000fd5b80604052508091508235815260208301356020820152612a9684604085016129ec565b60408201525092915050565b600060408284031215612ab457600080fd5b6040516040810181811067ffffffffffffffff82111715612ae557634e487b7160e01b600052604160045260246000fd5b604052823581526020928301359281019290925250919050565b60006101a08284031215612b1257600080fd5b612b1a6129b5565b612b2484846129ec565b8152612b338460808501612a30565b60208201526101408301356040820152612b51846101608501612aa2565b60608201529392505050565b600060208284031215612b6f57600080fd5b8151611dca81612863565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b60208082528181018390526000906040600585901b8401810190840186845b87811015612c3257868403603f190183528135368a9003601e19018112612be857600080fd5b8901858101903567ffffffffffffffff811115612c0457600080fd5b803603821315612c1357600080fd5b612c1e868284612b7a565b955050509184019190840190600101612bc2565b5091979650505050505050565b600060208284031215612c5157600080fd5b5051919050565b600060c08284031215612c6a57600080fd5b61224c8383612a30565b600060408284031215612c8657600080fd5b61224c8383612aa2565b805169ffffffffffffffffffff81168114612caa57600080fd5b919050565b600080600080600060a08688031215612cc757600080fd5b612cd086612c90565b9450602086015193506040860151925060608601519150612cf360808701612c90565b90509295509295909350565b634e487b7160e01b600052601160045260246000fd5b8082018082111561224f5761224f612cff565b8181038181111561224f5761224f612cff565b6000816000190483118215151615612d5557612d55612cff565b500290565b634e487b7160e01b600052601260045260246000fd5b600082612d8d57634e487b7160e01b600052601260045260246000fd5b500490565b8181036000831280158383131683831282161715612db257612db2612cff565b5092915050565b8082018281126000831280158216821582161715612dd957612dd9612cff565b505092915050565b600060808284031215612df357600080fd5b61224c83836129ec565b60005b83811015612e18578181015183820152602001612e00565b50506000910152565b60008251612e33818460208701612dfd565b9190910192915050565b6020815260008251806020840152612e5c816040850160208701612dfd565b601f01601f1916919091016040019291505056fea87c151ce721c42ba6f4f50ed70b1199b1c50a4b49cd628dd1b880634e673f434ff52032f36e32ac782042a01802e20394d4255c84a3c046490be98ab632691ba26469706673582212206b2b00abceb09a04e580a6c9f2c9c13b91065cac5b83e4b0280ba389a224dae264736f6c63430008100033

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

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

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