Skip to content
Verified contractExactMIT

ArbitrageV4

Address0x8b75deb16d45fac788bd9f2ac18e79c369eb84bd
Balance

0 ETH

 

Transactions

3,045

 

Compiler

solc 0.8.20

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.20+commit.a1b79de6
Language
solidity
Optimization
Yes, 1,000 runs
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
19,824,106
Creation transaction
0xeedbe2579a…5df22289b0

69 files

contracts/ArbitrageV4.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "contracts/interfaces/IWETH.sol";
import "contracts/interfaces/IPriceFeedAggregator.sol";
import "contracts/interfaces/IReserveHolder.sol";
import "contracts/interfaces/IArbitrageERC20.sol";
import "contracts/interfaces/IRewardController.sol";
import "contracts/library/ExternalContractAddresses.sol";
import "contracts/uniswap/libraries/UniswapV2Library.sol";
import "contracts/interfaces/IArbitrageV3.sol";

/// @title Contract for performing arbitrage
/// @notice This contract is responsible for buying USC tokens and for keeping price of USC token pegged to target price
/// @dev This contract represent second version of arbitrage contract, arbitrage is now private and all profit from arbitrage is kept in this contract
contract ArbitrageV4 is IArbitrageV3, ReentrancyGuard, Ownable {
  using SafeERC20 for IERC20;
  using SafeERC20 for IArbitrageERC20;

  uint256 public constant BASE_PRICE = 1e8;
  uint256 public constant USC_TARGET_PRICE = 1e8;
  uint256 public constant POOL_FEE = 30;
  uint256 public constant MAX_FEE = 100_00;

  // F = (1 - pool_fee) on 18 decimals
  uint256 public constant F = ((MAX_FEE - POOL_FEE) * 1e18) / MAX_FEE;
  uint16 public constant MAX_PRICE_TOLERANCE = 100_00;
  address public constant WETH = ExternalContractAddresses.WETH;
  address public constant STETH = ExternalContractAddresses.stETH;
  IUniswapV2Router02 public constant swapRouter = IUniswapV2Router02(ExternalContractAddresses.UNI_V2_SWAP_ROUTER);
  IUniswapV2Factory public constant poolFactory = IUniswapV2Factory(ExternalContractAddresses.UNI_V2_POOL_FACTORY);

  IArbitrageERC20 public immutable USC;
  IArbitrageERC20 public immutable CHI;
  IRewardController public immutable rewardController;
  IPriceFeedAggregator public immutable priceFeedAggregator;
  IReserveHolder public immutable reserveHolder;

  uint256 public pegPriceToleranceAbs;
  uint256 public mintBurnFee;
  uint256 public maxMintBurnPriceDiff;
  uint16 public maxMintBurnReserveTolerance;
  uint16 public chiPriceTolerance;
  uint16 public priceTolerance;

  bool public mintPaused;
  bool public burnPaused;

  uint256 public totalMintedUsc; // total amount of minted USC tokens during arbitrage when stablecoin is pegged

  mapping(address => bool) public isArbitrager;
  mapping(address => bool) public isPrivileged;

  modifier onlyArbitrager() {
    if (!isArbitrager[msg.sender]) {
      revert NotArbitrager(msg.sender);
    }

    _;
  }

  modifier whenMintNotPaused() {
    if (mintPaused) {
      revert ContractIsPaused();
    }

    _;
  }

  modifier whenBurnNotPaused() {
    if (burnPaused) {
      revert ContractIsPaused();
    }

    _;
  }

  modifier onlyWhenMintableOrBurnable() {
    uint256 ethPrice = priceFeedAggregator.peek(WETH);

    uint256 uscSpotPrice = _calculateUscSpotPrice(ethPrice);
    if (!_almostEqualAbs(uscSpotPrice, USC_TARGET_PRICE, maxMintBurnPriceDiff)) {
      revert PriceIsNotPegged();
    }

    (, uint256 reserveDiff, uint256 reserveValue) = _getReservesData();
    if (reserveDiff > Math.mulDiv(reserveValue, maxMintBurnReserveTolerance, MAX_PRICE_TOLERANCE)) {
      revert ReserveDiffTooBig();
    }

    _;
  }

  constructor(
    IArbitrageERC20 _USC,
    IArbitrageERC20 _CHI,
    IRewardController _rewardController,
    IPriceFeedAggregator _priceFeedAggregator,
    IReserveHolder _reserveHolder
  ) Ownable() {
    USC = _USC;
    CHI = _CHI;
    rewardController = _rewardController;
    priceFeedAggregator = _priceFeedAggregator;
    reserveHolder = _reserveHolder;
    mintPaused = false;
    burnPaused = false;

    IERC20(USC).approve(address(rewardController), type(uint256).max);
    IERC20(STETH).approve(address(reserveHolder), type(uint256).max);
  }

  /// @inheritdoc IArbitrageV3
  function setPegPriceToleranceAbs(uint256 _priceTolerance) external override onlyOwner {
    pegPriceToleranceAbs = _priceTolerance;
  }

  /// @inheritdoc IArbitrageV3
  function setMintPause(bool isPaused) external onlyOwner {
    mintPaused = isPaused;
  }

  /// @inheritdoc IArbitrageV3
  function setBurnPause(bool isPaused) external onlyOwner {
    burnPaused = isPaused;
  }

  /// @inheritdoc IArbitrageV3
  function setPriceTolerance(uint16 _priceTolerance) external onlyOwner {
    if (_priceTolerance > MAX_PRICE_TOLERANCE) {
      revert ToleranceTooBig(_priceTolerance);
    }
    priceTolerance = _priceTolerance;
    emit SetPriceTolerance(_priceTolerance);
  }

  /// @inheritdoc IArbitrageV3
  function setChiPriceTolerance(uint16 _chiPriceTolerance) external onlyOwner {
    if (_chiPriceTolerance > MAX_PRICE_TOLERANCE) {
      revert ToleranceTooBig(_chiPriceTolerance);
    }
    chiPriceTolerance = _chiPriceTolerance;
    emit SetChiPriceTolerance(_chiPriceTolerance);
  }

  /// @inheritdoc IArbitrageV3
  function setMaxMintBurnPriceDiff(uint256 _maxMintBurnPriceDiff) external onlyOwner {
    maxMintBurnPriceDiff = _maxMintBurnPriceDiff;
    emit SetMaxMintBurnPriceDiff(_maxMintBurnPriceDiff);
  }

  /// @inheritdoc IArbitrageV3
  function setMaxMintBurnReserveTolerance(uint16 _maxMintBurnReserveTolerance) external onlyOwner {
    if (_maxMintBurnReserveTolerance > MAX_PRICE_TOLERANCE) {
      revert ToleranceTooBig(_maxMintBurnReserveTolerance);
    }
    maxMintBurnReserveTolerance = _maxMintBurnReserveTolerance;
    emit SetMaxMintBurnReserveTolerance(_maxMintBurnReserveTolerance);
  }

  /// @inheritdoc IArbitrageV3
  function setMintBurnFee(uint16 _mintBurnFee) external onlyOwner {
    if (_mintBurnFee > MAX_FEE) {
      revert FeeTooBig(_mintBurnFee);
    }

    mintBurnFee = _mintBurnFee;
    emit SetMintBurnFee(_mintBurnFee);
  }

  /// @inheritdoc IArbitrageV3
  function updateArbitrager(address arbitrager, bool status) external onlyOwner {
    isArbitrager[arbitrager] = status;
    emit UpdateArbitrager(arbitrager, status);
  }

  /// @inheritdoc IArbitrageV3
  function updatePrivileged(address account, bool status) external onlyOwner {
    isPrivileged[account] = status;
    emit UpdatePrivileged(account, status);
  }

  /// @inheritdoc IArbitrageV3
  function claimRewards(IERC20[] memory tokens) external onlyOwner {
    for (uint256 i = 0; i < tokens.length; i++) {
      IERC20 token = tokens[i];
      uint256 balance = token.balanceOf(address(this));
      token.safeTransfer(msg.sender, balance);

      if (address(token) == address(USC)) {
        totalMintedUsc = 0;
      }
    }
  }

  /// @inheritdoc IArbitrageV3
  function mint() external payable whenMintNotPaused nonReentrant onlyWhenMintableOrBurnable returns (uint256) {
    uint256 ethAmount = msg.value;
    uint256 fee = Math.mulDiv(ethAmount, mintBurnFee, MAX_FEE);
    uint256 ethAmountAfterFee = ethAmount - fee;

    IWETH(WETH).deposit{value: ethAmount}();
    IERC20(WETH).safeTransfer(address(reserveHolder), ethAmountAfterFee);
    return _mint(ethAmountAfterFee, WETH);
  }

  /// @inheritdoc IArbitrageV3
  function mintWithWETH(
    uint256 wethAmount
  ) external whenMintNotPaused nonReentrant onlyWhenMintableOrBurnable returns (uint256) {
    uint256 fee = Math.mulDiv(wethAmount, mintBurnFee, MAX_FEE);
    IERC20(WETH).safeTransferFrom(msg.sender, address(this), fee);

    uint256 wethAmountAfterFee = wethAmount - fee;
    IERC20(WETH).safeTransferFrom(msg.sender, address(reserveHolder), wethAmountAfterFee);

    return _mint(wethAmountAfterFee, WETH);
  }

  /// @inheritdoc IArbitrageV3
  function mintWithStETH(
    uint256 stETHAmount
  ) external whenMintNotPaused nonReentrant onlyWhenMintableOrBurnable returns (uint256) {
    uint256 fee = Math.mulDiv(stETHAmount, mintBurnFee, MAX_FEE);
    IERC20(STETH).safeTransferFrom(msg.sender, address(this), fee);

    uint256 stETHAmountAfterFee = stETHAmount - fee;
    IERC20(STETH).safeTransferFrom(msg.sender, address(this), stETHAmountAfterFee);
    reserveHolder.deposit(IERC20(STETH).balanceOf(address(this)));

    return _mint(stETHAmountAfterFee, STETH);
  }

  /// @inheritdoc IArbitrageV3
  function burn(uint256 amount) external whenBurnNotPaused nonReentrant onlyWhenMintableOrBurnable returns (uint256) {
    uint256 ethPrice = priceFeedAggregator.peek(WETH);

    USC.safeTransferFrom(msg.sender, address(this), amount);
    amount -= (amount * mintBurnFee) / MAX_FEE;
    USC.burn(amount);

    uint256 ethAmountToRedeem = Math.mulDiv(amount, USC_TARGET_PRICE, ethPrice);

    reserveHolder.redeem(ethAmountToRedeem);
    IERC20(WETH).safeTransfer(msg.sender, ethAmountToRedeem);

    emit Burn(msg.sender, amount, ethAmountToRedeem);
    return ethAmountToRedeem;
  }

  /// @inheritdoc IArbitrageV3
  function executeArbitrage(uint256 maxChiSpotPrice) public override nonReentrant onlyArbitrager returns (uint256) {
    _validateArbitrage(maxChiSpotPrice);
    return _executeArbitrage();
  }

  /// @inheritdoc IArbitrageV3
  function getArbitrageData()
    public
    view
    returns (bool isPriceAboveTarget, bool isExcessOfReserves, uint256 reserveDiff, uint256 discount)
  {
    uint256 ethPrice = priceFeedAggregator.peek(WETH);
    uint256 uscPrice = _getAndValidateUscPrice(ethPrice);

    uint256 reserveValue;
    (isExcessOfReserves, reserveDiff, reserveValue) = _getReservesData();
    isPriceAboveTarget = uscPrice >= USC_TARGET_PRICE;

    //If prices are equal delta does not need to be calculated
    if (_almostEqualAbs(uscPrice, USC_TARGET_PRICE, pegPriceToleranceAbs)) {
      discount = Math.mulDiv(reserveDiff, BASE_PRICE, reserveValue);
    }
  }

  function _executeArbitrage() internal returns (uint256) {
    (bool isPriceAboveTarget, bool isExcessOfReserves, uint256 reserveDiff, uint256 discount) = getArbitrageData();

    uint256 ethPrice = priceFeedAggregator.peek(WETH);

    if (discount != 0) {
      if (isExcessOfReserves) {
        return _arbitrageAtPegExcessOfReserves(reserveDiff, discount, ethPrice);
      } else {
        return _arbitrageAtPegDeficitOfReserves(reserveDiff, discount, ethPrice);
      }
    } else if (isPriceAboveTarget) {
      if (isExcessOfReserves) {
        return _arbitrageAbovePegExcessOfReserves(reserveDiff, ethPrice);
      } else {
        return _arbitrageAbovePegDeficitOfReserves(reserveDiff, ethPrice);
      }
    } else {
      if (isExcessOfReserves) {
        return _arbitrageBellowPegExcessOfReserves(reserveDiff, ethPrice);
      } else {
        return _arbitrageBellowPegDeficitOfReserves(reserveDiff, ethPrice);
      }
    }
  }

  function _mint(uint256 amount, address token) private returns (uint256) {
    uint256 usdValue;
    if (token == WETH) {
      uint256 ethPrice = priceFeedAggregator.peek(WETH);
      usdValue = _convertTokenAmountToUsdValue(amount, ethPrice);
    } else {
      uint256 tokenPrice = priceFeedAggregator.peek(token);
      usdValue = _convertTokenAmountToUsdValue(amount, tokenPrice);
    }

    uint256 uscAmountToMint = _convertUsdValueToTokenAmount(usdValue, USC_TARGET_PRICE);
    USC.mint(msg.sender, uscAmountToMint);
    emit Mint(msg.sender, token, amount, uscAmountToMint);
    return uscAmountToMint;
  }

  function _arbitrageAbovePegExcessOfReserves(uint256 reserveDiff, uint256 ethPrice) private returns (uint256) {
    uint256 deltaUSC = _calculateDeltaUSC(ethPrice);

    USC.mint(address(this), deltaUSC);
    uint256 ethAmountReceived = _swap(address(USC), WETH, deltaUSC);

    uint256 deltaUsd = _convertTokenAmountToUsdValue(deltaUSC, USC_TARGET_PRICE);
    uint256 deltaInETH = _convertUsdValueToTokenAmount(deltaUsd, ethPrice);

    if (deltaInETH > ethAmountReceived) {
      revert DeltaBiggerThanAmountReceivedETH(deltaInETH, ethAmountReceived);
    }

    uint256 ethAmountToSwap;
    uint256 ethAmountForReserves;

    if (deltaUsd > reserveDiff) {
      ethAmountToSwap = _convertUsdValueToTokenAmount(reserveDiff, ethPrice);
      ethAmountForReserves = _convertUsdValueToTokenAmount(deltaUsd, ethPrice) - ethAmountToSwap;
      IERC20(WETH).safeTransfer(address(reserveHolder), ethAmountForReserves);
    } else {
      ethAmountToSwap = _convertUsdValueToTokenAmount(deltaUsd, ethPrice);
    }

    uint256 chiAmountReceived = _swap(WETH, address(CHI), ethAmountToSwap);
    CHI.burn(chiAmountReceived);

    uint256 rewardAmount = ethAmountReceived - ethAmountToSwap - ethAmountForReserves;

    uint256 rewardValue = _convertTokenAmountToUsdValue(rewardAmount, ethPrice);
    emit ExecuteArbitrage(msg.sender, 1, deltaUsd, reserveDiff, ethPrice, rewardValue);
    return rewardValue;
  }

  function _arbitrageAbovePegDeficitOfReserves(uint256 reserveDiff, uint256 ethPrice) private returns (uint256) {
    uint256 deltaUSC = _calculateDeltaUSC(ethPrice);

    USC.mint(address(this), deltaUSC);
    uint256 ethAmountReceived = _swap(address(USC), WETH, deltaUSC);

    uint256 deltaUsd = _convertTokenAmountToUsdValue(deltaUSC, USC_TARGET_PRICE);
    uint256 deltaInETH = _convertUsdValueToTokenAmount(deltaUsd, ethPrice);

    if (deltaInETH > ethAmountReceived) {
      revert DeltaBiggerThanAmountReceivedETH(deltaInETH, ethAmountReceived);
    }

    IERC20(WETH).safeTransfer(address(reserveHolder), deltaInETH);

    uint256 rewardAmount = ethAmountReceived - deltaInETH;

    uint256 rewardValue = _convertTokenAmountToUsdValue(rewardAmount, ethPrice);
    emit ExecuteArbitrage(msg.sender, 2, deltaUsd, reserveDiff, ethPrice, rewardValue);
    return rewardValue;
  }

  function _arbitrageBellowPegExcessOfReserves(uint256 reserveDiff, uint256 ethPrice) private returns (uint256) {
    uint256 uscAmountToFreeze;
    uint256 uscAmountToBurn;

    uint256 deltaETH = _calculateDeltaETH(ethPrice);
    uint256 deltaUsd = _convertTokenAmountToUsdValue(deltaETH, ethPrice);

    if (deltaUsd > reserveDiff) {
      uscAmountToFreeze = _convertUsdValueToTokenAmount(reserveDiff, USC_TARGET_PRICE);
      uscAmountToBurn = _convertUsdValueToTokenAmount(deltaUsd - reserveDiff, USC_TARGET_PRICE);
    } else {
      uscAmountToFreeze = _convertUsdValueToTokenAmount(deltaUsd, USC_TARGET_PRICE);
    }

    reserveHolder.redeem(deltaETH);
    uint256 uscAmountReceived = _swap(WETH, address(USC), deltaETH);

    if (uscAmountReceived < uscAmountToFreeze) {
      uscAmountToFreeze = uscAmountReceived;
    }

    rewardController.rewardUSC(uscAmountToFreeze);

    if (uscAmountToBurn > 0) {
      USC.burn(uscAmountToBurn);
    }

    uint256 rewardAmount = uscAmountReceived - uscAmountToFreeze - uscAmountToBurn;
    uint256 rewardValue = _convertTokenAmountToUsdValue(rewardAmount, USC_TARGET_PRICE);
    emit ExecuteArbitrage(msg.sender, 3, deltaUsd, reserveDiff, ethPrice, rewardValue);
    return rewardValue;
  }

  function _arbitrageBellowPegDeficitOfReserves(uint256 reserveDiff, uint256 ethPrice) private returns (uint256) {
    uint256 ethAmountToRedeem;
    uint256 ethAmountFromChi;

    uint256 deltaETH = _calculateDeltaETH(ethPrice);
    uint256 deltaUsd = _convertTokenAmountToUsdValue(deltaETH, ethPrice);

    if (deltaUsd > reserveDiff) {
      ethAmountFromChi = _convertUsdValueToTokenAmount(reserveDiff, ethPrice);
      ethAmountToRedeem = deltaETH - ethAmountFromChi;
      reserveHolder.redeem(ethAmountToRedeem);
    } else {
      ethAmountFromChi = deltaETH;
    }

    uint256 uscAmountToBurn = _convertUsdValueToTokenAmount(deltaUsd, USC_TARGET_PRICE);

    uint256 uscAmountReceived;
    {
      if (ethAmountFromChi > 0) {
        uint256 chiAmountToMint = _getAmountInForAmountOut(address(CHI), WETH, ethAmountFromChi);
        CHI.mint(address(this), chiAmountToMint);
        _swap(address(CHI), WETH, chiAmountToMint);
      }

      uscAmountReceived = _swap(WETH, address(USC), ethAmountFromChi + ethAmountToRedeem);
    }

    if (uscAmountToBurn > 0) {
      USC.burn(uscAmountToBurn);
    }

    {
      uint256 rewardAmount = uscAmountReceived - uscAmountToBurn;
      uint256 rewardValue = _convertTokenAmountToUsdValue(rewardAmount, USC_TARGET_PRICE);
      emit ExecuteArbitrage(msg.sender, 4, deltaUsd, reserveDiff, ethPrice, rewardValue);
      return rewardValue;
    }
  }

  function _arbitrageAtPegExcessOfReserves(
    uint256 reserveDiff,
    uint256 discount,
    uint256 ethPrice
  ) private returns (uint256) {
    uint256 uscAmountToMint = _convertUsdValueToTokenAmount(reserveDiff, USC_TARGET_PRICE);
    uint256 uscAmountForReward = Math.mulDiv(uscAmountToMint, discount, BASE_PRICE);

    USC.mint(address(this), uscAmountToMint);
    totalMintedUsc += uscAmountToMint - uscAmountForReward;

    uint256 rewardValue = _convertTokenAmountToUsdValue(uscAmountForReward, USC_TARGET_PRICE);

    emit ExecuteArbitrage(msg.sender, 5, 0, reserveDiff, ethPrice, rewardValue);
    return rewardValue;
  }

  function _arbitrageAtPegDeficitOfReserves(
    uint256 reserveDiff,
    uint256 discount,
    uint256 ethPrice
  ) private returns (uint256) {
    uint256 reserveDiffInUsc = _convertUsdValueToTokenAmount(reserveDiff, USC_TARGET_PRICE);

    uint256 uscAmountToBurn;
    uint256 ethToGet;
    if (reserveDiffInUsc > totalMintedUsc) {
      uscAmountToBurn = totalMintedUsc;

      uint256 ethToGetInUsd = _convertTokenAmountToUsdValue(reserveDiffInUsc - totalMintedUsc, USC_TARGET_PRICE);
      ethToGet = _convertUsdValueToTokenAmount(ethToGetInUsd, ethPrice);
    } else {
      uscAmountToBurn = reserveDiffInUsc;
      ethToGet = 0;
    }

    uint256 chiAmountForRewardInUsd = Math.mulDiv(reserveDiff, discount, BASE_PRICE);
    uint256 chiPrice = priceFeedAggregator.peek(address(CHI));
    uint256 chiAmountForReward = _convertUsdValueToTokenAmount(chiAmountForRewardInUsd, chiPrice);

    uint256 chiToCoverEth;
    if (ethToGet > 0) {
      chiToCoverEth = _getAmountInForAmountOut(address(CHI), WETH, ethToGet);
    }

    CHI.mint(address(this), chiToCoverEth + chiAmountForReward);

    if (ethToGet > 0) {
      uint256 ethReceived = _swap(address(CHI), WETH, chiToCoverEth);
      IERC20(WETH).safeTransfer(address(reserveHolder), ethReceived);
    }

    if (uscAmountToBurn > 0) {
      USC.burn(uscAmountToBurn);
      totalMintedUsc -= uscAmountToBurn;
    }

    emit ExecuteArbitrage(msg.sender, 6, 0, reserveDiff, ethPrice, chiAmountForRewardInUsd);
    return chiAmountForRewardInUsd;
  }

  function _getReservesData() public view returns (bool isExcessOfReserves, uint256 reserveDiff, uint256 reserveValue) {
    reserveValue = reserveHolder.getReserveValue();
    uint256 uscTotalSupplyValue = _convertTokenAmountToUsdValue(USC.totalSupply(), USC_TARGET_PRICE);

    if (reserveValue > uscTotalSupplyValue) {
      isExcessOfReserves = true;
      reserveDiff = (reserveValue - uscTotalSupplyValue);
    } else {
      isExcessOfReserves = false;
      reserveDiff = (uscTotalSupplyValue - reserveValue);
    }
  }

  function _getAndValidateUscPrice(uint256 ethPrice) private view returns (uint256) {
    uint256 uscPrice = priceFeedAggregator.peek(address(USC));
    uint256 uscSpotPrice = _calculateUscSpotPrice(ethPrice);
    uint256 priceDiff = _absDiff(uscSpotPrice, uscPrice);
    uint256 maxPriceDiff = Math.mulDiv(uscPrice, priceTolerance, MAX_PRICE_TOLERANCE);

    if (priceDiff > maxPriceDiff) {
      revert PriceSlippageTooBig();
    }

    return uscSpotPrice;
  }

  function _validateArbitrage(uint256 maxChiSpotPrice) private view {
    if (!isPrivileged[msg.sender]) {
      uint256 ethPrice = priceFeedAggregator.peek(WETH);
      uint256 chiSpotPrice = _calculateChiSpotPrice(ethPrice);

      if (maxChiSpotPrice != 0 && chiSpotPrice > maxChiSpotPrice) {
        revert ChiSpotPriceTooBig();
      }

      // If max chi spot price is not specified we need to check for twap difference
      if (maxChiSpotPrice == 0) {
        uint256 chiOraclePrice = priceFeedAggregator.peek(address(CHI));

        if (!_almostEqualRel(chiSpotPrice, chiOraclePrice, chiPriceTolerance)) {
          revert ChiPriceNotPegged(chiSpotPrice, chiOraclePrice);
        }
      }
    }
  }

  // input ethPrice has 8 decimals
  // returns result with 8 decimals
  function _calculateUscSpotPrice(uint256 ethPrice) private view returns (uint256) {
    (uint256 reserveUSC, uint256 reserveWETH) = UniswapV2Library.getReserves(
      address(poolFactory),
      address(USC),
      address(WETH)
    );
    uint256 uscFor1ETH = UniswapV2Library.quote(1 ether, reserveWETH, reserveUSC);
    return Math.mulDiv(ethPrice, 1 ether, uscFor1ETH);
  }

  // input ethPrice has 8 decimals
  // returns result with 8 decimals
  function _calculateChiSpotPrice(uint256 ethPrice) private view returns (uint256) {
    (uint256 reserveCHI, uint256 reserveWETH) = UniswapV2Library.getReserves(
      address(poolFactory),
      address(CHI),
      address(WETH)
    );
    uint256 chiFor1ETH = UniswapV2Library.quote(1 ether, reserveWETH, reserveCHI);
    return Math.mulDiv(ethPrice, 1 ether, chiFor1ETH);
  }

  // what amount of In tokens to put in pool to make price:   1 tokenOut = (priceOut / priceIn) tokenIn
  // assuming reserves are on 18 decimals, prices are on 8 decimals
  function _calculateDelta(
    uint256 reserveIn,
    uint256 priceIn,
    uint256 reserveOut,
    uint256 priceOut
  ) public pure returns (uint256) {
    // F = (1 - pool_fee) = 0.997 on 18 decimals,   in square root formula  a = F

    // parameter `b` in square root formula,  b = rIn * (1+f) ,  on 18 decimals
    uint256 b = Math.mulDiv(reserveIn, 1e18 + F, 1e18);
    uint256 b_sqr = Math.mulDiv(b, b, 1e18);

    // parameter `c` in square root formula,  c = rIn^2 - (rIn * rOut * priceOut) / priceIn
    uint256 c_1 = Math.mulDiv(reserveIn, reserveIn, 1e18);
    uint256 c_2 = Math.mulDiv(Math.mulDiv(reserveIn, reserveOut, 1e18), priceOut, priceIn);

    uint256 c;
    uint256 root;
    if (c_1 > c_2) {
      c = c_1 - c_2;
      // d = 4ac
      uint256 d = Math.mulDiv(4 * F, c, 1e18);

      // root = sqrt(b^2 - 4ac)
      // multiplying by 10^9 to get back to 18 decimals
      root = Math.sqrt(b_sqr - d) * 1e9;
    } else {
      c = c_2 - c_1;
      // d = 4ac
      uint256 d = Math.mulDiv(4 * F, c, 1e18);

      // root = sqrt(b^2 - 4ac)    -> in this case `c` is negative, so we add `d` to `b^2`
      // multiplying by 10^9 to get back to 18 decimals
      root = Math.sqrt(b_sqr + d) * 1e9;
    }
    // delta = (-b + root) / 2*f
    uint256 delta = Math.mulDiv(1e18, root - b, 2 * F);

    return delta;
  }

  // given ethPrice is on 8 decimals
  // how many USC to put in pool to make price:   1 ETH = ethPrice * USC
  function _calculateDeltaUSC(uint256 ethPrice) public view returns (uint256) {
    (uint256 reserveUSC, uint256 reserveWETH) = UniswapV2Library.getReserves(
      address(poolFactory),
      address(USC),
      address(WETH)
    );
    return _calculateDelta(reserveUSC, USC_TARGET_PRICE, reserveWETH, ethPrice);
  }

  // how many ETH to put in pool to make price:   1 ETH = ethPrice * USC
  function _calculateDeltaETH(uint256 ethPrice) public view returns (uint256) {
    (uint256 reserveUSC, uint256 reserveWETH) = UniswapV2Library.getReserves(
      address(poolFactory),
      address(USC),
      address(WETH)
    );
    return _calculateDelta(reserveWETH, ethPrice, reserveUSC, USC_TARGET_PRICE);
  }

  function _makePath(address t1, address t2) internal pure returns (address[] memory path) {
    path = new address[](2);
    path[0] = t1;
    path[1] = t2;
  }

  function _makePath(address t1, address t2, address t3) internal pure returns (address[] memory path) {
    path = new address[](3);
    path[0] = t1;
    path[1] = t2;
    path[2] = t3;
  }

  function _swap(address tokenIn, address tokenOut, uint256 amount) private returns (uint256) {
    address[] memory path;

    if (tokenIn != WETH && tokenOut != WETH) {
      path = _makePath(tokenIn, WETH, tokenOut);
    } else {
      path = _makePath(tokenIn, tokenOut);
    }

    IERC20(tokenIn).approve(address(swapRouter), amount);
    uint256[] memory amounts = swapRouter.swapExactTokensForTokens(amount, 0, path, address(this), block.timestamp);

    uint256 amountReceived = amounts[path.length - 1];

    return amountReceived;
  }

  function _getAmountInForAmountOut(address tIn, address tOut, uint256 amountOut) internal view returns (uint256) {
    (uint256 rIn, uint256 rOut) = UniswapV2Library.getReserves(address(poolFactory), tIn, tOut);
    return UniswapV2Library.getAmountIn(amountOut, rIn, rOut);
  }

  function _convertUsdValueToTokenAmount(uint256 usdValue, uint256 price) internal pure returns (uint256) {
    return Math.mulDiv(usdValue, 1e18, price);
  }

  function _convertTokenAmountToUsdValue(uint256 amount, uint256 price) internal pure returns (uint256) {
    return Math.mulDiv(amount, price, 1e18);
  }

  function _absDiff(uint256 a, uint256 b) internal pure returns (uint256) {
    return (a > b) ? a - b : b - a;
  }

  function _almostEqualAbs(uint256 price1, uint256 price2, uint256 delta) internal pure returns (bool) {
    return _absDiff(price1, price2) <= delta;
  }

  function _almostEqualRel(uint256 price1, uint256 price2, uint256 delta) internal pure returns (bool) {
    (uint256 highPrice, uint256 lowPrice) = price1 > price2 ? (price1, price2) : (price2, price1);
    uint256 priceDiff = highPrice - lowPrice;
    uint256 maxPriceDiff = Math.mulDiv(highPrice, delta, MAX_PRICE_TOLERANCE);

    return priceDiff <= maxPriceDiff;
  }

  receive() external payable {}
}

@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";

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

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    function __Ownable_init() internal onlyInitializing {
        __Ownable_init_unchained();
    }

    function __Ownable_init_unchained() internal onlyInitializing {
        _transferOwnership(_msgSender());
    }

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

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

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (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]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev 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;
    }
}

@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol

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

pragma solidity ^0.8.0;

import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC20_init_unchained(name_, symbol_);
    }

    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(address from, address to, uint256 amount) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

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

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

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

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[45] private __gap;
}

@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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);
}

@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol

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

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";

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

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

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

@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/ERC721.sol)

pragma solidity ^0.8.0;

import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
    using AddressUpgradeable for address;
    using StringsUpgradeable for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC721_init_unchained(name_, symbol_);
    }

    function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        _name = name_;
        _symbol = symbol_;
    }

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

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: address zero is not a valid owner");
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _ownerOf(tokenId);
        require(owner != address(0), "ERC721: invalid token ID");
        return owner;
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        _requireMinted(tokenId);

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721Upgradeable.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "ERC721: approve caller is not token owner or approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        _requireMinted(tokenId);

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(address from, address to, uint256 tokenId) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual override {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
        _safeTransfer(from, to, tokenId, data);
    }

    /**
     * @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.
     *
     * `data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
     */
    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
        return _owners[tokenId];
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _ownerOf(tokenId) != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        address owner = ERC721Upgradeable.ownerOf(tokenId);
        return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId, 1);

        // Check that tokenId was not minted by `_beforeTokenTransfer` hook
        require(!_exists(tokenId), "ERC721: token already minted");

        unchecked {
            // Will not overflow unless all 2**256 token ids are minted to the same owner.
            // Given that tokens are minted one by one, it is impossible in practice that
            // this ever happens. Might change if we allow batch minting.
            // The ERC fails to describe this case.
            _balances[to] += 1;
        }

        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);

        _afterTokenTransfer(address(0), to, tokenId, 1);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     * This is an internal function that does not check if the sender is authorized to operate on the token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721Upgradeable.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId, 1);

        // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
        owner = ERC721Upgradeable.ownerOf(tokenId);

        // Clear approvals
        delete _tokenApprovals[tokenId];

        unchecked {
            // Cannot overflow, as that would require more tokens to be burned/transferred
            // out than the owner initially received through minting and transferring in.
            _balances[owner] -= 1;
        }
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);

        _afterTokenTransfer(owner, address(0), tokenId, 1);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(address from, address to, uint256 tokenId) internal virtual {
        require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId, 1);

        // Check that tokenId was not transferred by `_beforeTokenTransfer` hook
        require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");

        // Clear approvals from the previous owner
        delete _tokenApprovals[tokenId];

        unchecked {
            // `_balances[from]` cannot overflow for the same reason as described in `_burn`:
            // `from`'s balance is the number of token held, which is at least one before the current
            // transfer.
            // `_balances[to]` could overflow in the conditions described in `_mint`. That would require
            // all 2**256 token ids to be minted, which in practice is impossible.
            _balances[from] -= 1;
            _balances[to] += 1;
        }
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId, 1);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits an {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
        require(owner != operator, "ERC721: approve to caller");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Reverts if the `tokenId` has not been minted yet.
     */
    function _requireMinted(uint256 tokenId) internal view virtual {
        require(_exists(tokenId), "ERC721: invalid token ID");
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) private returns (bool) {
        if (to.isContract()) {
            try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
                return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    /// @solidity memory-safe-assembly
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
     * - When `from` is zero, the tokens will be minted for `to`.
     * - When `to` is zero, ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}

    /**
     * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
     * - When `from` is zero, the tokens were minted for `to`.
     * - When `to` is zero, ``from``'s tokens were burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}

    /**
     * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
     *
     * WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant
     * being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such
     * that `ownerOf(tokenId)` is `a`.
     */
    // solhint-disable-next-line func-name-mixedcase
    function __unsafe_increaseBalance(address account, uint256 amount) internal {
        _balances[account] += amount;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[44] private __gap;
}

@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol

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

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721ReceiverUpgradeable {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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);
}

@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/extensions/ERC721Enumerable.sol)

pragma solidity ^0.8.0;

import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";

/**
 * @dev This implements an optional extension of {ERC721} defined in the EIP that adds
 * enumerability of all the token ids in the contract as well as all token ids owned by each
 * account.
 */
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
    function __ERC721Enumerable_init() internal onlyInitializing {
    }

    function __ERC721Enumerable_init_unchained() internal onlyInitializing {
    }
    // Mapping from owner to list of owned token IDs
    mapping(address => mapping(uint256 => uint256)) private _ownedTokens;

    // Mapping from token ID to index of the owner tokens list
    mapping(uint256 => uint256) private _ownedTokensIndex;

    // Array with all token ids, used for enumeration
    uint256[] private _allTokens;

    // Mapping from token id to position in the allTokens array
    mapping(uint256 => uint256) private _allTokensIndex;

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

    /**
     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
        return _ownedTokens[owner][index];
    }

    /**
     * @dev See {IERC721Enumerable-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _allTokens.length;
    }

    /**
     * @dev See {IERC721Enumerable-tokenByIndex}.
     */
    function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
        return _allTokens[index];
    }

    /**
     * @dev See {ERC721-_beforeTokenTransfer}.
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 firstTokenId,
        uint256 batchSize
    ) internal virtual override {
        super._beforeTokenTransfer(from, to, firstTokenId, batchSize);

        if (batchSize > 1) {
            // Will only trigger during construction. Batch transferring (minting) is not available afterwards.
            revert("ERC721Enumerable: consecutive transfers not supported");
        }

        uint256 tokenId = firstTokenId;

        if (from == address(0)) {
            _addTokenToAllTokensEnumeration(tokenId);
        } else if (from != to) {
            _removeTokenFromOwnerEnumeration(from, tokenId);
        }
        if (to == address(0)) {
            _removeTokenFromAllTokensEnumeration(tokenId);
        } else if (to != from) {
            _addTokenToOwnerEnumeration(to, tokenId);
        }
    }

    /**
     * @dev Private function to add a token to this extension's ownership-tracking data structures.
     * @param to address representing the new owner of the given token ID
     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
     */
    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
        uint256 length = ERC721Upgradeable.balanceOf(to);
        _ownedTokens[to][length] = tokenId;
        _ownedTokensIndex[tokenId] = length;
    }

    /**
     * @dev Private function to add a token to this extension's token tracking data structures.
     * @param tokenId uint256 ID of the token to be added to the tokens list
     */
    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
        _allTokensIndex[tokenId] = _allTokens.length;
        _allTokens.push(tokenId);
    }

    /**
     * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
     * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
     * This has O(1) time complexity, but alters the order of the _ownedTokens array.
     * @param from address representing the previous owner of the given token ID
     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
     */
    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
        uint256 tokenIndex = _ownedTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary
        if (tokenIndex != lastTokenIndex) {
            uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];

            _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
        }

        // This also deletes the contents at the last position of the array
        delete _ownedTokensIndex[tokenId];
        delete _ownedTokens[from][lastTokenIndex];
    }

    /**
     * @dev Private function to remove a token from this extension's token tracking data structures.
     * This has O(1) time complexity, but alters the order of the _allTokens array.
     * @param tokenId uint256 ID of the token to be removed from the tokens list
     */
    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = _allTokens.length - 1;
        uint256 tokenIndex = _allTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
        uint256 lastTokenId = _allTokens[lastTokenIndex];

        _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
        _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index

        // This also deletes the contents at the last position of the array
        delete _allTokensIndex[tokenId];
        _allTokens.pop();
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[46] private __gap;
}

@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)

pragma solidity ^0.8.0;

import "../IERC721Upgradeable.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol

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

pragma solidity ^0.8.0;

import "../IERC721Upgradeable.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [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://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/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);
        }
    }
}

@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

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

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

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/MathUpgradeable.sol";
import "./math/SignedMathUpgradeable.sol";

/**
 * @dev String operations.
 */
library StringsUpgradeable {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

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

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

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

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

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

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

@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";

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

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

@openzeppelin/contracts-upgradeable/utils/introspection/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);
}

@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library MathUpgradeable {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

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

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

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

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                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) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

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

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

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

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

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@openzeppelin/contracts-upgradeable/utils/math/SignedMathUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

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

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

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

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

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

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

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

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

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

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

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

@openzeppelin/contracts/security/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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);
}

@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/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);
}

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/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;

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

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

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

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    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");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

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

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

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    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");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation 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).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

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

@openzeppelin/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [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://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/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);
        }
    }
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

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

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

@openzeppelin/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

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

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

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

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                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) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

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

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

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

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

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@openzeppelin/contracts/utils/math/SafeCast.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {
    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.2._
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v2.5._
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.2._
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v2.5._
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v2.5._
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v2.5._
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v2.5._
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     *
     * _Available since v3.0._
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.7._
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.7._
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
    }

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

@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol

pragma solidity >=0.5.0;

interface IUniswapV2Factory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint);

    function feeTo() external view returns (address);
    function feeToSetter() external view returns (address);

    function getPair(address tokenA, address tokenB) external view returns (address pair);
    function allPairs(uint) external view returns (address pair);
    function allPairsLength() external view returns (uint);

    function createPair(address tokenA, address tokenB) external returns (address pair);

    function setFeeTo(address) external;
    function setFeeToSetter(address) external;
}

@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol

pragma solidity >=0.5.0;

interface IUniswapV2Pair {
    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    function name() external pure returns (string memory);
    function symbol() external pure returns (string memory);
    function decimals() external pure returns (uint8);
    function totalSupply() external view returns (uint);
    function balanceOf(address owner) external view returns (uint);
    function allowance(address owner, address spender) external view returns (uint);

    function approve(address spender, uint value) external returns (bool);
    function transfer(address to, uint value) external returns (bool);
    function transferFrom(address from, address to, uint value) external returns (bool);

    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function PERMIT_TYPEHASH() external pure returns (bytes32);
    function nonces(address owner) external view returns (uint);

    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;

    event Mint(address indexed sender, uint amount0, uint amount1);
    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
    event Swap(
        address indexed sender,
        uint amount0In,
        uint amount1In,
        uint amount0Out,
        uint amount1Out,
        address indexed to
    );
    event Sync(uint112 reserve0, uint112 reserve1);

    function MINIMUM_LIQUIDITY() external pure returns (uint);
    function factory() external view returns (address);
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function price0CumulativeLast() external view returns (uint);
    function price1CumulativeLast() external view returns (uint);
    function kLast() external view returns (uint);

    function mint(address to) external returns (uint liquidity);
    function burn(address to) external returns (uint amount0, uint amount1);
    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
    function skim(address to) external;
    function sync() external;

    function initialize(address, address) external;
}

@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol

pragma solidity >=0.6.2;

interface IUniswapV2Router01 {
    function factory() external pure returns (address);
    function WETH() external pure returns (address);

    function addLiquidity(
        address tokenA,
        address tokenB,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB, uint liquidity);
    function addLiquidityETH(
        address token,
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETH(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountToken, uint amountETH);
    function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETHWithPermit(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountToken, uint amountETH);
    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapTokensForExactTokens(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);
    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);

    function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
    function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
    function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}

@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol

pragma solidity >=0.6.2;

import './IUniswapV2Router01.sol';

interface IUniswapV2Router02 is IUniswapV2Router01 {
    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountETH);
    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountETH);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable;
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
}

contracts/ReserveHolder.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "./interfaces/IReserveHolder.sol";
import "./interfaces/IPriceFeedAggregator.sol";
import "./interfaces/ISTETH.sol";
import "./interfaces/IWETH.sol";
import "./interfaces/ICurvePool.sol";
import "./library/ExternalContractAddresses.sol";

/// @title Contract for holding stETH reserves
/// @notice This contract holds stETH reserves and rebalances them
/// @notice Part of reserves are is WETH so arbitrage can take them and perform aribtrage without swapping stETH for WETH
/// @dev This contract is upgradeable
contract ReserveHolder is IReserveHolder, OwnableUpgradeable {
  using SafeERC20 for ISTETH;
  using SafeERC20 for IWETH;

  uint256 public constant BASE_PRICE = 1e8;
  uint256 public constant MAX_PERCENTAGE = 100_00;
  IWETH public constant WETH = IWETH(ExternalContractAddresses.WETH);
  ISTETH public constant stETH = ISTETH(ExternalContractAddresses.stETH);
  ICurvePool public constant curvePool = ICurvePool(ExternalContractAddresses.CURVE_ETH_STETH_POOL);

  IPriceFeedAggregator public priceFeedAggregator;
  address public claimer;
  uint256 public totalClaimed;
  uint256 public swapEthTolerance;
  uint256 public ethThreshold;
  uint256 public totalStEthDeposited;
  uint256 public curveStEthSafeGuardPercentage;

  mapping(address account => bool status) public isArbitrager;

  modifier onlyArbitrager() {
    if (isArbitrager[msg.sender] != true) {
      revert NotArbitrager(msg.sender);
    }
    _;
  }

  modifier onlyClaimer() {
    if (msg.sender != claimer) {
      revert NotClaimer(msg.sender);
    }
    _;
  }

  receive() external payable {
    emit Receive(msg.sender, msg.value);
  }

  function initialize(
    IPriceFeedAggregator _priceFeedAggregator,
    address _claimer,
    uint256 _ethThreshold,
    uint256 _curveStEthSafeGuardPercentage
  ) external initializer {
    if (_ethThreshold > MAX_PERCENTAGE) {
      revert ThresholdTooHigh(_ethThreshold);
    }
    __Ownable_init();
    claimer = _claimer;
    priceFeedAggregator = _priceFeedAggregator;
    ethThreshold = _ethThreshold;
    curveStEthSafeGuardPercentage = _curveStEthSafeGuardPercentage;
    swapEthTolerance = 0.1 ether;
  }

  /// @inheritdoc IReserveHolder
  function setArbitrager(address arbitrager, bool status) external onlyOwner {
    isArbitrager[arbitrager] = status;
    emit SetArbitrager(arbitrager, status);
  }

  /// @inheritdoc IReserveHolder
  function setClaimer(address _claimer) external onlyOwner {
    claimer = _claimer;
    emit SetClaimer(_claimer);
  }

  /// @inheritdoc IReserveHolder
  function setEthThreshold(uint256 _ethThreshold) external onlyOwner {
    if (_ethThreshold > MAX_PERCENTAGE) {
      revert ThresholdTooHigh(_ethThreshold);
    }
    ethThreshold = _ethThreshold;
    emit SetEthThreshold(_ethThreshold);
  }

  /// @inheritdoc IReserveHolder
  function setSwapEthTolerance(uint256 _swapEthTolerance) external onlyOwner {
    swapEthTolerance = _swapEthTolerance;
    emit SetSwapEthTolerance(_swapEthTolerance);
  }

  /// @inheritdoc IReserveHolder
  function setCurveStEthSafeGuardPercentage(uint256 _curveStEthSafeGuardPercentage) external onlyOwner {
    if (_curveStEthSafeGuardPercentage > MAX_PERCENTAGE) {
      revert SafeGuardTooHigh(_curveStEthSafeGuardPercentage);
    }
    curveStEthSafeGuardPercentage = _curveStEthSafeGuardPercentage;
    emit SetCurveStEthSafeGuardPercentage(_curveStEthSafeGuardPercentage);
  }

  /// @inheritdoc IReserveHolder
  function getReserveValue() external view returns (uint256) {
    uint256 stEthPrice = priceFeedAggregator.peek(address(stETH));
    uint256 ethPrice = priceFeedAggregator.peek(address(WETH));
    uint256 ethBalance = address(this).balance + WETH.balanceOf(address(this));
    return Math.mulDiv(totalStEthDeposited, stEthPrice, 1e18) + Math.mulDiv(ethBalance, ethPrice, 1e18);
  }

  /// @inheritdoc IReserveHolder
  function getCurrentRewards() external view returns (uint256) {
    return stETH.balanceOf(address(this)) - totalStEthDeposited;
  }

  /// @inheritdoc IReserveHolder
  function getCumulativeRewards() external view returns (uint256) {
    return stETH.balanceOf(address(this)) - totalStEthDeposited + totalClaimed;
  }

  /// @inheritdoc IReserveHolder
  function deposit(uint256 amount) external {
    uint256 balanceBefore = stETH.balanceOf(address(this));
    stETH.safeTransferFrom(msg.sender, address(this), amount);
    totalStEthDeposited += stETH.balanceOf(address(this)) - balanceBefore;

    emit Deposit(msg.sender, amount);
  }

  /// @inheritdoc IReserveHolder
  function rebalance() external {
    uint256 ethPrice = _peek(address(WETH));
    uint256 stEthPrice = _peek(address(stETH));
    uint256 ethValue = Math.mulDiv(WETH.balanceOf(address(this)), ethPrice, BASE_PRICE);
    uint256 stEthValue = Math.mulDiv(stETH.balanceOf(address(this)), stEthPrice, BASE_PRICE);
    uint256 ethThresholdValue = Math.mulDiv((ethValue + stEthValue), ethThreshold, MAX_PERCENTAGE);

    if (ethThresholdValue > ethValue) {
      uint256 stEthAmountToSwap = Math.mulDiv((ethThresholdValue - ethValue), BASE_PRICE, stEthPrice);
      uint256 stEthBalanceBefore = stETH.balanceOf(address(this));
      _swap(stEthAmountToSwap);
      uint256 stEthBalanceAfter = stETH.balanceOf(address(this));
      totalStEthDeposited -= stEthBalanceBefore - stEthBalanceAfter;

      emit Rebalance(0, stEthAmountToSwap);
    } else if (ethThresholdValue < ethValue) {
      uint256 stEthBalanceBefore = stETH.balanceOf(address(this));
      uint256 ethAmountToSwap = Math.mulDiv((ethValue - ethThresholdValue), BASE_PRICE, ethPrice);

      WETH.withdraw(ethAmountToSwap);
      stETH.submit{value: ethAmountToSwap}(address(this));

      uint256 stEthBalanceAfter = stETH.balanceOf(address(this));
      totalStEthDeposited += stEthBalanceAfter - stEthBalanceBefore;

      emit Rebalance(ethAmountToSwap, 0);
    }
  }

  /// @inheritdoc IReserveHolder
  function redeem(uint256 amount) external onlyArbitrager returns (uint256) {
    uint256 ethBalance = WETH.balanceOf(address(this));
    if (amount > ethBalance) {
      uint256 stEthBalanceBefore = stETH.balanceOf(address(this));
      uint256 stEthAmountToSwap = amount - ethBalance;
      uint256 safeStEthAmountToSwap = stEthAmountToSwap +
        Math.mulDiv(stEthAmountToSwap, curveStEthSafeGuardPercentage, MAX_PERCENTAGE);
      _swap(safeStEthAmountToSwap);
      uint256 stEthBalanceAfter = stETH.balanceOf(address(this));
      totalStEthDeposited -= stEthBalanceBefore - stEthBalanceAfter;

      emit RedeemSwap(amount - ethBalance, safeStEthAmountToSwap);
    }
    WETH.safeTransfer(msg.sender, amount);

    emit Redeem(msg.sender, amount);
    return amount;
  }

  /// @inheritdoc IReserveHolder
  function claimRewards(address account, uint256 amount) external onlyClaimer {
    totalClaimed += amount;
    stETH.safeTransfer(account, amount);
    emit ClaimRewards(account, amount);
  }

  /// @inheritdoc IReserveHolder
  function wrapETH() external {
    WETH.deposit{value: address(this).balance}();
  }

  function _swap(uint256 amountIn) private {
    stETH.approve(address(curvePool), amountIn);
    uint256 ethReceived = curvePool.exchange(1, 0, amountIn, 0);
    WETH.deposit{value: ethReceived}();
  }

  function _peek(address asset) private view returns (uint256) {
    uint256 price = priceFeedAggregator.peek(asset);
    return price;
  }

  function _safeTransferETH(address to, uint256 value) private {
    (bool success, ) = to.call{value: value}(new bytes(0));
    if (!success) {
      revert EtherSendFailed(to, value);
    }
  }
}

contracts/dso/LPRewards.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "../interfaces/ILPRewards.sol";
import "../interfaces/IPriceFeedAggregator.sol";
import "./PoolHelper.sol";

/// @title Contract for handling LP rewards
/// @notice Each LP token has its own LPRewards contract
contract LPRewards is ILPRewards, Ownable {
  using SafeERC20 for IERC20;
  using SafeCast for uint256;

  uint8 public immutable decimals;
  IUniswapV2Pair public immutable lpToken;
  IPriceFeedAggregator public immutable priceFeedAggregator;

  address public ochi;
  uint64 public currentEpoch;
  int256 public totalAmountLocked;
  uint256 public epochMinLPBalance;
  uint256 public currentLPValue;
  int256 public cumulativeProfit;

  mapping(uint256 tokenId => LockingTokenData) public lockingTokenData;
  mapping(uint256 epochId => EpochData) public epochData;

  modifier onlyOCHI() {
    if (msg.sender != ochi) {
      revert NotOCHI();
    }
    _;
  }

  constructor(IUniswapV2Pair _lpToken, IPriceFeedAggregator _priceFeedAggregator) {
    lpToken = _lpToken;
    decimals = lpToken.decimals();
    priceFeedAggregator = _priceFeedAggregator;
    currentEpoch = 1;
    totalAmountLocked = 0;
  }

  function setOCHI(address _ochi) external onlyOwner {
    ochi = _ochi;
    emit SetOCHI(_ochi);
  }

  /// @notice Locks LP tokens for given period, user gets rewards until the end of the period
  /// @param lockingTokenId Unique OCHI id
  /// @param amount Amount of LP tokens to lock
  /// @param epochDuration Locking duration in epochs
  /// @custom:usage This function should be called from OCHI contract in purpose of locking LP tokens
  function lockLP(uint256 lockingTokenId, uint256 amount, uint64 epochDuration) external onlyOCHI {
    if (amount == 0) {
      return;
    }

    LockingTokenData storage position = lockingTokenData[lockingTokenId];

    if (position.amountLocked != 0) {
      revert LockingTokenIdAlreadyUsed(lockingTokenId);
    }

    uint64 nextEpoch = currentEpoch + 1;
    epochData[nextEpoch].totalDeltaAmountLocked += amount.toInt256();
    epochData[nextEpoch + epochDuration].totalDeltaAmountLocked -= amount.toInt256();

    position.amountLocked = amount;
    position.endingEpoch = nextEpoch + epochDuration;
    position.lastClaimedEpoch = currentEpoch;

    emit LockLP(lockingTokenId, amount, currentEpoch, position.endingEpoch);
  }

  /// @notice Claims rewards for given token id
  /// @param lockingTokenId Unique OCHI id
  /// @param account Account to send rewards to
  /// @custom:usage This function should be called from OCHI contract in purpose of claiming rewards
  function claimRewards(uint256 lockingTokenId, address account) external onlyOCHI {
    int256 rewardUSD = calculateUnclaimedReward(lockingTokenId);
    if (rewardUSD < 0) {
      return;
    }

    uint256 totalPoolValue = PoolHelper.getTotalPoolUSDValue(lpToken, priceFeedAggregator);
    uint256 lpTokensToBurn = Math.mulDiv(uint256(rewardUSD), lpToken.totalSupply(), totalPoolValue);
    if (lpTokensToBurn == 0) {
      return;
    }

    IERC20(address(lpToken)).safeTransfer(address(lpToken), lpTokensToBurn);
    lpToken.burn(account);

    uint256 newBalance = lpToken.balanceOf(address(this));
    if (newBalance < epochMinLPBalance) epochMinLPBalance = newBalance;

    lockingTokenData[lockingTokenId].lastClaimedEpoch = currentEpoch - 1;

    emit ClaimRewards(lockingTokenId, account, lpTokensToBurn, rewardUSD);
  }

  /// @notice End current epoch and start new one
  /// @custom:usage This function should be called from OCHI contract when epoch is updated
  function updateEpoch() external onlyOCHI {
    EpochData storage epoch = epochData[currentEpoch];

    totalAmountLocked += epoch.totalDeltaAmountLocked;

    uint256 prevLPValue = currentLPValue;
    currentLPValue = PoolHelper.getUSDValueForLP(10 ** decimals, lpToken, priceFeedAggregator);

    int256 totalProfit = (currentLPValue.toInt256() - prevLPValue.toInt256()) * epochMinLPBalance.toInt256();
    int256 profitPerLockedToken;
    if (totalAmountLocked != 0) {
      profitPerLockedToken = totalProfit / totalAmountLocked;
    }

    cumulativeProfit += profitPerLockedToken;
    epoch.cumulativeProfit = cumulativeProfit;

    epochMinLPBalance = lpToken.balanceOf(address(this));
    currentEpoch++;

    emit UpdateEpoch(currentEpoch - 1, currentLPValue, totalAmountLocked, profitPerLockedToken);
  }

  /// @notice Takes LP tokens from contract and sends them to receiver
  /// @param receiver Account to send LP tokens to
  /// @custom:usage This function should be called only in case of moving liquidity to another pool
  function recoverLPTokens(address receiver) external onlyOCHI {
    uint256 amount = lpToken.balanceOf(address(this));
    IERC20(address(lpToken)).safeTransfer(receiver, amount);
    emit RecoverLPTokens(receiver, amount);
  }

  /// @notice Calculates unclaimed rewards for given token id
  /// @param lockingTokenId Unique OCHI id
  function calculateUnclaimedReward(uint256 lockingTokenId) public view returns (int256) {
    LockingTokenData storage position = lockingTokenData[lockingTokenId];
    if (position.endingEpoch == 0) {
      return 0;
    }

    uint64 fromEpoch = position.lastClaimedEpoch;
    uint64 toEpoch = currentEpoch - 1;
    if (position.endingEpoch - 1 < toEpoch) toEpoch = position.endingEpoch - 1;
    if (toEpoch <= fromEpoch) return 0;

    int256 profitDelta = epochData[toEpoch].cumulativeProfit - epochData[fromEpoch].cumulativeProfit;
    int256 totalUSDreward = (position.amountLocked.toInt256() * profitDelta) / (10 ** decimals).toInt256();
    return totalUSDreward;
  }

  /// @notice Calculates the profit in last epoch in usd value
  function getLastEpochProfit() external view returns (int256) {
    if (currentEpoch < 2) return 0;
    return epochData[currentEpoch - 1].cumulativeProfit - epochData[currentEpoch - 2].cumulativeProfit;
  }
}

contracts/dso/OCHI.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "../interfaces/IOCHI.sol";
import "../interfaces/IPriceFeedAggregator.sol";
import "../interfaces/IMintableBurnable.sol";
import "../interfaces/ILPRewards.sol";
import "../library/ExternalContractAddresses.sol";
import "./PoolHelper.sol";

/// @title Contract for creating and executing options
/// @notice Each LP token has its own LPRewards contract
/// @dev This contract is upgradeable
/// @dev This contract handles creation and execution of options but does not hold LP tokens
contract OCHI is IOCHI, ERC721EnumerableUpgradeable, OwnableUpgradeable {
  using SafeERC20 for IERC20;
  using SafeERC20 for IMintableBurnable;
  using SafeERC20 for IUniswapV2Pair;

  uint256 public constant MAX_LOCK_PERIOD_EPOCHS = 52;
  uint256 public constant EPOCH_DURATION = 1 weeks;
  uint256 public constant BASE_PRICE = 1e8;
  uint256 public constant MULTIPLIER = 1e18;
  uint256 public constant TARGET_RATIO = 80_00;
  uint256 public constant DENOMINATOR = 100_00;
  address public constant WETH = ExternalContractAddresses.WETH;

  IERC20 public usc;
  IMintableBurnable public chi;
  IUniswapV2Pair public uscEthPair;
  IUniswapV2Pair public chiEthPair;
  IPriceFeedAggregator public priceFeedAggregator;

  uint64 public currentEpoch;
  uint256 public firstEpochTimestamp;
  uint256 public mintedOCHI;
  uint256 public totalOCHIlocked;

  mapping(IUniswapV2Pair token => ILPRewards) public lpRewards;
  mapping(uint256 id => ChiOption) public options;

  function initialize(
    IERC20 _usc,
    IMintableBurnable _chi,
    IPriceFeedAggregator _priceFeedAggregator,
    IUniswapV2Pair _uscEthPair,
    IUniswapV2Pair _chiEthPair,
    ILPRewards _uscEthPairRewards,
    ILPRewards _chiEthPairRewards,
    uint256 _firstEpochTimestamp
  ) external initializer {
    __ERC721_init("Option CHI", "oCHI");
    __Ownable_init();
    usc = _usc;
    chi = _chi;
    priceFeedAggregator = _priceFeedAggregator;
    uscEthPair = _uscEthPair;
    chiEthPair = _chiEthPair;

    lpRewards[_uscEthPair] = _uscEthPairRewards;
    lpRewards[_chiEthPair] = _chiEthPairRewards;

    currentEpoch = 1;
    firstEpochTimestamp = _firstEpochTimestamp;
  }

  /// @inheritdoc IOCHI
  function mint(
    uint256 chiAmount,
    uint256 uscEthPairAmount,
    uint256 chiEthPairAmount,
    uint64 lockPeriodInEpochs
  ) external {
    if (lockPeriodInEpochs > MAX_LOCK_PERIOD_EPOCHS || lockPeriodInEpochs == 0) {
      revert InvalidLockPeriod(lockPeriodInEpochs);
    }

    (uint256 strikePrice, uint256 oChiAmount) = calculateOptionData(
      chiAmount,
      uscEthPairAmount,
      chiEthPairAmount,
      lockPeriodInEpochs
    );

    uint64 nextEpoch = currentEpoch + 1;
    uint256 tokenId = ++mintedOCHI;
    options[tokenId] = ChiOption({
      amount: oChiAmount,
      strikePrice: strikePrice,
      uscEthPairAmount: uscEthPairAmount,
      chiEthPairAmount: chiEthPairAmount,
      lockedUntil: nextEpoch + lockPeriodInEpochs,
      validUntil: nextEpoch + 2 * lockPeriodInEpochs
    });

    totalOCHIlocked += oChiAmount;

    ILPRewards uscEthLPRewards = lpRewards[uscEthPair];
    ILPRewards chiEthLPRewards = lpRewards[chiEthPair];

    if (chiAmount > 0) {
      chi.burnFrom(msg.sender, chiAmount);
    }
    IERC20(address(uscEthPair)).safeTransferFrom(msg.sender, address(uscEthLPRewards), uscEthPairAmount);
    IERC20(address(chiEthPair)).safeTransferFrom(msg.sender, address(chiEthLPRewards), chiEthPairAmount);

    uscEthLPRewards.lockLP(tokenId, uscEthPairAmount, uint64(lockPeriodInEpochs));
    chiEthLPRewards.lockLP(tokenId, chiEthPairAmount, uint64(lockPeriodInEpochs));

    _safeMint(msg.sender, tokenId);

    emit Mint(tokenId, chiAmount, uscEthPairAmount, chiEthPairAmount, lockPeriodInEpochs, strikePrice, oChiAmount);
  }

  /// @inheritdoc IOCHI
  function burn(uint256 tokenId) external {
    if (!_isApprovedOrOwner(msg.sender, tokenId)) {
      revert NotAllowed(tokenId);
    }

    ChiOption storage option = options[tokenId];

    if (currentEpoch < option.lockedUntil) {
      revert OptionLocked(tokenId);
    }
    if (currentEpoch > option.validUntil) {
      revert OptionExpired(tokenId);
    }

    lpRewards[uscEthPair].claimRewards(tokenId, msg.sender);
    lpRewards[chiEthPair].claimRewards(tokenId, msg.sender);

    uint256 chiAmount = option.amount;
    uint256 chiBalance = chi.balanceOf(address(this));
    uint256 amountToTransfer = Math.min(chiAmount, chiBalance);
    uint256 amountToMint = chiAmount - amountToTransfer;

    if (amountToMint > 0) {
      chi.mint(msg.sender, amountToMint);
    }
    if (amountToTransfer > 0) {
      chi.transfer(msg.sender, amountToTransfer);
    }

    _burn(tokenId);

    totalOCHIlocked -= options[tokenId].amount;

    emit Burn(msg.sender, tokenId, chiAmount);
  }

  /// @inheritdoc IOCHI
  function updateEpoch() public {
    if (block.timestamp < firstEpochTimestamp + (currentEpoch - 1) * EPOCH_DURATION) {
      revert EpochNotFinished();
    }

    lpRewards[uscEthPair].updateEpoch();
    lpRewards[chiEthPair].updateEpoch();

    currentEpoch++;
    emit UpdateEpoch(currentEpoch - 1, block.timestamp);
  }

  /// @inheritdoc IOCHI
  function claimRewards(uint256 tokenId) public {
    if (!_isApprovedOrOwner(msg.sender, tokenId)) {
      revert NotAllowed(tokenId);
    }

    lpRewards[uscEthPair].claimRewards(tokenId, msg.sender);
    lpRewards[chiEthPair].claimRewards(tokenId, msg.sender);

    emit ClaimRewardsOCHI(tokenId);
  }

  /// @notice Claims rewards for all users tokens
  function claimAllRewards() public {
    uint256 balance = balanceOf(msg.sender);
    for (uint256 i = 0; i < balance; i++) {
      claimRewards(tokenOfOwnerByIndex(msg.sender, i));
    }
  }

  /// @inheritdoc IOCHI
  function recoverLPTokens() external onlyOwner {
    lpRewards[uscEthPair].recoverLPTokens(msg.sender);
    lpRewards[chiEthPair].recoverLPTokens(msg.sender);

    emit RecoverLPTokens();
  }

  /// @inheritdoc IOCHI
  function getUnclaimedRewardsValue(uint256 tokenId) external view returns (int256) {
    return
      lpRewards[uscEthPair].calculateUnclaimedReward(tokenId) + lpRewards[chiEthPair].calculateUnclaimedReward(tokenId);
  }

  /// @notice Calulates strike price and ochi amount for supplied asets
  /// @param chiAmount amount of chi token to supply
  /// @param uscEthPairAmount amount of USC/ETH LP token to supply
  /// @param chiEthPairAmount amount of CHI/ETH LP token to supply
  /// @param lockPeriodInEpochs locking duration
  /// @return strikePrice strike price given for supplied assets
  /// @return oChiAmount ochi amount given for supplied assets
  function calculateOptionData(
    uint256 chiAmount,
    uint256 uscEthPairAmount,
    uint256 chiEthPairAmount,
    uint256 lockPeriodInEpochs
  ) public view returns (uint256 strikePrice, uint256 oChiAmount) {
    uint256 timeMultiplier = Math.mulDiv(lockPeriodInEpochs, MULTIPLIER, 4 * MAX_LOCK_PERIOD_EPOCHS);
    uint256 chiMultiplier = Math.mulDiv(chiAmount, MULTIPLIER, chi.totalSupply());
    (uint256 poolMultiplier, uint256 positionsValue) = getAndValidatePositionsData(uscEthPairAmount, chiEthPairAmount);

    uint256 discount = timeMultiplier + Math.min(poolMultiplier + chiMultiplier, MULTIPLIER / 4);
    uint256 chiPrice = _peek(address(chi));
    strikePrice = Math.mulDiv(chiPrice, MULTIPLIER - discount, MULTIPLIER);

    uint256 chiValue = Math.mulDiv(chiAmount, chiPrice, MULTIPLIER);
    oChiAmount = Math.mulDiv(positionsValue + chiValue, MULTIPLIER, strikePrice);
  }

  /// @notice Calculates multiplier for supplied LP assets
  /// @param uscEthPairAmount amount of USC/ETH LP token to supply
  /// @param chiEthPairAmount amount of CHI/ETH LP token to supply
  /// @return multiplier multiplier used for caluclating discount
  /// @param value parameter used for calculating ochi amount
  function getAndValidatePositionsData(
    uint256 uscEthPairAmount,
    uint256 chiEthPairAmount
  ) public view returns (uint256 multiplier, uint256 value) {
    uint256 uscEthPairTotalSupply = uscEthPair.totalSupply();
    uint256 chiEthPairTotalSupply = chiEthPair.totalSupply();

    if (
      uscEthPair.balanceOf(address(this)) + uscEthPairAmount >
      Math.mulDiv(uscEthPairTotalSupply, TARGET_RATIO, DENOMINATOR) ||
      chiEthPair.balanceOf(address(this)) + chiEthPairAmount >
      Math.mulDiv(chiEthPairTotalSupply, TARGET_RATIO, DENOMINATOR)
    ) {
      revert PolTargetRatioExceeded();
    }

    multiplier =
      Math.mulDiv(uscEthPairAmount, MULTIPLIER, uscEthPairTotalSupply) +
      Math.mulDiv(chiEthPairAmount, MULTIPLIER, chiEthPairTotalSupply);

    value = (PoolHelper.getUSDValueForLP(uscEthPairAmount, uscEthPair, priceFeedAggregator) +
      PoolHelper.getUSDValueForLP(chiEthPairAmount, chiEthPair, priceFeedAggregator));
  }

  /// @notice Calculates the total LP reward for the last epoch
  /// @return totalReward total reward in usd value
  function getLastEpochTotalReward() external view returns (int256 totalReward) {
    if (currentEpoch < 2) return 0;
    return lpRewards[uscEthPair].getLastEpochProfit() + lpRewards[chiEthPair].getLastEpochProfit();
  }

  function _peek(address asset) internal view returns (uint256 price) {
    price = priceFeedAggregator.peek(asset);
  }
}

contracts/dso/PoolHelper.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "../interfaces/IPriceFeedAggregator.sol";

library PoolHelper {
  function getTotalPoolUSDValue(
    IUniswapV2Pair pair,
    IPriceFeedAggregator priceFeedAggregator
  ) internal view returns (uint256) {
    (uint112 token0amount, uint112 token1amount, ) = pair.getReserves();
    uint256 price0 = priceFeedAggregator.peek(pair.token0());
    uint256 price1 = priceFeedAggregator.peek(pair.token1());

    // assuming both tokens have 18 decimals!
    uint256 totalValue = Math.mulDiv(token0amount, price0, 1e18) + Math.mulDiv(token1amount, price1, 1e18);
    return totalValue;
  }

  function getUSDValueForLP(
    uint256 lpAmount,
    IUniswapV2Pair pair,
    IPriceFeedAggregator priceFeedAggregator
  ) internal view returns (uint256) {
    return Math.mulDiv(getTotalPoolUSDValue(pair, priceFeedAggregator), lpAmount, pair.totalSupply());
  }
}

contracts/interfaces/IArbitrage.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IArbitrage {
  event SetPriceTolerance(uint16 priceTolerance);
  event SetMaxMintPriceDiff(uint256 maxMintPriceDiff);
  event Mint(address indexed account, address token, uint256 amount, uint256 uscAmount);
  event ExecuteArbitrage(
    address indexed account,
    uint256 indexed arbNum,
    uint256 deltaUsd,
    uint256 reserveDiff,
    uint256 ethPrice,
    uint256 rewardValue
  );

  error DeltaBiggerThanAmountReceivedETH(uint256 deltaETH, uint256 receivedETH);
  error ToleranceTooBig(uint16 _tolerance);
  error PriceSlippageTooBig();

  /// @notice Sets spot price tolerance from TWAP price
  /// @dev 100% = 10000
  /// @param _priceTolerance Price tolerance in percents
  /// @custom:usage This function should be called from owner in purpose of setting price tolerance
  function setPriceTolerance(uint16 _priceTolerance) external;

  /// @notice Sets max mint price diff
  /// @param _maxMintPriceDiff Max mint price diff
  /// @custom:usage This function should be called from owner in purpose of setting max mint price diff
  function setMaxMintPriceDiff(uint256 _maxMintPriceDiff) external;

  /// @notice Mint USC tokens for ETH
  /// @dev If USC price is different from target price for less then max mint price diff, then minting is allowed without performing arbitrage
  /// @return uscAmount Amount of USC tokens minted
  function mint() external payable returns (uint256 uscAmount);

  /// @notice Mint USC tokens for WETH
  /// @dev If USC price is different from target price for less then max mint price diff, then minting is allowed without performing arbitrage
  /// @param wethAmount Amount of WETH to mint with
  /// @return uscAmount Amount of USC tokens minted
  function mintWithWETH(uint256 wethAmount) external returns (uint256 uscAmount);

  /// @notice Mint USC tokens for stETH
  /// @dev If USC price is different from target price for less then max mint price diff, then minting is allowed without performing arbitrage
  /// @param stETHAmount Amount of stETH to mint with
  /// @return uscAmount Amount of USC tokens minted
  function mintWithStETH(uint256 stETHAmount) external returns (uint256 uscAmount);

  /// @notice Executes arbitrage, profit sent to caller
  /// @notice Returns reward value in USD
  /// @return rewardValue Reward value in USD
  /// @custom:usage This function should be called from external keeper in purpose of pegging USC price and getting reward
  /// @custom:usage This function has no restrictions, anyone can be arbitrager
  function executeArbitrage() external returns (uint256 rewardValue);

  /// @notice Gets information for perfoming arbitrage such as price diff, reserve diff, discount
  /// @return isPriceAboveTarget True if USC price is above target price
  /// @return isExcessOfReserves True if there is excess of reserves
  /// @return reserveDiff Reserve diff, excess or deficit of reserves
  /// @return discount Discount in percents, only if price is equal to target price
  function getArbitrageData()
    external
    view
    returns (bool isPriceAboveTarget, bool isExcessOfReserves, uint256 reserveDiff, uint256 discount);
}

contracts/interfaces/IArbitrageERC20.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

interface IArbitrageERC20 is IERC20 {
  function mint(address to, uint256 amount) external;

  function burn(uint256 amount) external;
}

contracts/interfaces/IArbitrageV3.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

interface IArbitrageV3 {
  error DeltaBiggerThanAmountReceivedETH(uint256 deltaETH, uint256 receivedETH);
  error ToleranceTooBig(uint16 _tolerance);
  error PriceSlippageTooBig();
  error NotArbitrager(address account);
  error PriceIsNotPegged();
  error ReserveDiffTooBig();
  error ChiPriceNotPegged(uint256 spotPrice, uint256 twapPrice);
  error FeeTooBig(uint256 fee);
  error ChiSpotPriceTooBig();
  error ContractIsPaused();

  event SetPriceTolerance(uint16 priceTolerance);
  event Mint(address indexed account, address token, uint256 amount, uint256 uscAmount);
  event ExecuteArbitrage(
    address indexed account,
    uint256 indexed arbNum,
    uint256 deltaUsd,
    uint256 reserveDiff,
    uint256 ethPrice,
    uint256 rewardValue
  );
  event UpdateArbitrager(address indexed account, bool status);
  event SetMaxMintBurnPriceDiff(uint256 maxMintBurnPriceDiff);
  event SetChiPriceTolerance(uint16 chiPriceTolerance);
  event SetMaxMintBurnReserveTolerance(uint16 maxBurnReserveTolerance);
  event SetMintBurnFee(uint256 mintFee);
  event UpdatePrivileged(address indexed privileged, bool isPrivileged);
  event Burn(address account, uint256 amount, uint256 ethAmount);

  /// @notice Sets absolute peg price tolerance
  /// @param _priceTolerance Absolute value of price tolerance
  /// @custom:usage This function should be called from owner in purpose of setting price tolerance
  function setPegPriceToleranceAbs(uint256 _priceTolerance) external;

  /// @notice Sets spot price tolerance from TWAP price
  /// @dev 100% = 10000
  /// @param _priceTolerance Price tolerance in percents
  /// @custom:usage This function should be called from owner in purpose of setting price tolerance
  function setPriceTolerance(uint16 _priceTolerance) external;

  /// @notice Mint USC tokens for ETH
  /// @dev If USC price is different from target price for less then max mint price diff, then minting is allowed without performing arbitrage
  /// @return uscAmount Amount of USC tokens minted
  function mint() external payable returns (uint256 uscAmount);

  /// @notice Mint USC tokens for WETH
  /// @dev If USC price is different from target price for less then max mint price diff, then minting is allowed without performing arbitrage
  /// @param wethAmount Amount of WETH to mint with
  /// @return uscAmount Amount of USC tokens minted
  function mintWithWETH(uint256 wethAmount) external returns (uint256 uscAmount);

  /// @notice Mint USC tokens for stETH
  /// @dev If USC price is different from target price for less then max mint price diff, then minting is allowed without performing arbitrage
  /// @param stETHAmount Amount of stETH to mint with
  /// @return uscAmount Amount of USC tokens minted
  function mintWithStETH(uint256 stETHAmount) external returns (uint256 uscAmount);

  /// @notice Executes arbitrage, profit sent to caller
  /// @notice Returns reward value in USD
  /// @param maxChiSpotPrice maximum spot price of CHI, if 0 TWAP check will be done
  /// @return rewardValue Reward value in USD
  /// @custom:usage This function should be called from external keeper in purpose of pegging USC price and getting reward
  /// @custom:usage This function has no restrictions, anyone can be arbitrager
  function executeArbitrage(uint256 maxChiSpotPrice) external returns (uint256 rewardValue);

  /// @notice Gets information for perfoming arbitrage such as price diff, reserve diff, discount
  /// @return isPriceAboveTarget True if USC price is above target price
  /// @return isExcessOfReserves True if there is excess of reserves
  /// @return reserveDiff Reserve diff, excess or deficit of reserves
  /// @return discount Discount in percents, only if price is equal to target price
  function getArbitrageData()
    external
    view
    returns (bool isPriceAboveTarget, bool isExcessOfReserves, uint256 reserveDiff, uint256 discount);

  /// @notice Update arbitrager status
  /// @dev This function can be called only by owner of contract
  /// @param account Arbitrager account
  /// @param status Arbitrager status
  function updateArbitrager(address account, bool status) external;

  /// @notice Claim rewards from arbitrages
  /// @dev This function can be called only by owner of contract
  /// @param tokens Tokens to claim rewards for
  function claimRewards(IERC20[] memory tokens) external;

  /// @notice Sets maximum mint and burn price difference
  /// @dev This function can be called only by owner of contract, value is absolute
  /// @param _maxMintBurnPriceDiff Maximum mint and burn price difference
  function setMaxMintBurnPriceDiff(uint256 _maxMintBurnPriceDiff) external;

  /// @notice Sets CHI price tolerance percentage when checking TWAP
  /// @dev This function can be called only by owner of contract, value is relative
  /// @param _chiPriceTolerance CHI price tolerance percentage
  function setChiPriceTolerance(uint16 _chiPriceTolerance) external;

  /// @notice Sets maximum mint and burn price difference
  /// @dev This function can be called only by owner of contract, value is relative
  /// @param _maxMintBurnReserveTolerance Maximum mint and burn reserve tolerance
  function setMaxMintBurnReserveTolerance(uint16 _maxMintBurnReserveTolerance) external;

  /// @notice Sets mint and burn fee
  /// @dev This function can be called only by owner of contract
  /// @param _mintBurnFee Mint and burn fee
  function setMintBurnFee(uint16 _mintBurnFee) external;

  /// @notice Update privilege status, only privileged accounts can call arbitrage and pass CHI TWAP check
  /// @dev This function can be called only by owner of contract
  /// @param account Arbitrager account
  /// @param status Privilege status
  function updatePrivileged(address account, bool status) external;

  /// @notice Burns USC tokens from msg.sender and sends him WETH from reserves
  /// @param amount Amount of USC tokens to burn
  /// @return ethAmount Amount of WETH received
  function burn(uint256 amount) external returns (uint256 ethAmount);

  /// @notice Sets mint pause
  /// @param isPaused true of false
  function setMintPause(bool isPaused) external;

  /// @notice Sets burn pause
  /// @param isPaused true of false
  function setBurnPause(bool isPaused) external;
}

contracts/interfaces/IBurnableERC20.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IBurnableERC20 {
  function burnFrom(address account, uint256 amount) external;
}

contracts/interfaces/IChiLocking.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IChiLocking {
  struct LockedPosition {
    uint256 amount;
    uint256 startEpoch;
    uint256 duration; // in epochs
    uint256 shares;
    uint256 withdrawnChiAmount;
  }

  struct LockingData {
    uint256 lastUpdatedEpoch;
    uint256 unclaimedStETH;
    LockedPosition[] positions;
  }

  struct AllLockedPositionsOutput {
    LockedPosition position;
    uint256 votingPower;
    uint256 stETHreward;
    uint256 totalAccumulatedChi;
    uint256 totalChiRewards;
  }

  struct EpochData {
    uint256 lockedSharesInEpoch;
    uint256 totalLockedChiInEpoch;
    uint256 sharesToUnlock;
    uint256 cumulativeStETHPerLockedShare;
    uint256 cumulativeStETHPerUnlocked;
    uint256 numberOfEndingPositions;
  }

  event SetUscStaking(address indexed uscStaking);
  event SetRewardController(address indexed rewardController);
  event SetChiLocker(address indexed chiLocker, bool indexed status);
  event LockChi(address indexed account, uint256 amount, uint256 shares, uint256 startEpoch, uint256 endEpoch);
  event UpdateEpoch(
    uint256 indexed epoch,
    uint256 totalLockedChi,
    uint256 chiEmissions,
    uint256 stETHrewards,
    uint256 stEthPerLockedShare
  );
  event ClaimStETH(address indexed account, uint256 amount);
  event WithdrawChiFromAccount(address indexed account, address indexed toAddress, uint256 amount);

  error ZeroAmount();
  error NotRewardController();
  error NotChiLocker();
  error UnavailableWithdrawAmount(uint256 amount);

  /// @notice Sets address of uscStaking contract
  /// @param _uscStaking Address of uscStaking contract
  function setUscStaking(address _uscStaking) external;

  /// @notice Sets address of rewardController contract
  /// @param _rewardController Address of rewardController contract
  function setRewardController(address _rewardController) external;

  /// @notice Sets address of contract who can call lock function
  /// @param contractAddress Address of contract who calles lock function, chiStaking currently
  /// @param toSet true if contract can call lock function, false otherwise
  function setChiLocker(address contractAddress, bool toSet) external;

  /// @notice Gets locked position for given account and position index
  /// @param account Account to get locked position for
  /// @param pos Index of locked position
  /// @return position Locked position
  function getLockedPosition(address account, uint256 pos) external view returns (LockedPosition memory position);

  /// @notice Gets all locked position for given account
  /// @param account Account to get locked positions
  /// @return out Array of locked positions
  function getAllLockedPositions(address account) external view returns (AllLockedPositionsOutput[] memory out);

  /// @notice Gets total staked chi amount, locked amount is also considered staked
  /// @return stakedChi Total staked chi amount
  function getStakedChi() external view returns (uint256 stakedChi);

  /// @notice Gets total locked chi amount
  /// @return lockedChi Total locked chi amount
  function getLockedChi() external view returns (uint256 lockedChi);

  /// @notice Gets total voting power
  /// @return totalVotingPower Total voting power
  function getTotalVotingPower() external view returns (uint256 totalVotingPower);

  /// @notice Gets total chi amount that is available to withdraw for given account
  /// @param account Account to get available chi amount for
  /// @return availableTotal Total amount of chi that is available to withdraw
  function availableChiWithdraw(address account) external view returns (uint256 availableTotal);

  /// @notice Locks given amount of chi for given account for given duration
  /// @param account Account to lock chi for
  /// @param amount Amount of chi to lock
  /// @param duration Duration of locking in epochs
  /// @custom:usage This function should be called from chiStaking and uscStaking contracts in purpose of locking chi
  function lockChi(address account, uint256 amount, uint256 duration) external;

  /// @notice Updates epoch data
  /// @param chiEmissions Amount of chi incentives for chi lockers that is emitted in current epoch
  /// @param stETHrewards Amount of stETH rewards for chi lockers that is emitted in current epoch
  /// @custom:usage This function should be called from rewardController contract in purpose of updating epoch data
  function updateEpoch(uint256 chiEmissions, uint256 stETHrewards) external;

  /// @notice Claims stETH rewards for given account
  /// @notice This contract does not send stETH rewards nor holds them, reserveHolder does that
  /// @notice This contract only calculates and updates unclaimed stETH amount for given account
  /// @param account Account to claim stETH rewards for
  /// @return amount Amount of stETH rewards that user can claim
  /// @custom:usage This function should be called from rewardController contract in purpose of claiming stETH rewards
  function claimStETH(address account) external returns (uint256 amount);

  /// @notice Withdraws given amount of unlocked chi tokens for given account, sends to account by default
  /// @notice This contract hold CHI tokens and inside this function sends them back to user
  /// @param account Account to withdraw CHI for
  /// @param amount Amount of CHI tokens to withdraw
  /// @custom:usage This function should be called from chiStaking contract in purpose of withdrawing CHI tokens
  function withdrawChiFromAccount(address account, uint256 amount) external;

  /// @notice Withdraws given amount of unlocked chi tokens for given account, sends to account by default
  /// @notice This contract hold CHI tokens and inside this function sends them back to user
  /// @param account Account to withdraw CHI for
  /// @param toAddress Address to which to send tokens
  /// @param amount Amount of CHI tokens to withdraw
  /// @custom:usage This function should be called from chiStaking contract in purpose of withdrawing CHI tokens
  function withdrawChiFromAccountToAddress(address account, address toAddress, uint256 amount) external;

  /// @notice Calculates and returns unclaimed stETH amount for given account
  /// @param account Account to calculate unclaimed stETH amount for
  /// @return totalAmount Total amount of unclaimed stETH for given account
  function unclaimedStETHAmount(address account) external view returns (uint256 totalAmount);

  /// @notice Calculates and returns voting power for given account
  /// @param account Account to calculate voting power for
  /// @return votingPower Voting power for given account
  function getVotingPower(address account) external view returns (uint256 votingPower);
}

contracts/interfaces/IChiStaking.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IChiLocking} from "./IChiLocking.sol";
import {IStaking} from "./IStaking.sol";

interface IChiStaking is IStaking {
  event Lock(address indexed account, uint256 amount, uint256 duration, bool useStakedTokens);
  event ClaimStETH(address indexed account, uint256 amount);
  event SetChiLocking(address indexed chiLocking);
  event SetRewardController(address indexed rewardController);

  error InvalidDuration(uint256 duration);

  /// @notice Sets address of chiLocking contract
  /// @param _chiLocking Address of chiLocking contract
  function setChiLocking(IChiLocking _chiLocking) external;

  /// @notice Updates epoch data
  /// @param stETHrewards Amount of stETH rewards for chi stakers that is emitted in current epoch
  /// @custom:usage This function should be called from rewardController contract in purpose of updating epoch data
  function updateEpoch(uint256 stETHrewards) external;

  /// @notice Locks given amount of chi tokens for given duration for caller
  /// @dev If caller want to use staked tokens for locking, function will unstake them first
  /// @param amount Amount of chi tokens to lock
  /// @param duration Locking duration in epochs
  /// @param useStakedTokens If true, then staked tokens will be used for locking
  function lock(uint256 amount, uint256 duration, bool useStakedTokens) external;
}

contracts/interfaces/IChiVesting.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IChiVesting {
  struct VestingData {
    uint256 startAmount;
    uint256 shares;
    uint256 unlockedChi;
    uint256 lastWithdrawnEpoch;
    uint256 unclaimedStETH;
    uint256 lastClaimedEpoch;
  }

  struct EpochData {
    uint256 cumulativeStETHRewardPerShare;
    uint256 cumulativeUnlockedPerShare;
  }

  event AddVesting(address indexed account, uint256 amount, uint256 shares);
  event UpdateEpoch(uint256 indexed epoch, uint256 stETHrewards, uint256 totalLockedChi);
  event WithdrawChi(address indexed account, uint256 amount);
  event ClaimStETH(address indexed account, uint256 amount);
  event SetRewardController(address indexed rewardController);
  event SetChiVester(address indexed chiVester, bool indexed toSet);

  error NotRewardController();
  error NotChiVester();
  error CliffPassed();
  error UnavailableWithdrawAmount(uint256 amount);

  /// @notice Gets cliff duration
  /// @return duration Cliff duration
  function cliffDuration() external view returns (uint256 duration);

  /// @notice Sets address of rewardController contract
  /// @param rewardController Address of rewardController contract
  function setRewardController(address rewardController) external;

  /// @notice Updates status of contract that can add vesting, TimeWeightedBonding contract in this case
  /// @param contractAddress Address of contract
  /// @param toSet Status to set
  function setChiVester(address contractAddress, bool toSet) external;

  /// @notice Gets total locked chi amount
  /// @return lockedChi Total locked chi amount
  function getLockedChi() external view returns (uint256 lockedChi);

  /// @notice Vests given amount of chi tokens for given account
  /// @param account Account to vest tokens for
  /// @param chiAmount Amount of chi tokens to vest
  /// @custom:usage This function should be called from TimeWeightedBonding contract in purpose of vesting chi tokens
  function addVesting(address account, uint256 chiAmount) external;

  /// @notice Updates epoch data
  /// @param chiEmissions Amount of chi incentives for vesters in current epoch
  /// @param stETHrewards Amount of stETH rewards for vesters that is emitted in current epoch
  /// @custom:usage This function should be called from rewardController contract in purpose of updating epoch data
  function updateEpoch(uint256 chiEmissions, uint256 stETHrewards) external;

  /// @notice Withdraws vested chi tokens for caller
  /// @dev Contract hold vested chi tokens and inside this function it transfers them to caller
  /// @param amount Amount of chi tokens to withdraw
  function withdrawChi(uint256 amount) external;

  /// @notice Claims stETH rewards for given account
  /// @notice This contract does not send stETH rewards nor holds them, reserveHolder does that
  /// @notice This contract only calculates and updates unclaimed stETH amount for given account
  /// @param account Account to claim stETH rewards for
  /// @return amount Amount of stETH rewards that user can claim
  /// @custom:usage This function should be called from rewardController contract in purpose of claiming stETH rewards
  function claimStETH(address account) external returns (uint256 amount);

  /// @notice Calculates and returns unclaimed stETH rewards for given account
  /// @param account Account to calculate unclaimed stETH rewards for
  /// @return amount Amount of unclaimed stETH rewards
  function unclaimedStETHAmount(address account) external view returns (uint256 amount);

  /// @notice Calculates and returns voting power earned from vesting for given account
  /// @param account Account to calculate voting power for
  /// @return votingPower Voting power earned from vesting
  function getVotingPower(address account) external view returns (uint256 votingPower);

  /// @notice Gets total voting power
  /// @return totalVotingPower Total voting power
  function getTotalVotingPower() external view returns (uint256 totalVotingPower);

  /// @notice Calculates and returns chi amount that is available for withdrawing for given account
  /// @param account Account to calculate available chi amount for
  /// @return availableChi Total amount of chi that is available for withdrawing
  function availableChiWithdraw(address account) external view returns (uint256 availableChi);
}

contracts/interfaces/ICurvePool.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface ICurvePool {
  /// @notice Swaps tokens
  /// @param i Index of token to swap from
  /// @param j Index of token to swap to
  /// @param dx Amount of tokens to swap
  /// @param min_dy Minimum amount of tokens to receive
  /// @return dy Amount of tokens received
  function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external payable returns (uint256 dy);
}

contracts/interfaces/ILPRewards.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface ILPRewards {
  struct LockingTokenData {
    uint256 amountLocked;
    uint64 lastClaimedEpoch;
    uint64 endingEpoch;
  }

  struct EpochData {
    int256 totalDeltaAmountLocked;
    int256 cumulativeProfit;
  }

  event LockLP(uint256 indexed lockingTokenId, uint256 amount, uint64 currentEpoch, uint64 endingEpoch);
  event ClaimRewards(uint256 indexed lockingTokenId, address indexed account, uint256 amount, int256 rewardUSD);
  event UpdateEpoch(uint64 indexed epoch, uint256 lpValue, int256 totalAmountLocked, int256 profitPerToken);
  event RecoverLPTokens(address indexed account, uint256 amount);
  event SetOCHI(address indexed ochi);

  error LockingTokenIdAlreadyUsed(uint256 lockingTokenId);
  error ClaimngRewardLessThanZero();
  error NotOCHI();

  /// @notice Gets current epoch
  /// @return currentEpoch Current epoch
  function currentEpoch() external view returns (uint64 currentEpoch);

  /// @notice Sets address of OCHI contract
  /// @param _ochi Address of OCHI contract
  /// @custom:usage This function should be called only once during deployment
  /// @custom:usage Caller must be owner
  function setOCHI(address _ochi) external;

  /// @notice Locks LP tokens for given period, user gets rewards until the end of the period
  /// @param lockingTokenId Unique OCHI id
  /// @param amount Amount of LP tokens to lock
  /// @param epochDuration Locking duration in epochs
  /// @custom:usage This function should be called from OCHI contract in purpose of locking LP tokens
  function lockLP(uint256 lockingTokenId, uint256 amount, uint64 epochDuration) external;

  /// @notice Claims rewards for given token id
  /// @param lockingTokenId Unique OCHI id
  /// @param account Account to send rewards to
  /// @custom:usage This function should be called from OCHI contract in purpose of claiming rewards
  function claimRewards(uint256 lockingTokenId, address account) external;

  /// @notice End current epoch and start new one
  /// @custom:usage This function should be called from OCHI contract when epoch is updated
  function updateEpoch() external;

  /// @notice Takes LP tokens from contract and sends them to receiver
  /// @param receiver Account to send LP tokens to
  /// @custom:usage This function should be called only in case of moving liquidity to another pool
  function recoverLPTokens(address receiver) external;

  /// @notice Calculates unclaimed rewards for given token id
  /// @param lockingTokenId Unique OCHI id
  /// @return rewardUSD Amount of unclaimed rewards in USD
  function calculateUnclaimedReward(uint256 lockingTokenId) external view returns (int256 rewardUSD);
  
  /// @notice returns profit in USD for the last epoch
  /// @return profit profit in USD
  function getLastEpochProfit() external view returns (int256 profit);
}

contracts/interfaces/ILPStaking.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {IStakingWithEpochs} from "./IStakingWithEpochs.sol";
import {IStaking} from "./IStaking.sol";

interface ILPStaking is IStakingWithEpochs, IStaking {
  event UpdateEpoch(uint256 indexed epoch, uint256 chiEmissions);
  event LockChi(address indexed account, uint256 amount, uint256 duration);
  event ClaimStETH(address indexed account, uint256 amount);

  error InvalidDuration(uint256 duration);

  function updateEpoch(uint256, uint256) external;

  function lockChi(uint256) external;
}

contracts/interfaces/IMintableBurnable.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

interface IMintableBurnable is IERC20 {
  function mint(address to, uint256 amount) external;

  function burnFrom(address from, uint256 amount) external;
}

contracts/interfaces/IMintableERC20.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

interface IMintableERC20 is IERC20 {
  function mint(address account, uint256 amount) external;
}

contracts/interfaces/IOCHI.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IOCHI {
  struct ChiOption {
    uint256 amount;
    uint256 strikePrice;
    uint256 uscEthPairAmount;
    uint256 chiEthPairAmount;
    uint64 lockedUntil;
    uint64 validUntil;
  }

  event Mint(
    uint256 indexed tokenId,
    uint256 chiAmount,
    uint256 uscEthPairAmount,
    uint256 chiEthPairAmount,
    uint64 lockPeriodInEpochs,
    uint256 strikePrice,
    uint256 oChiAmount
  );
  event Burn(address indexed account, uint256 indexed tokenId, uint256 chiAmount);
  event UpdateEpoch(uint64 indexed epoch, uint256 timestamp);
  event ClaimRewardsOCHI(uint256 indexed tokenId);
  event RecoverLPTokens();

  error PolTargetRatioExceeded();
  error InvalidLockPeriod(uint256 lockPeriod);
  error NotAllowed(uint256 tokenId);
  error OptionLocked(uint256 tokenId);
  error OptionExpired(uint256 tokenId);
  error EpochNotFinished();

  /// @notice Mint OCHI tokens for given period, user gets rewards until the end of the period
  /// @param chiAmount Amount of CHI tokens user wants to burn in order to boost his discount in option
  /// @param uscEthPairAmount Amount of USC/ETH LP tokens user wants to lock and sell to protocol
  /// @param chiEthPairAmount Amount of CHI/ETH LP tokens user wants to lock and sell to protocol
  /// @param lockPeriodInEpochs Locking duration in epochs
  function mint(
    uint256 chiAmount,
    uint256 uscEthPairAmount,
    uint256 chiEthPairAmount,
    uint64 lockPeriodInEpochs
  ) external;

  /// @notice Burn OCHI token in order to execute option and get his discounted CHI
  /// @notice When lock period expires user has lock period window to execute option, after that option can not be executed
  /// @param tokenId Unique OCHI id
  function burn(uint256 tokenId) external;

  /// @notice Ends current epoch and start new one
  function updateEpoch() external;

  /// @notice Claims rewards for given token id
  /// @param tokenId Unique OCHI id
  function claimRewards(uint256 tokenId) external;

  /// @notice Returns unclaimed rewards value for given token id
  /// @param tokenId Unique OCHI id
  /// @return rewardsUSD rewards value in USD
  function getUnclaimedRewardsValue(uint256 tokenId) external view returns (int256 rewardsUSD);

  /// @notice Recovers LP tokens from rewards contract
  /// @custom:usage This function should be called only in case of moving liquidity to another pool
  function recoverLPTokens() external;

  function calculateOptionData(
    uint256 chiAmount,
    uint256 uscEthPairAmount,
    uint256 chiEthPairAmount,
    uint256 lockPeriodInEpochs
  ) external view returns (uint256 strikePrice, uint256 oChiAmount);

  function getAndValidatePositionsData(
    uint256 uscEthPairAmount,
    uint256 chiEthPairAmount
  ) external view returns (uint256 multiplier, uint256 value);

  function getLastEpochTotalReward() external view returns (int256 totalReward);

  function claimAllRewards() external;
}

contracts/interfaces/IPriceFeedAggregator.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IPriceFeedAggregator {
  event SetPriceFeed(address indexed base, address indexed feed);

  error ZeroAddress();

  /// @notice Sets price feed adapter for given token
  /// @param base Token address
  /// @param feed Price feed adapter address
  function setPriceFeed(address base, address feed) external;

  /// @notice Gets price for given token
  /// @param base Token address
  /// @return price Price for given token
  function peek(address base) external view returns (uint256 price);
}

contracts/interfaces/IReserveHolder.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IReserveHolder {
  event SetArbitrager(address indexed arbitrager, bool enabled);
  event SetClaimer(address indexed claimer);
  event SetEthThreshold(uint256 threshold);
  event SetSwapEthTolerance(uint256 tolerance);
  event SetCurveStEthSafeGuardPercentage(uint256 percentage);
  event Deposit(address indexed account, uint256 amount);
  event Rebalance(uint256 ethAmount, uint256 stEthAmount);
  event Redeem(address indexed account, uint256 amount);
  event RedeemSwap(uint256 ethAmount, uint256 stEthAmount);
  event ClaimRewards(address indexed account, uint256 amount);
  event Receive(address indexed account, uint256 amount);

  error NotArbitrager(address _account);
  error NotClaimer(address _account);
  error ThresholdTooHigh(uint256 _threshold);
  error SafeGuardTooHigh(uint256 _safeGuard);
  error EtherSendFailed(address _account, uint256 _amount);

  /// @notice Updates arbitrager status
  /// @param arbitrager Arbitrager address
  /// @param status Arbitrager status
  function setArbitrager(address arbitrager, bool status) external;

  /// @notice Sets claimer address
  /// @param claimer Claimer address
  /// @custom:usage Claimer should be rewardController contract
  function setClaimer(address claimer) external;

  /// @notice Sets eth threshold
  /// @param ethThreshold Eth threshold
  /// @custom:usage Eth threshold should be set in percentage
  /// @custom:usage Part of reserves is in WETH so arbitrage contract can use them without swapping stETH for ETH
  function setEthThreshold(uint256 ethThreshold) external;

  /// @notice Sets swap eth tolerance
  /// @param swapEthTolerance Swap eth tolerance
  /// @custom:usage Swap eth tolerance should be set in wei
  /// @custom:usage Absolute tolerance for swapping stETH for ETH
  function setSwapEthTolerance(uint256 swapEthTolerance) external;

  /// @notice Sets curve stETH safe guard percentage
  /// @param curveStEthSafeGuardPercentage Curve stETH safe guard percentage
  function setCurveStEthSafeGuardPercentage(uint256 curveStEthSafeGuardPercentage) external;

  /// @notice Gets reserve value in USD
  /// @return reserveValue Reserve value in USD
  function getReserveValue() external view returns (uint256 reserveValue);

  /// @notice Gets current rewards generated by stETH
  /// @return currentRewards Current rewards generated by stETH
  function getCurrentRewards() external view returns (uint256 currentRewards);

  /// @notice Gets cumulative rewards generated by stETH
  /// @return cumulativeRewards Cumulative rewards generated by stETH
  function getCumulativeRewards() external view returns (uint256 cumulativeRewards);

  /// @notice Deposits stETH to reseves
  /// @param amount Amount of stETH to deposit
  function deposit(uint256 amount) external;

  /// @notice Rebalance reserve in order to achieve balace/ethThreshold ratio
  /// @dev If there is more WETH than ethThreshold then unwrap WETH and get stETH from Lido
  /// @dev If there is less WETH than ethThreshold then swap stETH for WETH on UniV2
  /// @custom:usage This function should be called by external keeper
  function rebalance() external;

  /// @notice Redeems stETH from reserves
  /// @param amount Amount of stETH to redeem
  /// @return wethAmount Amount of WETH received
  /// @custom:usage This function should be called by arbitrage contract
  function redeem(uint256 amount) external returns (uint256 wethAmount);

  /// @notice Claims stETH rewards in given amount for given account
  /// @notice Contract does not perform any check and is relying on rewardController contract to perform them
  /// @param account Account to claim stETH rewards for
  /// @param amount Amount of stETH to claim
  /// @custom:usage This function should be called by rewardController contract
  function claimRewards(address account, uint256 amount) external;

  /// @notice Wrapps ETH to WETH
  /// @dev Users can buy USC with ETH which is transfered to this contract. This function should be called to wrapp than ETH to WETH
  /// @custom:usage This function should be called by external keeper
  function wrapETH() external;
}

contracts/interfaces/IRewardController.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

interface IRewardController {
  struct EpochData {
    uint256 totalUscReward;
    uint256 reserveHolderTotalRewards;
  }

  struct StETHRewards {
    uint256 uscStakingStEthReward;
    uint256 chiStakingStEthReward;
    uint256 chiLockingStEthReward;
    uint256 chiVestingStEthReward;
    uint256 uscEthLPStakingStEthReward;
    uint256 chiEthLPStakingStEthReward;
  }

  struct ChiIncentives {
    uint256 uscStakingChiIncentives;
    uint256 chiLockingChiIncentives;
    uint256 chiVestingChiIncentives;
  }

  event RewardUSC(address indexed account, uint256 amount);
  event UpdateEpoch(uint256 indexed epoch, uint256 totalStEthReward, uint256 totalChiIncentives);
  event ClaimStEth(address indexed account, uint256 amount);
  event SetChiIncentivesPerEpoch(uint256 indexed chiIncentivesPerEpoch);
  event SetArbitrager(address indexed arbitrager);
  event UpdateArbitrager(address indexed account, bool isArbitrager);

  error ZeroAmount();
  error NotArbitrager();
  error EpochNotFinished();

  /// @notice Set amount of chi incentives per epoch for chi lockers
  /// @param _chiIncentivesForChiLocking Amount of chi incentives per epoch
  function setChiIncentivesForChiLocking(uint256 _chiIncentivesForChiLocking) external;

  /// @notice Set amount of chi incentives per epoch for USC staking
  /// @param _chiIncentivesForUscStaking Amount of chi incentives per epoch
  function setChiIncentivesForUscStaking(uint256 _chiIncentivesForUscStaking) external;

  /// @notice Set amount of chi incentives per epoch for USC-ETH LP staking contracts
  /// @param _chiIncentivesForUscEthLPStaking Amount of chi incentives per epoch
  function setChiIncentivesForUscEthLPStaking(uint256 _chiIncentivesForUscEthLPStaking) external;

  /// @notice Set amount of chi incentives per epoch for CHI-ETH LP staking contracts
  /// @param _chiIncentivesForChiEthLPStaking Amount of chi incentives per epoch
  function setChiIncentivesForChiEthLPStaking(uint256 _chiIncentivesForChiEthLPStaking) external;

  /// @notice Sets arbitrager contract, deprecated in favor of updateArbitrager
  /// @param _arbitrager Arbitrager contract
  function setArbitrager(IArbitrage _arbitrager) external;

  /// @notice Sets arbitrager contract
  /// @param account Account to update arbitrager status for
  /// @param status True if account is arbitrager, false otherwise
  function updateArbitrager(address account, bool status) external;

  /// @notice Freezes given amount of USC token
  /// @dev Frozen tokens are not transfered they are burned and later minted again when conditions are met
  /// @param amount Amount of USC tokens to freeze
  /// @custom:usage This function should be called from Arbitrager contract in purpose of freezing USC tokens
  function rewardUSC(uint256 amount) external;

  /// @notice Updates epoch data
  /// @dev This functio will update epochs in all subcontracts and will distribute chi incentives and stETH rewards
  /// @custom:usage This function should be called once a week in order to end current epoch and start new one
  /// @custom:usage Thsi function ends current epoch and distributes chi incentives and stETH rewards to all contracts in this epoch
  function updateEpoch() external;

  /// @notice Claims stETH rewards for caller
  /// @dev This function will claim stETH rewards from all subcontracts and will send them to caller
  /// @dev Thsi contract does not hold stETH, instead it sends it through reserveHolder contract
  function claimStEth() external;

  /// @notice Calculates and returns unclaimed stETH amount for given account in all subcontracts
  /// @param account Account to calculate unclaimed stETH amount for
  /// @return totalAmount Total amount of unclaimed stETH for given account
  function unclaimedStETHAmount(address account) external view returns (uint256 totalAmount);
}

contracts/interfaces/ISTETH.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

interface ISTETH is IERC20 {
  function submit(address referral) external payable returns (uint256);
}

contracts/interfaces/IStaking.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

interface IStaking is IStakingWithEpochs {
  /// @notice Sets address of rewardController contract
  /// @param rewardController Address of rewardController contract
  function setRewardController(address rewardController) external;

  /// @notice Gets total staked chi amount
  /// @return stakedChi Total staked chi amount
  function getStakedChi() external view returns (uint256 stakedChi);

  /// @notice Claims stETH rewards for given account
  /// @notice This contract does not send stETH rewards nor holds them, reserveHolder does that
  /// @notice This contract only calculates and updates unclaimed stETH amount for given account
  /// @param account Account to claim stETH rewards for
  /// @return amount Amount of stETH rewards that user can claim
  /// @custom:usage This function should be called from rewardController contract in purpose of claiming stETH rewards
  function claimStETH(address account) external returns (uint256 amount);

  /// @notice Calculates and returns unclaimed stETH rewards for given account
  /// @param account Account to calculate unclaimed stETH rewards for
  /// @return amount Amount of unclaimed stETH rewards
  function unclaimedStETHAmount(address account) external view returns (uint256 amount);
}

contracts/interfaces/IStakingWithEpochs.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IStakingWithEpochs {
  enum RewardToken {
    USC,
    CHI,
    STETH
  }

  struct EpochData {
    uint256 shares;
    mapping(RewardToken => uint256) cumulativeRewardsPerShare;
  }

  struct StakeData {
    uint256 lastUpdatedEpoch;
    uint256 shares;
    uint256 addSharesNextEpoch;
    mapping(RewardToken => uint256) unclaimedRewards;
  }

  event Stake(address indexed account, uint256 amount);
  event Unstake(address indexed account, address indexed toAddress, uint256 amount);

  error ZeroAmount();
  error NotRewardController();
  error AmountBelowStakedBalance(uint256 stakedBalance, uint256 amount);

  /// @notice Gets current reward for given account and token
  /// @param account Account to get reward for
  /// @param token Token to get reward for
  /// @return amount Current reward for given account and token
  /// @custom:usage This function should be used in inheriting contracts to get current reward for given account and token
  function getUnclaimedRewards(address account, RewardToken token) external view returns (uint256 amount);

  /// @notice Gets cumulative reward per share for given account and token
  /// @param epoch Epoch to get cumulative reward per share for
  /// @param token Token to get cumulative reward per share for
  /// @return amount Cumulative reward per share for given epoch and token
  /// @custom:usage This function should be used in inheriting contracts to get cumulative reward per share for given epoch and token
  function getCumulativeRewardsPerShare(uint256 epoch, RewardToken token) external view returns (uint256 amount);

  /// @notice Stakes given amount of tokens
  /// @param amount Amount of tokens to stake
  /// @custom:usage This function should be called from inheriting contracts to stake tokens
  /// @custom:usage Logic should be the same for both uscStaking and chiStaking contracts
  function stake(uint256 amount) external;

  /// @notice Unstakes given amount of tokens, sends tokens to msg.sender by default
  /// @param amount Amount of tokens to unstake
  /// @custom:usage This function should be called from inheriting contracts to unstake tokens
  /// @custom:usage Logic should be the same for both uscStaking and chiStaking contracts
  function unstake(uint256 amount) external;

  /// @notice Unstakes given amount of tokens
  /// @param amount Amount of tokens to unstake
  /// @param toAddress Address to send tokens
  /// @custom:usage This function should be called from inheriting contracts to unstake tokens
  /// @custom:usage Logic should be the same for both uscStaking and chiStaking contracts
  function unstake(uint256 amount, address toAddress) external;
}

contracts/interfaces/IUSCStaking.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IStaking} from "./IStaking.sol";
import {IArbitrage} from "./IArbitrage.sol";

interface IUSCStaking is IStaking {
  event UpdateEpoch(uint256 indexed epoch, uint256 chiEmissions, uint256 uscRewards, uint256 stETHrewards);
  event LockChi(address indexed account, uint256 amount, uint256 duration);
  event ClaimUSCRewards(address indexed account, uint256 amount);
  event ClaimStETH(address indexed account, uint256 amount);

  error NotClaimable();
  error InvalidDuration(uint256 duration);

  /// @notice Updates epoch data
  /// @param chiEmissions Amount of CHI token incentives emitted in current epoch for USC stakers
  /// @param uscRewards Amount of USC token frozen in current epoch for USC stakers
  /// @param stETHrewards Amount of stETH token rewards in current epoch for USC stakers
  /// @custom:usage This function should be called from rewardController contract in purpose of updating epoch data
  function updateEpoch(uint256 chiEmissions, uint256 uscRewards, uint256 stETHrewards) external;

  /// @notice Locks CHI tokens that user earned from incentives for given duration
  /// @param duration Locking duration in epochs
  function lockChi(uint256 duration) external;

  /// @notice Claims USC rewards for caller
  /// @dev This function can be called only when price is above target and there is excess of reserves
  function claimUSCRewards() external;
}

contracts/interfaces/IWETH.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

interface IWETH is IERC20 {
  function deposit() external payable;

  function withdraw(uint256 amount) external;
}

contracts/library/ExternalContractAddresses.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @notice external contract addresses on Ethereum Mainnet
library ExternalContractAddresses {
  address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
  address public constant stETH = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;
  address public constant UNI_V2_SWAP_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
  address public constant UNI_V2_POOL_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
  address public constant ETH_USD_CHAINLINK_FEED = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419;
  address public constant STETH_USD_CHAINLINK_FEED = 0xCfE54B5cD566aB89272946F602D76Ea879CAb4a8;
  address public constant CURVE_ETH_STETH_POOL = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022;
}

contracts/periphery/DataProvider.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../library/ExternalContractAddresses.sol";
import "../interfaces/IPriceFeedAggregator.sol";
import "../interfaces/IStakingWithEpochs.sol";
import "../interfaces/IOCHI.sol";
import "../staking/RewardControllerV2.sol";
import "../staking/ChiStaking.sol";
import "../staking/ChiLocking.sol";
import "../staking/LPStaking.sol";
import "../staking/ChiVesting.sol";
import "../dso/PoolHelper.sol";
import "../dso/OCHI.sol";
import "../interfaces/IOCHI.sol";
import "../staking/USCStaking.sol";
import "../ReserveHolder.sol";
import "../dso/LPRewards.sol";

/// @title Data provider
/// @notice Data provider containing view functions used by frontend
contract DataProvider {
  using SafeCast for uint256;

  struct StEthReward {
    uint256 tokenValue;
    uint256 usdValue;
  }

  struct ChiReward {
    uint256 tokenValue;
    uint256 usdValue;
  }

  struct UscReward {
    uint256 tokenValue;
    uint256 usdValue;
  }

  struct Reward {
    StEthReward stEthReward;
    ChiReward chiReward;
    UscReward uscReward;
    uint256 totalReward;
  }

  struct Rewards {
    Reward stUscRewards;
    Reward stChiRewards;
    Reward veChiRewards;
    Reward uscEthLpRewards;
    Reward chiEthLpRewards;
    uint256 totalStEthReward;
    uint256 totalStEthRewardUsd;
    uint256 totalChiReward;
    uint256 totalChiRewardUsd;
  }

  function POLdata(
    OCHI dso,
    IUniswapV2Pair uniPair,
    IPriceFeedAggregator priceFeed
  ) external view returns (uint256 polUsdValue, uint256 polPercent) {
    uint256 lpAmount = uniPair.balanceOf(address(dso.lpRewards(uniPair)));
    polUsdValue = PoolHelper.getUSDValueForLP(lpAmount, uniPair, priceFeed);
    polPercent = Math.mulDiv(lpAmount, 10 ** 18, uniPair.totalSupply());
  }

  function getLPTokenPrice(
    IUniswapV2Pair pair,
    IPriceFeedAggregator priceFeedAggregator
  ) public view returns (uint256) {
    return PoolHelper.getUSDValueForLP(1 ether, pair, priceFeedAggregator);
  }

  function getTotalPoolValue(
    IUniswapV2Pair pair,
    IPriceFeedAggregator priceFeedAggregator
  ) public view returns (uint256) {
    return PoolHelper.getTotalPoolUSDValue(pair, priceFeedAggregator);
  }

  function chiStakingAPR(
    address chi,
    ChiStaking chiStaking,
    ChiLocking chiLocking,
    USCStaking uscStaking,
    LPStaking uscEthLpStaking,
    LPStaking chiEthLpStaking,
    ChiVesting chiVesting,
    RewardControllerV2 rewardController,
    IPriceFeedAggregator priceFeedAggregator,
    ReserveHolder reserveHolder
  ) public view returns (uint256) {
    uint256 stEthPrice = priceFeedAggregator.peek(ExternalContractAddresses.stETH);
    uint256 chiPrice = priceFeedAggregator.peek(chi);
    uint256 totalStakedChi = chiStaking.getStakedChi() +
      chiLocking.getStakedChi() +
      uscStaking.getStakedChi() +
      uscEthLpStaking.getStakedChi() +
      chiEthLpStaking.getStakedChi() +
      chiVesting.getLockedChi();
    uint256 chiStakedValue = Math.mulDiv(totalStakedChi, chiPrice, 1e8);

    uint256 currentEpoch = chiStaking.currentEpoch();

    (, uint256 totalRewardsTwoEpochsAgo) = currentEpoch >= 2 ? rewardController.epochs(currentEpoch - 2) : (0, 0);
    (, uint256 totalRewardsLastEpoch) = rewardController.epochs(currentEpoch - 1);

    uint256 totalEthReward;
    if (currentEpoch < 4) {
      totalEthReward = (reserveHolder.totalStEthDeposited() * 4) / 100 / 52;
    } else {
      totalEthReward = totalRewardsLastEpoch - totalRewardsTwoEpochsAgo;
    }

    uint256 totalEthRewardValue = Math.mulDiv(totalEthReward, stEthPrice, 1e8);

    return Math.mulDiv(totalEthRewardValue * 52, 1e18, chiStakedValue);
  }

  function uscStakingAPR(
    address chi,
    ChiStaking chiStaking,
    ChiLocking chiLocking,
    USCStaking uscStaking,
    LPStaking uscEthLpStaking,
    LPStaking chiEthLpStaking,
    ChiVesting chiVesting,
    RewardControllerV2 rewardController,
    IPriceFeedAggregator priceFeedAggregator,
    ReserveHolder reserveHolder
  ) external view returns (uint256 totalApr, uint256 uscApr, uint256 chiApr, uint256 boostedStChiApr) {
    uint256 currentEpoch = rewardController.currentEpoch();
    uint256 stChiApr = chiStakingAPR(
      chi,
      chiStaking,
      chiLocking,
      uscStaking,
      uscEthLpStaking,
      chiEthLpStaking,
      chiVesting,
      rewardController,
      priceFeedAggregator,
      reserveHolder
    );
    uint256 chiEmissions = rewardController.chiIncentivesForUscStaking();
    uint256 totalUscStaked = uscStaking.totalSupply();
    boostedStChiApr = (stChiApr * chiEmissions * 52) / totalUscStaked;

    uint256 chiPrice = priceFeedAggregator.peek(chi);
    uint256 chiEmissionsValue = Math.mulDiv(chiEmissions, chiPrice, 1e8);
    chiApr = Math.mulDiv(chiEmissionsValue * 52, 1e18, totalUscStaked);

    (uint256 uscRewardAmount, ) = rewardController.epochs(currentEpoch - 1);
    uscApr = Math.mulDiv(uscRewardAmount * 52, 1e18, totalUscStaked);

    return (boostedStChiApr + chiApr + uscApr, uscApr, chiApr, boostedStChiApr);
  }

  function chiLockingAPR(
    address chi,
    ChiStaking chiStaking,
    ChiLocking chiLocking,
    USCStaking uscStaking,
    LPStaking uscEthLpStaking,
    LPStaking chiEthLpStaking,
    ChiVesting chiVesting,
    RewardControllerV2 rewardController,
    IPriceFeedAggregator priceFeedAggregator,
    ReserveHolder reserveHolder
  ) public view returns (uint256 totalApr, uint256 chiApr, uint256 stChiApr, uint256 boostedStChiApr) {
    uint256 chiPrice = priceFeedAggregator.peek(chi);
    uint256 totalLockedChiValue = Math.mulDiv(chiLocking.getLockedChi() + chiVesting.getLockedChi(), chiPrice, 1e8);
    uint256 chiEmissions = rewardController.chiIncentivesForChiLocking();
    uint256 chiEmissionsValue = Math.mulDiv(chiEmissions, chiPrice, 1e8);
    chiApr = Math.mulDiv(chiEmissionsValue * 52, 1e18, totalLockedChiValue);
    stChiApr = chiStakingAPR(
      chi,
      chiStaking,
      chiLocking,
      uscStaking,
      uscEthLpStaking,
      chiEthLpStaking,
      chiVesting,
      rewardController,
      priceFeedAggregator,
      reserveHolder
    );

    boostedStChiApr = Math.mulDiv(chiEmissionsValue, stChiApr * 52, totalLockedChiValue);

    return (chiApr + stChiApr + boostedStChiApr, chiApr, stChiApr, boostedStChiApr);
  }

  function dsoAPR(
    address chi,
    OCHI ochi,
    IPriceFeedAggregator priceFeedAggregator
  ) external view returns (uint256 apr, int256 tradingFees) {
    LPRewards uscEthLpRewards = LPRewards(address(ochi.lpRewards(ochi.uscEthPair())));
    LPRewards chiEthLpRewards = LPRewards(address(ochi.lpRewards(ochi.chiEthPair())));

    int256 profitPerTokenUscEth = uscEthLpRewards.getLastEpochProfit();
    int256 profitPerTokenChiEth = chiEthLpRewards.getLastEpochProfit();

    int256 lpBalanceUscEth = uscEthLpRewards.epochMinLPBalance().toInt256();
    int256 lpBalanceChiEth = chiEthLpRewards.epochMinLPBalance().toInt256();

    int256 totalProfitPrevWeek = ((profitPerTokenUscEth * lpBalanceUscEth) / 1e18) +
      ((profitPerTokenChiEth * lpBalanceChiEth) / 1e18);

    if (totalProfitPrevWeek < 0) {
      return (0, 0);
    }

    uint256 totalChiLocked = ochi.totalOCHIlocked();
    uint256 chiPrice = priceFeedAggregator.peek(chi);
    uint256 totalChiLockedValue = Math.mulDiv(totalChiLocked, chiPrice, 1e18);

    return (Math.mulDiv(uint256(totalProfitPrevWeek) * 52, 1e18, totalChiLockedValue), totalProfitPrevWeek);
  }

  function uscEthLPAPR(
    address chi,
    ChiStaking chiStaking,
    ChiLocking chiLocking,
    USCStaking uscStaking,
    LPStaking uscEthLpStaking,
    LPStaking chiEthLpStaking,
    ChiVesting chiVesting,
    RewardControllerV2 rewardController,
    IPriceFeedAggregator priceFeedAggregator,
    IUniswapV2Pair uscEthPair,
    ReserveHolder reserveHolder
  ) external view returns (uint256 totalApr, uint256 chiApr, uint256 stChiApr) {
    uint256 chiPrice = priceFeedAggregator.peek(chi);
    uint256 chiEmissions = rewardController.chiIncentivesForUscEthLPStaking();
    uint256 chiEmissionsValue = Math.mulDiv(chiEmissions, chiPrice, 1e8);

    uint256 totalStaked = uscEthLpStaking.totalSupply();
    uint256 uscEthPairPrice = getLPTokenPrice(uscEthPair, priceFeedAggregator);
    uint256 totalStakedValue = Math.mulDiv(totalStaked, uscEthPairPrice, 1e8);
    chiApr = Math.mulDiv(chiEmissionsValue * 52, 1e18, totalStakedValue);

    uint256 chiStakingAPR = chiStakingAPR(
      chi,
      chiStaking,
      chiLocking,
      uscStaking,
      uscEthLpStaking,
      chiEthLpStaking,
      chiVesting,
      rewardController,
      priceFeedAggregator,
      reserveHolder
    );
    stChiApr = Math.mulDiv(chiEmissionsValue, chiStakingAPR * 52, totalStakedValue);

    return (chiApr + stChiApr, chiApr, stChiApr);
  }

  function chiEthLPAPR(
    address chi,
    ChiStaking chiStaking,
    ChiLocking chiLocking,
    USCStaking uscStaking,
    LPStaking uscEthLpStaking,
    LPStaking chiEthLpStaking,
    ChiVesting chiVesting,
    RewardControllerV2 rewardController,
    IPriceFeedAggregator priceFeedAggregator,
    IUniswapV2Pair chiEthPair,
    ReserveHolder reserveHolder
  ) external view returns (uint256 totalApr, uint256 chiApr, uint256 stChiApr) {
    uint256 chiPrice = priceFeedAggregator.peek(chi);
    uint256 chiEmissions = rewardController.chiIncentivesForChiEthLPStaking();
    uint256 chiEmissionsValue = Math.mulDiv(chiEmissions, chiPrice, 1e8);

    uint256 totalStaked = chiEthLpStaking.totalSupply();
    uint256 chiEthPairPrice = getLPTokenPrice(chiEthPair, priceFeedAggregator);
    uint256 totalStakedValue = Math.mulDiv(totalStaked, chiEthPairPrice, 1e8);
    chiApr = Math.mulDiv(chiEmissionsValue * 52, 1e18, totalStakedValue);

    uint256 chiStakingAPR = chiStakingAPR(
      chi,
      chiStaking,
      chiLocking,
      uscStaking,
      uscEthLpStaking,
      chiEthLpStaking,
      chiVesting,
      rewardController,
      priceFeedAggregator,
      reserveHolder
    );
    stChiApr = Math.mulDiv(chiEmissionsValue, chiStakingAPR * 52, totalStakedValue);

    return (chiApr + stChiApr, chiApr, stChiApr);
  }

  function estimatedYieldPerWeek(
    address chi,
    ChiStaking chiStaking,
    ChiLocking chiLocking,
    USCStaking uscStaking,
    LPStaking uscEthLpStaking,
    LPStaking chiEthLpStaking,
    ChiVesting chiVesting,
    RewardControllerV2 rewardController,
    IPriceFeedAggregator priceFeedAggregator,
    ReserveHolder reserveHolder
  ) external view returns (uint256) {
    (uint256 chiLockingApr, , , ) = chiLockingAPR(
      chi,
      chiStaking,
      chiLocking,
      uscStaking,
      uscEthLpStaking,
      chiEthLpStaking,
      chiVesting,
      rewardController,
      priceFeedAggregator,
      reserveHolder
    );
    uint256 totalLockedChi = chiLocking.getLockedChi() + chiVesting.getLockedChi();
    uint256 chiPrice = priceFeedAggregator.peek(chi);
    uint256 totalLockedChiValue = Math.mulDiv(totalLockedChi, chiPrice, 1e18);
    uint256 chiLockingWeeklyAPR = chiLockingApr / 52;

    return Math.mulDiv(totalLockedChiValue, chiLockingWeeklyAPR, 1e18);
  }

  function totalValueOfLockedChi(
    IPriceFeedAggregator priceFeedAggregator,
    ChiLocking chiLocking,
    ChiVesting chiVesting,
    address chi,
    address account
  ) external view returns (uint256) {
    IChiLocking.AllLockedPositionsOutput[] memory lockedPositions = chiLocking.getAllLockedPositions(account);

    uint256 totalChi;
    for (uint256 i = 0; i < lockedPositions.length; i++) {
      totalChi += lockedPositions[i].totalAccumulatedChi;
    }

    (uint256 totalVestedChi, , , , , ) = chiVesting.vestingData(account);
    totalChi += totalVestedChi;

    uint256 chiPrice = priceFeedAggregator.peek(address(chi));

    return Math.mulDiv(totalChi, chiPrice, 1e18);
  }

  function rewards(
    address chi,
    address usc,
    ChiStaking chiStaking,
    ChiLocking chiLocking,
    USCStaking uscStaking,
    LPStaking uscEthLPStaking,
    LPStaking chiEthLPStaking,
    ChiVesting chiVesting,
    RewardControllerV2 rewardController,
    IPriceFeedAggregator priceFeedAggregator,
    ReserveHolder reserveHolder
  ) external view returns (Rewards memory) {
    uint256 chiIncentivesForUscStaking = rewardController.chiIncentivesForUscStaking();
    uint256 chiIncentivesForChiLocking = rewardController.chiIncentivesForChiLocking();
    uint256 chiIncentivesForUscEthLPStaking = rewardController.chiIncentivesForUscEthLPStaking();
    uint256 chiIncentivesForChiEthLPStaking = rewardController.chiIncentivesForChiEthLPStaking();
    uint256 uscRewards = IERC20(usc).balanceOf(address(rewardController));
    uint256 uscRewardsUsd = Math.mulDiv(uscRewards, 1e8, 1e18);

    uint256 chiPrice = priceFeedAggregator.peek(chi);

    uint256 chiIncentivesForUscStakingUsd = Math.mulDiv(chiIncentivesForUscStaking, chiPrice, 1e18);
    uint256 chiIncentivesForChiLockingUsd = Math.mulDiv(chiIncentivesForChiLocking, chiPrice, 1e18);
    uint256 chiIncentivesForUscEthLPStakingUsd = Math.mulDiv(chiIncentivesForUscEthLPStaking, chiPrice, 1e18);
    uint256 chiIncentivesForChiEthLPStakingUsd = Math.mulDiv(chiIncentivesForChiEthLPStaking, chiPrice, 1e18);

    uint256 stETHEpochrewards = reserveHolder.getCurrentRewards();
    uint256 stETHEcpohrewardsUsd = Math.mulDiv(
      stETHEpochrewards,
      priceFeedAggregator.peek(ExternalContractAddresses.stETH),
      1e18
    );

    uint256 uscStakedChi = uscStaking.getStakedChi();
    uint256 chiStakedChi = chiStaking.getStakedChi();
    uint256 chiLockedChi = chiLocking.getStakedChi();
    uint256 chiVestingChi = chiVesting.getLockedChi();
    uint256 uscEthLPStakingChi = uscEthLPStaking.getStakedChi();
    uint256 chiEthLPStakingChi = chiEthLPStaking.getStakedChi();
    uint256 totalChi = uscStakedChi +
      chiStakedChi +
      chiLockedChi +
      chiVestingChi +
      uscEthLPStakingChi +
      chiEthLPStakingChi;

    uint256 uscStakingStEthReward;
    uint256 chiStakingStEthReward;
    uint256 chiLockingStEthReward;
    uint256 chiVestingStEthReward;
    uint256 uscEthLPStakingStEthReward;
    uint256 chiEthLPStakingStEthReward;
    uint256 chiVestingStEthRewardUsd;
    uint256 chiLockingStEthRewardUsd;
    uint256 chiStakingStEthRewardUsd;
    uint256 uscStakingStEthRewardUsd;
    uint256 uscEthLPStakingStEthRewardUsd;
    uint256 chiEthLPStakingStEthRewardUsd;
    if (totalChi != 0) {
      uint256 stEthPrice = priceFeedAggregator.peek(ExternalContractAddresses.stETH);

      uscStakingStEthReward = Math.mulDiv(uscStakedChi, stETHEpochrewards, totalChi);
      chiStakingStEthReward = Math.mulDiv(chiStakedChi, stETHEpochrewards, totalChi);
      chiLockingStEthReward = Math.mulDiv(chiLockedChi, stETHEpochrewards, totalChi);
      chiVestingStEthReward = Math.mulDiv(chiVestingChi, stETHEpochrewards, totalChi);
      uscEthLPStakingStEthReward = Math.mulDiv(uscEthLPStakingChi, stETHEpochrewards, totalChi);
      chiEthLPStakingStEthReward = Math.mulDiv(chiEthLPStakingStEthReward, stETHEpochrewards, totalChi);

      uscStakingStEthRewardUsd = Math.mulDiv(uscStakingStEthReward, stEthPrice, 1e18);
      chiStakingStEthRewardUsd = Math.mulDiv(chiStakingStEthReward, stEthPrice, 1e18);
      chiLockingStEthRewardUsd = Math.mulDiv(chiLockingStEthReward, stEthPrice, 1e18);
      chiVestingStEthRewardUsd = Math.mulDiv(chiVestingStEthReward, stEthPrice, 1e18);
      uscEthLPStakingStEthRewardUsd = Math.mulDiv(uscEthLPStakingStEthReward, stEthPrice, 1e18);
      chiEthLPStakingStEthRewardUsd = Math.mulDiv(chiEthLPStakingStEthReward, stEthPrice, 1e18);
    }

    uint256 totalStEthReward = uscStakingStEthReward +
      chiStakingStEthReward +
      chiLockingStEthReward +
      chiVestingStEthReward +
      uscEthLPStakingStEthReward +
      chiEthLPStakingStEthReward;

    uint totalStEthRewardUsd = uscStakingStEthRewardUsd +
      chiStakingStEthRewardUsd +
      chiLockingStEthRewardUsd +
      chiVestingStEthRewardUsd +
      uscEthLPStakingStEthRewardUsd +
      chiEthLPStakingStEthRewardUsd;

    uint256 totalChiReward = chiIncentivesForUscStaking +
      chiIncentivesForChiLocking +
      chiIncentivesForUscEthLPStaking +
      chiIncentivesForChiEthLPStaking;

    uint256 totalChiRewardUsd = chiIncentivesForUscStakingUsd +
      chiIncentivesForChiLockingUsd +
      chiIncentivesForUscEthLPStakingUsd +
      chiIncentivesForChiEthLPStakingUsd;

    return (
      Rewards({
        stUscRewards: Reward({
          stEthReward: StEthReward({tokenValue: uscStakingStEthReward, usdValue: uscStakingStEthRewardUsd}),
          chiReward: ChiReward({tokenValue: chiIncentivesForUscStaking, usdValue: chiIncentivesForUscStakingUsd}),
          uscReward: UscReward({tokenValue: uscRewards, usdValue: uscRewardsUsd}),
          totalReward: uscStakingStEthRewardUsd + chiIncentivesForUscStakingUsd + uscRewardsUsd
        }),
        stChiRewards: Reward({
          stEthReward: StEthReward({tokenValue: stETHEpochrewards, usdValue: stETHEcpohrewardsUsd}),
          chiReward: ChiReward({tokenValue: 0, usdValue: 0}),
          uscReward: UscReward({tokenValue: 0, usdValue: 0}),
          totalReward: stETHEcpohrewardsUsd
        }),
        veChiRewards: Reward({
          stEthReward: StEthReward({
            tokenValue: chiVestingStEthReward + chiLockingStEthReward,
            usdValue: chiVestingStEthRewardUsd + chiLockingStEthRewardUsd
          }),
          chiReward: ChiReward({tokenValue: chiIncentivesForChiLocking, usdValue: chiIncentivesForChiLockingUsd}),
          uscReward: UscReward({tokenValue: 0, usdValue: 0}),
          totalReward: chiVestingStEthRewardUsd + chiLockingStEthRewardUsd + chiIncentivesForChiLockingUsd
        }),
        uscEthLpRewards: Reward({
          stEthReward: StEthReward({tokenValue: uscEthLPStakingStEthReward, usdValue: uscEthLPStakingStEthRewardUsd}),
          chiReward: ChiReward({
            tokenValue: chiIncentivesForUscEthLPStaking,
            usdValue: chiIncentivesForUscEthLPStakingUsd
          }),
          uscReward: UscReward({tokenValue: 0, usdValue: 0}),
          totalReward: uscEthLPStakingStEthRewardUsd + chiIncentivesForUscEthLPStakingUsd
        }),
        chiEthLpRewards: Reward({
          stEthReward: StEthReward({tokenValue: chiEthLPStakingStEthReward, usdValue: chiEthLPStakingStEthRewardUsd}),
          chiReward: ChiReward({
            tokenValue: chiIncentivesForChiEthLPStaking,
            usdValue: chiIncentivesForChiEthLPStakingUsd
          }),
          uscReward: UscReward({tokenValue: 0, usdValue: 0}),
          totalReward: chiEthLPStakingStEthRewardUsd + chiIncentivesForChiEthLPStakingUsd
        }),
        totalStEthReward: totalStEthReward,
        totalStEthRewardUsd: totalStEthRewardUsd,
        totalChiReward: totalChiReward,
        totalChiRewardUsd: totalChiRewardUsd
      })
    );
  }
}

contracts/staking/ChiLocking.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "../interfaces/IChiLocking.sol";
import "../library/ExternalContractAddresses.sol";

/// @title Contract for locking CHI tokens
/// @notice This contract holds CHI tokens that are locked
/// @notice Locking of reward distribution of CHI tokens is done per epoch
contract ChiLocking is IChiLocking, OwnableUpgradeable {
  using SafeERC20 for IERC20;

  uint256 public constant MAX_LOCK_DURATION = 208; // 4 years in weeks
  IERC20 public constant stETH = IERC20(ExternalContractAddresses.stETH);

  IERC20 public chi;
  address public rewardController;
  uint256 public currentEpoch;
  uint256 public totalLockedChi;
  uint256 public totalUnlockedChi;
  uint256 public totalLockedShares;
  uint256 public totalVotingPower;
  uint256 public sumOfLockedDurations;
  uint256 public numberOfLockedPositions;
  uint256 public addVotingPowerInEpoch;
  uint256 public sumShareDurationProduct;
  uint256 public addedAmountInEpoch;

  mapping(address account => bool status) public chiLockers;
  mapping(address account => LockingData) public locks;
  mapping(uint256 id => EpochData) public epochs;

  modifier onlyRewardController() {
    if (msg.sender != rewardController) {
      revert NotRewardController();
    }
    _;
  }

  modifier onlyChiLockers() {
    if (!chiLockers[msg.sender]) {
      revert NotChiLocker();
    }
    _;
  }

  function initialize(IERC20 _chi, address _chiStaking) external initializer {
    __Ownable_init();
    chiLockers[_chiStaking] = true;
    chi = _chi;
    currentEpoch = 1;
  }

  /// @inheritdoc IChiLocking
  function setUscStaking(address _uscStaking) external onlyOwner {
    chiLockers[_uscStaking] = true;
    emit SetUscStaking(_uscStaking);
  }

  /// @inheritdoc IChiLocking
  function setRewardController(address _rewardController) external onlyOwner {
    rewardController = _rewardController;
    emit SetRewardController(_rewardController);
  }

  /// @inheritdoc IChiLocking
  function setChiLocker(address contractAddress, bool toSet) external onlyOwner {
    chiLockers[contractAddress] = toSet;
    emit SetChiLocker(contractAddress, toSet);
  }

  /// @inheritdoc IChiLocking
  function getLockedPosition(address account, uint256 pos) external view returns (LockedPosition memory) {
    return locks[account].positions[pos];
  }

  function getAllLockedPositions(address account) external view returns (AllLockedPositionsOutput[] memory out) {
    LockingData storage lockData = locks[account];

    out = new AllLockedPositionsOutput[](lockData.positions.length);

    for (uint256 i = 0; i < lockData.positions.length; i++) {
      LockedPosition storage position = lockData.positions[i];
      out[i].position = position;
      out[i].votingPower = _getCurrentVotingPowerForPosition(position);
      out[i].stETHreward = _getUnclaimedStETHPositionAmount(lockData.positions[i], lockData.lastUpdatedEpoch);
      out[i].totalAccumulatedChi = _totalAccumulatedAtEpoch(currentEpoch, lockData.positions[i]);
      out[i].totalChiRewards = (out[i].totalAccumulatedChi > position.amount)
        ? out[i].totalAccumulatedChi - position.amount
        : 0;
    }
  }

  /// @inheritdoc IChiLocking
  function getStakedChi() public view returns (uint256) {
    return totalLockedChi + totalUnlockedChi;
  }

  /// @inheritdoc IChiLocking
  function getLockedChi() public view returns (uint256) {
    return totalLockedChi;
  }

  /// @inheritdoc IChiLocking
  function getTotalVotingPower() external view returns (uint256) {
    return totalVotingPower;
  }

  /// @inheritdoc IChiLocking
  function availableChiWithdraw(address account) public view returns (uint256 availableTotal) {
    LockingData storage lockData = locks[account];
    for (uint256 i = 0; i < lockData.positions.length; i++) {
      availableTotal += _availableToWithdrawFromPosition(lockData.positions[i]);
    }
  }

  /// @inheritdoc IChiLocking
  function lockChi(address account, uint256 amount, uint256 duration) external onlyChiLockers {
    if (amount == 0) {
      revert ZeroAmount();
    }

    uint256 shares = _getNumberOfShares(amount);
    duration++;

    EpochData storage currentEpochData = epochs[currentEpoch];
    EpochData storage afterEndEpoch = epochs[currentEpoch + duration];

    locks[account].positions.push(
      LockedPosition({
        amount: amount,
        startEpoch: currentEpoch,
        duration: duration,
        shares: shares,
        withdrawnChiAmount: 0
      })
    );

    totalLockedChi += amount;
    totalLockedShares += shares;
    currentEpochData.lockedSharesInEpoch += shares;
    currentEpochData.totalLockedChiInEpoch += amount;
    afterEndEpoch.sharesToUnlock += shares;

    totalVotingPower += Math.mulDiv(amount, duration, MAX_LOCK_DURATION);
    sumShareDurationProduct += Math.mulDiv(shares, duration, MAX_LOCK_DURATION);
    sumOfLockedDurations += duration + 1;
    numberOfLockedPositions += 1;
    afterEndEpoch.numberOfEndingPositions += 1;

    emit LockChi(account, amount, shares, currentEpoch, currentEpoch + duration);
  }

  /// @inheritdoc IChiLocking
  function updateEpoch(uint256 chiEmissions, uint256 stETHrewards) external onlyRewardController {
    EpochData storage epoch = epochs[currentEpoch];

    uint256 stETHrewardsForLocked;
    uint256 stakedChi = getStakedChi();
    if (stakedChi != 0) {
      stETHrewardsForLocked = Math.mulDiv(stETHrewards, totalLockedChi, stakedChi);
    }
    uint256 stETHrewardsForUnlocked = stETHrewards - stETHrewardsForLocked;

    uint256 stEthPerLockedShare;
    if (epoch.lockedSharesInEpoch != 0) {
      stEthPerLockedShare = Math.mulDiv(stETHrewardsForLocked, 1e18, epoch.lockedSharesInEpoch);
    }
    epoch.cumulativeStETHPerLockedShare = epochs[currentEpoch - 1].cumulativeStETHPerLockedShare + stEthPerLockedShare;

    uint256 stEthPerUnlocked;
    if (totalUnlockedChi != 0) {
      stEthPerUnlocked = Math.mulDiv(stETHrewardsForUnlocked, 1e18, totalUnlockedChi);
    }

    epoch.cumulativeStETHPerUnlocked = epochs[currentEpoch - 1].cumulativeStETHPerUnlocked + stEthPerUnlocked;

    totalVotingPower -= totalLockedChi / MAX_LOCK_DURATION;
    sumShareDurationProduct -= totalLockedShares / MAX_LOCK_DURATION;

    if (totalLockedShares != 0) {
      totalVotingPower += Math.mulDiv(chiEmissions, sumShareDurationProduct, totalLockedShares);
    }

    totalLockedChi += chiEmissions;
    epoch.totalLockedChiInEpoch += chiEmissions;

    EpochData storage nextEpoch = epochs[currentEpoch + 1];

    uint256 amountToUnlock;
    if (totalLockedShares != 0) {
      amountToUnlock = Math.mulDiv(epoch.totalLockedChiInEpoch, nextEpoch.sharesToUnlock, epoch.lockedSharesInEpoch);
    }

    totalLockedChi = totalLockedChi - amountToUnlock;
    totalUnlockedChi = totalUnlockedChi + amountToUnlock;
    totalLockedShares -= nextEpoch.sharesToUnlock;

    nextEpoch.lockedSharesInEpoch = totalLockedShares;
    nextEpoch.totalLockedChiInEpoch = totalLockedChi;

    currentEpoch++;
    emit UpdateEpoch(currentEpoch - 1, totalLockedChi, chiEmissions, stETHrewards, stEthPerLockedShare);
  }

  /// @inheritdoc IChiLocking
  function claimStETH(address account) external onlyRewardController returns (uint256 amount) {
    _updateUnclaimedStETH(account);
    amount = locks[account].unclaimedStETH;
    locks[account].unclaimedStETH = 0;

    emit ClaimStETH(account, amount);
  }

  /// @inheritdoc IChiLocking
  function withdrawChiFromAccount(address account, uint256 amount) public onlyChiLockers {
    withdrawChiFromAccountToAddress(account, account, amount);
  }

  /// @inheritdoc IChiLocking
  function withdrawChiFromAccountToAddress(address account, address toAddress, uint256 amount) public onlyChiLockers {
    if (amount == 0) {
      return;
    }

    _updateUnclaimedStETH(account);

    uint256 toWithdraw = amount;

    LockingData storage lockData = locks[account];

    uint256 pos = 0;
    while (toWithdraw > 0) {
      if (pos >= lockData.positions.length) {
        revert UnavailableWithdrawAmount(amount);
      }

      LockedPosition storage position = lockData.positions[pos];

      if (currentEpoch < position.startEpoch + position.duration) {
        pos++;
      } else {
        uint256 availableToWithdraw = _availableToWithdrawFromPosition(position);

        if (availableToWithdraw > toWithdraw) {
          position.withdrawnChiAmount += toWithdraw;
          toWithdraw = 0;
        } else {
          position.withdrawnChiAmount += toWithdraw;
          toWithdraw -= availableToWithdraw;
          _removePosition(lockData, pos);
        }
      }
    }

    totalUnlockedChi -= amount;
    chi.safeTransfer(toAddress, amount);

    emit WithdrawChiFromAccount(account, toAddress, amount);
  }

  /// @inheritdoc IChiLocking
  function unclaimedStETHAmount(address account) public view returns (uint256 totalAmount) {
    LockingData storage lockData = locks[account];
    totalAmount = lockData.unclaimedStETH;
    if (lockData.lastUpdatedEpoch == currentEpoch) return totalAmount;

    for (uint256 i = 0; i < lockData.positions.length; i++) {
      totalAmount += _getUnclaimedStETHPositionAmount(lockData.positions[i], lockData.lastUpdatedEpoch);
    }
  }

  /// @inheritdoc IChiLocking
  function getVotingPower(address account) public view returns (uint256) {
    uint256 votingPower = 0;
    LockingData storage lockData = locks[account];
    for (uint256 i = 0; i < lockData.positions.length; i++) {
      votingPower += _getCurrentVotingPowerForPosition(lockData.positions[i]);
    }
    return votingPower;
  }

  function _getNumberOfShares(uint256 chiAmount) internal view returns (uint256) {
    if (totalLockedChi == 0) return chiAmount;
    return Math.mulDiv(chiAmount, totalLockedShares, totalLockedChi);
  }

  function _updateUnclaimedStETH(address account) internal {
    locks[account].unclaimedStETH = unclaimedStETHAmount(account);
    locks[account].lastUpdatedEpoch = currentEpoch;
  }

  function _getUnclaimedStETHPositionAmount(
    LockedPosition storage position,
    uint256 lastUpdated
  ) internal view returns (uint256 unclaimedAmount) {
    if (lastUpdated == currentEpoch) return 0;

    uint256 fromEpoch = lastUpdated < position.startEpoch ? position.startEpoch : lastUpdated;
    uint256 toEpoch = currentEpoch - 1;

    uint256 lockEndsInEpoch = position.startEpoch + position.duration - 1;
    if (fromEpoch <= lockEndsInEpoch) {
      if (toEpoch <= lockEndsInEpoch) {
        unclaimedAmount += _unclaiemdStETHDuringLocked(position, fromEpoch, toEpoch);
        return unclaimedAmount;
      } else {
        unclaimedAmount += _unclaiemdStETHDuringLocked(position, fromEpoch, lockEndsInEpoch);
      }

      fromEpoch = lockEndsInEpoch + 1;
    }

    unclaimedAmount += _unclaiemdStETHAfterLocked(position, fromEpoch, toEpoch);
  }

  function _unclaiemdStETHDuringLocked(
    LockedPosition storage position,
    uint256 fromEpoch,
    uint256 toEpoch
  ) internal view returns (uint256) {
    uint256 rewardPerShare = epochs[toEpoch].cumulativeStETHPerLockedShare -
      epochs[fromEpoch - 1].cumulativeStETHPerLockedShare;

    return Math.mulDiv(rewardPerShare, position.shares, 1e18);
  }

  function _unclaiemdStETHAfterLocked(
    LockedPosition storage position,
    uint256 fromEpoch,
    uint256 toEpoch
  ) internal view returns (uint256) {
    uint256 unlockedChiAmount = _availableToWithdrawFromPosition(position);
    uint256 rewardPerChi = epochs[toEpoch].cumulativeStETHPerUnlocked -
      epochs[fromEpoch - 1].cumulativeStETHPerUnlocked;
    return Math.mulDiv(rewardPerChi, unlockedChiAmount, 1e18);
  }

  function _getCurrentVotingPowerForPosition(LockedPosition storage position) internal view returns (uint256) {
    if (currentEpoch >= position.startEpoch + position.duration || currentEpoch < position.startEpoch) return 0;
    uint256 epochsUntilEnd = position.startEpoch + position.duration - currentEpoch;

    if (currentEpoch == position.startEpoch) {
      return Math.mulDiv(position.amount, epochsUntilEnd, MAX_LOCK_DURATION);
    } else {
      return Math.mulDiv(_totalAccumulatedAtEpoch(currentEpoch - 1, position), epochsUntilEnd, MAX_LOCK_DURATION);
    }
  }

  function _availableToWithdrawFromPosition(LockedPosition storage position) internal view returns (uint256) {
    uint256 endLockingEpoch = position.startEpoch + position.duration - 1;
    if (currentEpoch <= endLockingEpoch) return 0;
    return _totalAccumulatedAtEpoch(endLockingEpoch, position) - position.withdrawnChiAmount;
  }

  function _totalAccumulatedAtEpoch(uint256 epochNum, LockedPosition storage position) internal view returns (uint256) {
    uint256 endEpoch = position.startEpoch + position.duration - 1;
    if (endEpoch < epochNum) epochNum = endEpoch;

    EpochData storage epoch = epochs[epochNum];
    return Math.mulDiv(position.shares, epoch.totalLockedChiInEpoch, epoch.lockedSharesInEpoch);
  }

  function _removePosition(LockingData storage lockData, uint256 pos) internal {
    lockData.positions[pos] = lockData.positions[lockData.positions.length - 1];
    lockData.positions.pop();
  }
}

contracts/staking/ChiStaking.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../interfaces/IChiStaking.sol";
import "../interfaces/IChiLocking.sol";
import "./StakingWithEpochs.sol";

/// @title Contract for staking chi tokens
/// @notice This contract holds staked CHI tokens, staking is done per epoch
/// @dev This contract is upgradeable
contract ChiStaking is IChiStaking, OwnableUpgradeable, StakingWithEpochs {
  using SafeERC20 for IERC20;

  uint256 public constant MIN_LOCK_DURATION = 4; // 4 epochs = 4 weeks = 1 month
  uint256 public constant MAX_LOCK_DURATION = 208; // 208 epochs = 208 weeks = 4 years

  IChiLocking public chiLocking;

  function initialize(IERC20 _chiAddress) external initializer {
    __Ownable_init();
    __StakingWithEpochs_init("Staked CHI", "stCHI", _chiAddress);
  }

  /// @inheritdoc IChiStaking
  function setChiLocking(IChiLocking _chiLocking) external onlyOwner {
    chiLocking = _chiLocking;
    emit SetChiLocking(address(_chiLocking));
  }

  /// @inheritdoc IStaking
  function setRewardController(address _rewardController) external onlyOwner {
    _setRewardController(_rewardController);
    emit SetRewardController(_rewardController);
  }

  /// @inheritdoc IStaking
  function getStakedChi() external view returns (uint256) {
    return epochs[currentEpoch].shares;
  }

  /// @inheritdoc IChiStaking
  function updateEpoch(uint256 stETHrewards) external onlyRewardController {
    _updateCumulativeRewardsForToken(epochs[currentEpoch], epochs[currentEpoch - 1], RewardToken.STETH, stETHrewards);
    _updateEpoch();
  }

  /// @inheritdoc IStakingWithEpochs
  function unstake(uint256 amount) public override(IStakingWithEpochs, StakingWithEpochs) {
    unstake(amount, msg.sender);
  }

  /// @inheritdoc IStakingWithEpochs
  function unstake(uint256 amount, address toAddress) public override(IStakingWithEpochs, StakingWithEpochs) {
    uint256 availableOnLocking = chiLocking.availableChiWithdraw(msg.sender);
    if (amount <= availableOnLocking) {
      chiLocking.withdrawChiFromAccountToAddress(msg.sender, toAddress, amount);
    } else {
      chiLocking.withdrawChiFromAccountToAddress(msg.sender, toAddress, availableOnLocking);
      StakingWithEpochs.unstake(amount - availableOnLocking, toAddress);
    }
  }

  /// @inheritdoc IChiStaking
  function lock(uint256 amount, uint256 duration, bool useStakedTokens) external {
    if (duration < MIN_LOCK_DURATION || duration > MAX_LOCK_DURATION) {
      revert InvalidDuration(duration);
    }

    if (!useStakedTokens) {
      stakeToken.safeTransferFrom(msg.sender, address(chiLocking), amount);
      chiLocking.lockChi(msg.sender, amount, duration);
    } else {
      unstake(amount, address(chiLocking));
      chiLocking.lockChi(msg.sender, amount, duration + 1);
    }

    emit Lock(msg.sender, amount, duration, useStakedTokens);
  }

  /// @inheritdoc IStaking
  function claimStETH(address account) external onlyRewardController returns (uint256) {
    uint256 amount = _claimAndUpdateReward(account, RewardToken.STETH);
    emit ClaimStETH(account, amount);
    return amount;
  }

  /// @inheritdoc IStaking
  function unclaimedStETHAmount(address account) public view returns (uint256) {
    return _getCurrentReward(account, RewardToken.STETH);
  }

  function _calculatingRewards(RewardToken token) internal pure override returns (bool) {
    if (token == RewardToken.STETH) return true;
    return false;
  }
}

contracts/staking/ChiVesting.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "../interfaces/IChiVesting.sol";

/// @title Contract for vesting chi tokens
/// @notice This contract holds chi tokens that are vested
/// @notice This contract hold vested chi tokens, vesting is done on epochs
/// @dev This contract is upgradeable
contract ChiVesting is IChiVesting, OwnableUpgradeable {
  using SafeERC20 for IERC20;

  uint256 public constant MAX_LOCK_DURATION = 208;
  IERC20 public chi;

  uint256 public cliffDuration;
  uint256 public vestingDuration;
  uint256 public totalLockedChi;
  uint256 public totalUnlockedChi;
  uint256 public totalShares;
  uint256 public currentEpoch;
  uint256 public totalVotingPower;
  address public rewardController;

  mapping(address account => bool status) public chiVesters;
  mapping(address account => VestingData) public vestingData;
  mapping(uint256 id => EpochData) public epochs;

  modifier onlyRewardController() {
    if (msg.sender != rewardController) {
      revert NotRewardController();
    }
    _;
  }

  modifier onlyChiVesters() {
    if (!chiVesters[msg.sender]) {
      revert NotChiVester();
    }
    _;
  }

  function initialize(IERC20 _chi, uint256 _cliffDuration, uint256 _vestingDuration) external initializer {
    __Ownable_init();

    chi = _chi;
    cliffDuration = _cliffDuration;
    vestingDuration = _vestingDuration;
    currentEpoch = 1;
  }

  /// @inheritdoc IChiVesting
  function setRewardController(address _rewardController) external onlyOwner {
    rewardController = _rewardController;
    emit SetRewardController(_rewardController);
  }

  /// @inheritdoc IChiVesting
  function setChiVester(address contractAddress, bool toSet) external onlyOwner {
    chiVesters[contractAddress] = toSet;
    emit SetChiVester(contractAddress, toSet);
  }

  /// @inheritdoc IChiVesting
  function getLockedChi() public view returns (uint256) {
    return totalLockedChi;
  }

  /// @inheritdoc IChiVesting
  function addVesting(address account, uint256 chiAmount) external onlyChiVesters {
    if (currentEpoch > cliffDuration) {
      revert CliffPassed();
    }

    _updateUnclaimedStETH(account);

    uint256 shares = _getNumberOfShares(chiAmount);
    VestingData storage vesting = vestingData[account];
    vesting.shares += shares;
    vesting.startAmount += chiAmount;

    totalLockedChi += chiAmount;
    totalShares += shares;

    totalVotingPower += Math.mulDiv(chiAmount, _epochsUntilEnd(), MAX_LOCK_DURATION);

    emit AddVesting(account, chiAmount, shares);
  }

  /// @inheritdoc IChiVesting
  function updateEpoch(uint256 chiEmissions, uint256 stETHrewards) external onlyRewardController {
    EpochData storage epoch = epochs[currentEpoch];

    uint256 stETHRewardPerShare;
    if (totalShares != 0) {
      stETHRewardPerShare = Math.mulDiv(stETHrewards, 1e18, totalShares);
    }
    epoch.cumulativeStETHRewardPerShare = epochs[currentEpoch - 1].cumulativeStETHRewardPerShare + stETHRewardPerShare;

    uint256 epochsUntilEnd = _epochsUntilEnd();

    totalLockedChi += chiEmissions;

    if (epochsUntilEnd > 0) {
      totalVotingPower += Math.mulDiv(chiEmissions, _epochsUntilEnd(), MAX_LOCK_DURATION);
    }

    uint256 amountToUnlock;
    if (totalLockedChi > 0 && currentEpoch > cliffDuration && epochsUntilEnd > 0) {
      amountToUnlock = totalLockedChi / _epochsUntilEnd();
    }

    uint256 amountUnlockedPerShare;
    if (totalShares > 0) {
      amountUnlockedPerShare = Math.mulDiv(amountToUnlock, 1e18, totalShares);
    }
    epoch.cumulativeUnlockedPerShare = epochs[currentEpoch - 1].cumulativeUnlockedPerShare + amountUnlockedPerShare;

    totalLockedChi -= amountToUnlock;
    totalUnlockedChi += amountToUnlock;

    if (epochsUntilEnd > 0) {
      // decrease for unlocked tokens
      uint256 decreaseVotingPower = Math.mulDiv(amountToUnlock, epochsUntilEnd, MAX_LOCK_DURATION);
      if (decreaseVotingPower > totalVotingPower) {
        totalVotingPower = 0;
      } else {
        totalVotingPower -= decreaseVotingPower;
      }

      // regular decrease in voting power because of less time until end of locking
      totalVotingPower = Math.mulDiv(totalVotingPower, epochsUntilEnd - 1, epochsUntilEnd);
    }

    currentEpoch++;
    emit UpdateEpoch(currentEpoch - 1, stETHrewards, totalLockedChi);
  }

  /// @inheritdoc IChiVesting
  function withdrawChi(uint256 amount) external {
    VestingData storage vesting = vestingData[msg.sender];

    _updateAvailabeWithdraw(msg.sender);
    if (amount > vesting.unlockedChi) {
      revert UnavailableWithdrawAmount(amount);
    }

    vesting.unlockedChi -= amount;
    totalUnlockedChi -= amount;

    chi.safeTransfer(msg.sender, amount);

    emit WithdrawChi(msg.sender, amount);
  }

  /// @inheritdoc IChiVesting
  function claimStETH(address account) external onlyRewardController returns (uint256) {
    _updateUnclaimedStETH(account);
    uint256 amount = vestingData[account].unclaimedStETH;
    vestingData[account].unclaimedStETH = 0;

    emit ClaimStETH(account, amount);
    return amount;
  }

  /// @inheritdoc IChiVesting
  function unclaimedStETHAmount(address account) public view returns (uint256) {
    VestingData storage vesting = vestingData[account];
    uint256 totalAmount = vesting.unclaimedStETH;

    uint256 rewardPerShare = epochs[currentEpoch - 1].cumulativeStETHRewardPerShare -
      epochs[vesting.lastClaimedEpoch].cumulativeStETHRewardPerShare;
    totalAmount += Math.mulDiv(rewardPerShare, vesting.shares, 1e18);

    return totalAmount;
  }

  /// @inheritdoc IChiVesting
  function getVotingPower(address account) external view returns (uint256) {
    if (currentEpoch > cliffDuration + vestingDuration) return 0;
    VestingData storage vesting = vestingData[account];
    return vesting.shares != 0 ? Math.mulDiv(totalVotingPower, vesting.shares, totalShares) : 0;
  }

  /// @inheritdoc IChiVesting
  function getTotalVotingPower() external view returns (uint256) {
    return totalVotingPower;
  }

  /// @inheritdoc IChiVesting
  function availableChiWithdraw(address account) public view returns (uint256) {
    VestingData storage vesting = vestingData[account];
    return vesting.unlockedChi + _availableUnlockFromTo(vesting.lastWithdrawnEpoch, currentEpoch - 1, vesting.shares);
  }

  // includes available amount in `toEpoch`
  function _availableUnlockFromTo(uint256 fromEpoch, uint256 toEpoch, uint256 shares) internal view returns (uint256) {
    uint256 availableWithdrawPerShare = epochs[toEpoch].cumulativeUnlockedPerShare -
      epochs[fromEpoch].cumulativeUnlockedPerShare;
    return Math.mulDiv(availableWithdrawPerShare, shares, 1e18);
  }

  function _getNumberOfShares(uint256 chiAmount) internal view returns (uint256) {
    if (totalLockedChi == 0) return chiAmount;
    return Math.mulDiv(chiAmount, totalShares, totalLockedChi);
  }

  function _updateAvailabeWithdraw(address account) internal {
    vestingData[account].unlockedChi = availableChiWithdraw(account);
    vestingData[account].lastWithdrawnEpoch = currentEpoch - 1;
  }

  function _updateUnclaimedStETH(address account) internal {
    vestingData[account].unclaimedStETH = unclaimedStETHAmount(account);
    vestingData[account].lastClaimedEpoch = currentEpoch - 1;
  }

  function _epochsUntilEnd() internal view returns (uint256) {
    if (currentEpoch > cliffDuration + vestingDuration + 1) return 0;
    return cliffDuration + vestingDuration + 1 - currentEpoch;
  }
}

contracts/staking/LPStaking.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../interfaces/ILPStaking.sol";
import "../interfaces/IChiLocking.sol";
import "./StakingWithEpochs.sol";

/// @title Contract for staking USC/ETH and CHI/ETH LP tokens
/// @notice Staking is done in epochs
/// @dev Contract is upgradeable
contract LPStaking is ILPStaking, OwnableUpgradeable, StakingWithEpochs {
  using SafeERC20 for IERC20;

  uint256 public constant MIN_LOCK_DURATION = 4;
  uint256 public constant MAX_LOCK_DURATION = 208;

  IERC20 public chi;
  IChiLocking public chiLockingContract;

  uint256 public chiAmountFromEmissions;

  function initialize(
    IERC20 _chi,
    IChiLocking _chiLockingContract,
    IERC20 _token,
    string memory _name,
    string memory _symbol
  ) external initializer {
    __Ownable_init();
    __StakingWithEpochs_init(_name, _symbol, _token);

    chi = _chi;
    chiLockingContract = _chiLockingContract;
  }

  /// @notice Sets reward controller contract address
  /// @param _rewardController Reward controller contract address
  function setRewardController(address _rewardController) external onlyOwner {
    _setRewardController(_rewardController);
  }

  /// @notice Updates epoch data
  /// @param chiEmissions Amount of CHI token incentives emitted in current epoch for USC stakers
  /// @custom:usage This function should be called from rewardController contract in purpose of updating epoch data
  function updateEpoch(uint256 chiEmissions, uint256 stETHrewards) external onlyRewardController {
    EpochData storage epoch = epochs[currentEpoch];
    EpochData storage prevEpoch = epochs[currentEpoch - 1];

    _updateCumulativeRewardsForToken(epoch, prevEpoch, RewardToken.CHI, chiEmissions);
    _updateCumulativeRewardsForToken(epoch, prevEpoch, RewardToken.STETH, stETHrewards);
    _updateEpoch();

    chiAmountFromEmissions += chiEmissions;

    emit UpdateEpoch(currentEpoch - 1, chiEmissions);
  }

  /// @inheritdoc IStaking
  function claimStETH(address account) external onlyRewardController returns (uint256) {
    uint256 amount = _claimAndUpdateReward(account, RewardToken.STETH);
    emit ClaimStETH(account, amount);
    return amount;
  }

  /// @inheritdoc IStaking
  function getStakedChi() external view returns (uint256) {
    return chiAmountFromEmissions;
  }

  /// @inheritdoc IStaking
  function unclaimedStETHAmount(address account) public view returns (uint256) {
    return _getCurrentReward(account, RewardToken.STETH);
  }

  /// @notice Locks CHI tokens that user earned from incentives for given duration
  /// @param duration Locking duration in epochs
  function lockChi(uint256 duration) external {
    if (duration < MIN_LOCK_DURATION || duration > MAX_LOCK_DURATION) {
      revert InvalidDuration(duration);
    }

    uint256 amount = _claimAndUpdateReward(msg.sender, RewardToken.CHI);
    chiLockingContract.lockChi(msg.sender, amount, duration);

    chiAmountFromEmissions -= amount;

    chi.safeTransfer(address(chiLockingContract), amount);

    emit LockChi(msg.sender, amount, duration);
  }

  function _calculatingRewards(RewardToken token) internal pure override returns (bool) {
    if (token == RewardToken.CHI) return true;
    if (token == RewardToken.STETH) return true;
    return false;
  }
}

contracts/staking/RewardControllerV2.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "../interfaces/IRewardController.sol";
import "../interfaces/IMintableERC20.sol";
import "../interfaces/IBurnableERC20.sol";
import "../interfaces/IArbitrage.sol";
import "../interfaces/IReserveHolder.sol";
import "../interfaces/IStaking.sol";
import "../interfaces/IUSCStaking.sol";
import "../interfaces/IChiStaking.sol";
import "../interfaces/IChiLocking.sol";
import "../interfaces/IChiVesting.sol";
import "../interfaces/ILPStaking.sol";

/// @title Contract for managing rewards
/// @notice This contract manages rewards for chi lockers, chi stakers, chi vesters and usc stakers
/// @notice This contract holds chi incentives for all contracts and distributes then at the end of epoch
/// @dev This contract is upgradeable
contract RewardControllerV2 is IRewardController, OwnableUpgradeable {
  using SafeERC20 for IERC20;

  uint256 public constant EPOCH_DURATION = 1 weeks;

  IERC20 public chi;
  IERC20 public usc;
  IReserveHolder public reserveHolder;
  IArbitrage public arbitrager;
  IUSCStaking public uscStaking;
  IChiStaking public chiStaking;
  IChiLocking public chiLocking;
  IChiVesting public chiVesting;
  ILPStaking public uscEthLPStaking;
  ILPStaking public chiEthLPStaking;

  uint256 public currentEpoch;
  uint256 public firstEpochTimestamp;
  uint256 public chiIncentivesForChiLocking;
  uint256 public chiIncentivesForUscStaking;
  uint256 public chiIncentivesForUscEthLPStaking;
  uint256 public chiIncentivesForChiEthLPStaking;

  mapping(uint256 id => EpochData) public epochs;

  // Upgrade
  uint256 public constant MAX_PERCENTAGE = 100_00;
  uint256 public uscStakingProtocolFee; // Protocol fee from USC staking rewards, maximum 100_00 = 100%

  // Upgrade
  mapping(address => bool) public isArbitrager;

  modifier onlyArbitrager() {
    if (!isArbitrager[msg.sender] && address(arbitrager) != msg.sender) {
      revert NotArbitrager();
    }
    _;
  }

  function initialize(
    IERC20 _chi,
    IERC20 _usc,
    IReserveHolder _reserveHolder,
    IUSCStaking _uscStaking,
    IChiStaking _chiStaking,
    IChiLocking _chiLocking,
    IChiVesting _chiVesting,
    ILPStaking _uscEthLPStaking,
    ILPStaking _chiEthLPStaking,
    uint256 _firstEpochTimestamp
  ) external initializer {
    __Ownable_init();
    chi = _chi;
    usc = _usc;
    reserveHolder = _reserveHolder;
    uscStaking = _uscStaking;
    chiStaking = _chiStaking;
    chiLocking = _chiLocking;
    chiVesting = _chiVesting;
    uscEthLPStaking = _uscEthLPStaking;
    chiEthLPStaking = _chiEthLPStaking;
    firstEpochTimestamp = _firstEpochTimestamp;
    currentEpoch = 1;
  }

  /// @inheritdoc IRewardController
  function setChiIncentivesForChiLocking(uint256 _chiIncentivesForChiLocking) external onlyOwner {
    chiIncentivesForChiLocking = _chiIncentivesForChiLocking;
  }

  /// @inheritdoc IRewardController
  function setChiIncentivesForUscStaking(uint256 _chiIncentivesForUscStaking) external onlyOwner {
    chiIncentivesForUscStaking = _chiIncentivesForUscStaking;
  }

  /// @inheritdoc IRewardController
  function setChiIncentivesForUscEthLPStaking(uint256 _chiIncentivesForUscEthLPStaking) external onlyOwner {
    chiIncentivesForUscEthLPStaking = _chiIncentivesForUscEthLPStaking;
  }

  /// @inheritdoc IRewardController
  function setChiIncentivesForChiEthLPStaking(uint256 _chiIncentivesForChiEthLPStaking) external onlyOwner {
    chiIncentivesForChiEthLPStaking = _chiIncentivesForChiEthLPStaking;
  }

  /// @inheritdoc IRewardController
  function setArbitrager(IArbitrage _arbitrager) external onlyOwner {
    arbitrager = _arbitrager;
    emit SetArbitrager(address(_arbitrager));
  }

  function updateArbitrager(address account, bool status) external onlyOwner {
    isArbitrager[account] = status;
    emit UpdateArbitrager(account, status);
  }

  function setUscStakingProtocolFee(uint256 _uscStakingProtocolFee) external onlyOwner {
    uscStakingProtocolFee = _uscStakingProtocolFee;
  }

  /// @inheritdoc IRewardController
  function rewardUSC(uint256 amount) external onlyArbitrager {
    if (amount == 0) {
      revert ZeroAmount();
    }

    usc.safeTransferFrom(msg.sender, address(this), amount);
    epochs[currentEpoch].totalUscReward += amount;

    emit RewardUSC(msg.sender, amount);
  }

  /// @inheritdoc IRewardController
  function updateEpoch() public {
    if (block.timestamp < firstEpochTimestamp + currentEpoch * EPOCH_DURATION) {
      revert EpochNotFinished();
    }

    uint256 totalUscRewards = epochs[currentEpoch].totalUscReward;
    uint256 uscProtocolFee = Math.mulDiv(totalUscRewards, uscStakingProtocolFee, MAX_PERCENTAGE);
    usc.safeTransfer(owner(), uscProtocolFee);

    epochs[currentEpoch].totalUscReward -= uscProtocolFee;

    StETHRewards memory stEthRewards = _updateAndGetStETHRewards();
    ChiIncentives memory chiIncentives = _updateAndGetChiIncentives();

    _updateEpochsInSubcontracts(stEthRewards, chiIncentives, epochs[currentEpoch].totalUscReward);

    usc.safeTransfer(address(uscStaking), epochs[currentEpoch].totalUscReward);
    chi.safeTransfer(address(uscStaking), chiIncentives.uscStakingChiIncentives);
    chi.safeTransfer(address(chiLocking), chiIncentives.chiLockingChiIncentives);
    chi.safeTransfer(address(chiVesting), chiIncentives.chiVestingChiIncentives);
    chi.safeTransfer(address(uscEthLPStaking), chiIncentivesForUscEthLPStaking);
    chi.safeTransfer(address(chiEthLPStaking), chiIncentivesForChiEthLPStaking);

    currentEpoch++;

    uint256 totalStEthRewards = stEthRewards.uscStakingStEthReward +
      stEthRewards.chiStakingStEthReward +
      stEthRewards.chiLockingStEthReward +
      stEthRewards.chiVestingStEthReward;
    uint256 totalChiIncentives = chiIncentives.uscStakingChiIncentives +
      chiIncentives.chiLockingChiIncentives +
      chiIncentives.chiVestingChiIncentives +
      chiIncentivesForUscEthLPStaking +
      chiIncentivesForChiEthLPStaking;
    emit UpdateEpoch(currentEpoch - 1, totalStEthRewards, totalChiIncentives);
  }

  /// @inheritdoc IRewardController
  function claimStEth() external {
    uint256 totalAmount;
    totalAmount += IStaking(address(uscStaking)).claimStETH(msg.sender);
    totalAmount += IStaking(address(chiStaking)).claimStETH(msg.sender);
    totalAmount += IStaking(address(chiLocking)).claimStETH(msg.sender);
    totalAmount += IStaking(address(chiVesting)).claimStETH(msg.sender);
    totalAmount += IStaking(address(uscEthLPStaking)).claimStETH(msg.sender);
    totalAmount += IStaking(address(chiEthLPStaking)).claimStETH(msg.sender);

    reserveHolder.claimRewards(msg.sender, totalAmount);

    emit ClaimStEth(msg.sender, totalAmount);
  }

  /// @inheritdoc IRewardController
  function unclaimedStETHAmount(address account) external view returns (uint256) {
    uint256 totalAmount;
    totalAmount += IStaking(address(uscStaking)).unclaimedStETHAmount(account);
    totalAmount += IStaking(address(chiStaking)).unclaimedStETHAmount(account);
    totalAmount += IStaking(address(chiLocking)).unclaimedStETHAmount(account);
    totalAmount += IStaking(address(chiVesting)).unclaimedStETHAmount(account);
    totalAmount += IStaking(address(uscEthLPStaking)).unclaimedStETHAmount(account);
    totalAmount += IStaking(address(chiEthLPStaking)).unclaimedStETHAmount(account);

    return totalAmount;
  }

  function _updateAndGetChiIncentives() internal view returns (ChiIncentives memory) {
    uint256 chiLockingLocked = chiLocking.getLockedChi();
    uint256 chiVestingLocked = chiVesting.getLockedChi();
    uint256 totalLockedChi = chiLockingLocked + chiVestingLocked;

    uint256 chiLockingChiIncentives;
    uint256 chiVestingChiIncentives;
    if (totalLockedChi != 0) {
      chiLockingChiIncentives = Math.mulDiv(chiLockingLocked, chiIncentivesForChiLocking, totalLockedChi);
      chiVestingChiIncentives = Math.mulDiv(chiVestingLocked, chiIncentivesForChiLocking, totalLockedChi);
    }

    return
      ChiIncentives({
        uscStakingChiIncentives: chiIncentivesForUscStaking,
        chiLockingChiIncentives: chiLockingChiIncentives,
        chiVestingChiIncentives: chiVestingChiIncentives
      });
  }

  function _updateEpochsInSubcontracts(
    StETHRewards memory stEthRewards,
    ChiIncentives memory chiIncentives,
    uint256 uscReward
  ) internal {
    uscStaking.updateEpoch(chiIncentives.uscStakingChiIncentives, uscReward, stEthRewards.uscStakingStEthReward);
    chiStaking.updateEpoch(stEthRewards.chiStakingStEthReward);
    chiLocking.updateEpoch(chiIncentives.chiLockingChiIncentives, stEthRewards.chiLockingStEthReward);
    chiVesting.updateEpoch(chiIncentives.chiVestingChiIncentives, stEthRewards.chiVestingStEthReward);
    uscEthLPStaking.updateEpoch(chiIncentivesForUscEthLPStaking, stEthRewards.uscEthLPStakingStEthReward);
    chiEthLPStaking.updateEpoch(chiIncentivesForChiEthLPStaking, stEthRewards.chiEthLPStakingStEthReward);
  }

  function _updateAndGetStETHRewards() internal returns (StETHRewards memory) {
    epochs[currentEpoch].reserveHolderTotalRewards = reserveHolder.getCumulativeRewards();
    uint256 stETHEpochrewards = epochs[currentEpoch].reserveHolderTotalRewards -
      epochs[currentEpoch - 1].reserveHolderTotalRewards;

    uint256 uscStakedChi = uscStaking.getStakedChi();
    uint256 chiStakedChi = chiStaking.getStakedChi();
    uint256 chiLockedChi = chiLocking.getStakedChi();
    uint256 chiVestingChi = chiVesting.getLockedChi();
    uint256 uscEthLPStakingChi = uscEthLPStaking.getStakedChi();
    uint256 chiEthLPStakingChi = chiEthLPStaking.getStakedChi();
    uint256 totalChi = uscStakedChi +
      chiStakedChi +
      chiLockedChi +
      chiVestingChi +
      uscEthLPStakingChi +
      chiEthLPStakingChi;

    uint256 uscStakingStEthReward;
    uint256 chiStakingStEthReward;
    uint256 chiLockingStEthReward;
    uint256 chiVestingStEthReward;
    uint256 uscEthLPStakingStEthReward;
    uint256 chiEthLPStakingStEthReward;
    if (totalChi != 0) {
      uscStakingStEthReward = Math.mulDiv(uscStakedChi, stETHEpochrewards, totalChi);
      chiStakingStEthReward = Math.mulDiv(chiStakedChi, stETHEpochrewards, totalChi);
      chiLockingStEthReward = Math.mulDiv(chiLockedChi, stETHEpochrewards, totalChi);
      chiVestingStEthReward = Math.mulDiv(chiVestingChi, stETHEpochrewards, totalChi);
      uscEthLPStakingStEthReward = Math.mulDiv(uscEthLPStakingChi, stETHEpochrewards, totalChi);
      chiEthLPStakingStEthReward = Math.mulDiv(chiEthLPStakingStEthReward, stETHEpochrewards, totalChi);
    }

    return
      StETHRewards({
        uscStakingStEthReward: uscStakingStEthReward,
        chiStakingStEthReward: chiStakingStEthReward,
        chiLockingStEthReward: chiLockingStEthReward,
        chiVestingStEthReward: chiVestingStEthReward,
        uscEthLPStakingStEthReward: uscEthLPStakingStEthReward,
        chiEthLPStakingStEthReward: chiEthLPStakingStEthReward
      });
  }
}

contracts/staking/StakingWithEpochs.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "../interfaces/IStakingWithEpochs.sol";
import "../interfaces/IMintableERC20.sol";
import "../interfaces/IBurnableERC20.sol";
import "../interfaces/IArbitrage.sol";

/// @title Contract for staking tokens
/// @notice Staking logic is placed inside this contract
/// @dev This contract is abstract and CHIStaking and USCStaking should inherit from him
abstract contract StakingWithEpochs is IStakingWithEpochs, ERC20Upgradeable {
  using SafeERC20 for IERC20;

  IERC20 public stakeToken;

  address public rewardController;
  uint256 public currentEpoch;

  mapping(address account => StakeData) public stakes;
  mapping(uint256 id => EpochData) public epochs;

  modifier onlyRewardController() {
    if (msg.sender != rewardController) {
      revert NotRewardController();
    }
    _;
  }

  function __StakingWithEpochs_init(
    string memory _name,
    string memory _symbol,
    IERC20 _stakeToken
  ) internal onlyInitializing {
    __ERC20_init(_name, _symbol);
    stakeToken = _stakeToken;
    currentEpoch = 1;
  }

  /// @inheritdoc IStakingWithEpochs
  function getUnclaimedRewards(address account, RewardToken token) external view returns (uint256) {
    return stakes[account].unclaimedRewards[token];
  }

  /// @inheritdoc IStakingWithEpochs
  function getCumulativeRewardsPerShare(uint256 epoch, RewardToken token) external view returns (uint256) {
    return epochs[epoch].cumulativeRewardsPerShare[token];
  }

  function unclaimedStChiAmount(address account) public view returns (uint256) {
    return _getCurrentReward(account, RewardToken.CHI);
  }

  /// @inheritdoc IStakingWithEpochs
  function stake(uint256 amount) external {
    if (amount == 0) {
      revert ZeroAmount();
    }

    stakeToken.safeTransferFrom(msg.sender, address(this), amount);
    _updateUnclaimedRewards(msg.sender);

    stakes[msg.sender].addSharesNextEpoch += amount;
    epochs[currentEpoch + 1].shares += amount;
    _mint(msg.sender, amount);

    emit Stake(msg.sender, amount);
  }

  /// @inheritdoc IStakingWithEpochs
  function unstake(uint256 amount) public virtual {
    unstake(amount, msg.sender);
  }

  /// @inheritdoc IStakingWithEpochs
  function unstake(uint256 amount, address toAddress) public virtual {
    if (amount == 0) {
      revert ZeroAmount();
    }

    StakeData storage stakeData = stakes[msg.sender];

    uint256 addSharesNextEpoch = stakeData.addSharesNextEpoch;
    if (stakeData.shares + addSharesNextEpoch < amount) {
      revert AmountBelowStakedBalance(stakeData.shares + addSharesNextEpoch, amount);
    }

    _updateUnclaimedRewards(msg.sender);
    addSharesNextEpoch = stakeData.addSharesNextEpoch;

    if (addSharesNextEpoch > amount) {
      stakeData.addSharesNextEpoch -= amount;
      epochs[currentEpoch + 1].shares -= amount;
    } else {
      uint256 fromCurrentShares = amount - addSharesNextEpoch;
      stakeData.shares -= fromCurrentShares;
      epochs[currentEpoch].shares -= fromCurrentShares;
      epochs[currentEpoch + 1].shares -= addSharesNextEpoch;
      stakeData.addSharesNextEpoch = 0;
    }

    stakeToken.safeTransfer(toAddress, amount);
    _burn(msg.sender, amount);

    emit Unstake(msg.sender, toAddress, amount);
  }

  function _updateUnclaimedRewards(address account) internal {
    StakeData storage stakeData = stakes[account];

    if (currentEpoch == stakeData.lastUpdatedEpoch) return;

    uint256 fromEpoch = stakeData.lastUpdatedEpoch > 0 ? stakeData.lastUpdatedEpoch - 1 : 0;
    _updateUnclaimedRewardsFromTo(stakeData, epochs[fromEpoch], epochs[currentEpoch - 1], stakeData.shares);

    if (stakeData.addSharesNextEpoch > 0) {
      _updateUnclaimedRewardsFromTo(
        stakeData,
        epochs[stakeData.lastUpdatedEpoch],
        epochs[currentEpoch - 1],
        stakeData.addSharesNextEpoch
      );
      stakeData.shares += stakeData.addSharesNextEpoch;
      stakeData.addSharesNextEpoch = 0;
    }

    stakeData.lastUpdatedEpoch = currentEpoch;
  }

  function _updateUnclaimedRewardsFromTo(
    StakeData storage stakeData,
    EpochData storage fromEpoch,
    EpochData storage toEpoch,
    uint256 shares
  ) internal {
    for (uint8 i = 0; i <= uint8(type(RewardToken).max); i++) {
      RewardToken token = RewardToken(i);
      if (_calculatingRewards(token)) {
        stakeData.unclaimedRewards[token] += Math.mulDiv(
          toEpoch.cumulativeRewardsPerShare[token] - fromEpoch.cumulativeRewardsPerShare[token],
          shares,
          1e18
        );
      }
    }
  }

  function _updateCumulativeRewardsForToken(
    EpochData storage epoch,
    EpochData storage prevEpoch,
    RewardToken token,
    uint256 amount
  ) internal {
    if (epoch.shares == 0) return;

    epoch.cumulativeRewardsPerShare[token] =
      prevEpoch.cumulativeRewardsPerShare[token] +
      Math.mulDiv(amount, 1e18, epoch.shares);
  }

  function _updateEpoch() internal {
    epochs[currentEpoch + 1].shares += epochs[currentEpoch].shares;
    currentEpoch++;
  }

  function _claimAndUpdateReward(address account, RewardToken token) internal returns (uint256) {
    _updateUnclaimedRewards(account);
    uint256 amount = stakes[account].unclaimedRewards[token];
    stakes[account].unclaimedRewards[token] = 0;
    return amount;
  }

  function _getCurrentReward(address account, RewardToken token) public view returns (uint256) {
    StakeData storage stakeData = stakes[account];
    uint256 totalAmount = stakeData.unclaimedRewards[token];

    if (currentEpoch == stakeData.lastUpdatedEpoch) return totalAmount;
    totalAmount += Math.mulDiv(
      epochs[currentEpoch - 1].cumulativeRewardsPerShare[token] -
        epochs[stakeData.lastUpdatedEpoch - 1].cumulativeRewardsPerShare[token],
      stakeData.shares,
      1e18
    );

    if (stakeData.addSharesNextEpoch > 0 && currentEpoch > stakeData.lastUpdatedEpoch + 1) {
      totalAmount += Math.mulDiv(
        epochs[currentEpoch - 1].cumulativeRewardsPerShare[token] -
          epochs[stakeData.lastUpdatedEpoch].cumulativeRewardsPerShare[token],
        stakeData.addSharesNextEpoch,
        1e18
      );
    }

    return totalAmount;
  }

  function _setRewardController(address _rewardController) internal {
    rewardController = _rewardController;
  }

  function _calculatingRewards(RewardToken token) internal virtual returns (bool);

  uint256[50] private __gap;
}

contracts/staking/USCStaking.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../interfaces/IUSCStaking.sol";
import "../interfaces/IArbitrage.sol";
import "../interfaces/IChiLocking.sol";
import "./StakingWithEpochs.sol";

/// @title Contract for staking USC tokens
/// @notice Staking is done in epochs
/// @dev Contract is upgradeable
contract USCStaking is IUSCStaking, OwnableUpgradeable, StakingWithEpochs {
  using SafeERC20 for IERC20;

  uint256 public constant MIN_LOCK_DURATION = 4; // 4 epochs = 4 weeks = 1 month
  uint256 public constant MAX_LOCK_DURATION = 208; // 208 epochs = 208 weeks = 4 years

  IERC20 public chi;
  IChiLocking public chiLockingContract;

  uint256 public chiAmountFromEmissions;

  function initialize(IERC20 _usc, IERC20 _chi, IChiLocking _chiLockingContract) external initializer {
    __Ownable_init();
    __StakingWithEpochs_init("Staked USC", "stUSC", _usc);
    chi = _chi;
    chiLockingContract = _chiLockingContract;
  }

  /// @inheritdoc IStaking
  function setRewardController(address _rewardController) external onlyOwner {
    _setRewardController(_rewardController);
  }

  /// @inheritdoc IUSCStaking
  function updateEpoch(uint256 chiEmissions, uint256 uscRewards, uint256 stETHrewards) external onlyRewardController {
    EpochData storage epoch = epochs[currentEpoch];
    EpochData storage prevEpoch = epochs[currentEpoch - 1];

    _updateCumulativeRewardsForToken(epoch, prevEpoch, RewardToken.CHI, chiEmissions);
    _updateCumulativeRewardsForToken(epoch, prevEpoch, RewardToken.USC, uscRewards);
    _updateCumulativeRewardsForToken(epoch, prevEpoch, RewardToken.STETH, stETHrewards);
    _updateEpoch();

    chiAmountFromEmissions += chiEmissions;

    emit UpdateEpoch(currentEpoch - 1, chiEmissions, uscRewards, stETHrewards);
  }

  /// @inheritdoc IUSCStaking
  function lockChi(uint256 duration) external {
    if (duration < MIN_LOCK_DURATION || duration > MAX_LOCK_DURATION) {
      revert InvalidDuration(duration);
    }

    uint256 amount = _claimAndUpdateReward(msg.sender, RewardToken.CHI);
    chiLockingContract.lockChi(msg.sender, amount, duration);

    chiAmountFromEmissions -= amount;
    chi.safeTransfer(address(chiLockingContract), amount);

    emit LockChi(msg.sender, amount, duration);
  }

  /// @inheritdoc IUSCStaking
  function claimUSCRewards() external {
    uint256 amount = _claimAndUpdateReward(msg.sender, RewardToken.USC);
    stakeToken.safeTransfer(msg.sender, amount);

    emit ClaimUSCRewards(msg.sender, amount);
  }

  /// @inheritdoc IStaking
  function claimStETH(address account) external onlyRewardController returns (uint256) {
    uint256 amount = _claimAndUpdateReward(account, RewardToken.STETH);
    emit ClaimStETH(account, amount);
    return amount;
  }

  /// @inheritdoc IStaking
  function unclaimedStETHAmount(address account) public view returns (uint256) {
    return _getCurrentReward(account, RewardToken.STETH);
  }

  /// @inheritdoc IStaking
  function getStakedChi() external view returns (uint256) {
    return chiAmountFromEmissions;
  }

  function _calculatingRewards(RewardToken token) internal pure override returns (bool) {
    if (token == RewardToken.USC) return true;
    if (token == RewardToken.CHI) return true;
    if (token == RewardToken.STETH) return true;
    return false;
  }
}

contracts/uniswap/libraries/SafeMath.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

// library copied from uniswap/v2-core/contracts/libraries/SafeMath.sol
// the only change is in pragma solidity version.
// this contract was the reason of incompatible solidity version error

// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)

library SafeMath {
  function add(uint x, uint y) internal pure returns (uint z) {
    require((z = x + y) >= x, "ds-math-add-overflow");
  }

  function sub(uint x, uint y) internal pure returns (uint z) {
    require((z = x - y) <= x, "ds-math-sub-underflow");
  }

  function mul(uint x, uint y) internal pure returns (uint z) {
    require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
  }
}

contracts/uniswap/libraries/UniswapV2Library.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

// library copied from uniswap/v2-core/contracts/libraries/UniswapV2Library.sol
// the only change is in pragma solidity version.

import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";

import "./SafeMath.sol";

library UniswapV2Library {
  using SafeMath for uint;

  // returns sorted token addresses, used to handle return values from pairs sorted in this order
  function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
    require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES");
    (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
    require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS");
  }

  // calculates the CREATE2 address for a pair without making any external calls
  function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
    (address token0, address token1) = sortTokens(tokenA, tokenB);
    pair = address(
      uint160(
        uint(
          keccak256(
            abi.encodePacked(
              hex"ff",
              factory,
              keccak256(abi.encodePacked(token0, token1)),
              hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
            )
          )
        )
      )
    );
  }

  // fetches and sorts the reserves for a pair
  function getReserves(
    address factory,
    address tokenA,
    address tokenB
  ) internal view returns (uint reserveA, uint reserveB) {
    (address token0, ) = sortTokens(tokenA, tokenB);
    (uint reserve0, uint reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
    (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
  }

  // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
  function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
    require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT");
    require(reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY");
    amountB = amountA.mul(reserveB) / reserveA;
  }

  // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
  function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
    require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT");
    require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY");
    uint amountInWithFee = amountIn.mul(997);
    uint numerator = amountInWithFee.mul(reserveOut);
    uint denominator = reserveIn.mul(1000).add(amountInWithFee);
    amountOut = numerator / denominator;
  }

  // given an output amount of an asset and pair reserves, returns a required input amount of the other asset
  function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
    require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT");
    require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY");
    uint numerator = reserveIn.mul(amountOut).mul(1000);
    uint denominator = reserveOut.sub(amountOut).mul(997);
    amountIn = (numerator / denominator).add(1);
  }

  // performs chained getAmountOut calculations on any number of pairs
  function getAmountsOut(
    address factory,
    uint amountIn,
    address[] memory path
  ) internal view returns (uint[] memory amounts) {
    require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
    amounts = new uint[](path.length);
    amounts[0] = amountIn;
    for (uint i; i < path.length - 1; i++) {
      (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
      amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
    }
  }

  // performs chained getAmountIn calculations on any number of pairs
  function getAmountsIn(
    address factory,
    uint amountOut,
    address[] memory path
  ) internal view returns (uint[] memory amounts) {
    require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
    amounts = new uint[](path.length);
    amounts[amounts.length - 1] = amountOut;
    for (uint i = path.length - 1; i > 0; i--) {
      (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
      amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
    }
  }
}
Compiler settingsShow
{
  "viaIR": true,
  "libraries": {},
  "optimizer": {
    "runs": 1000,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.