Skip to content
Verified contractExactMIT

RewardControllerV2

Address0xeeddebd206d6586c918d19c688a57e364bbce407
Balance

0 ETH

 

Transactions

1

 

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
EVM version
paris
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
21,472,493
Creation transaction
0xf45bb3efc5…5c940aaa70

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;

  // Upgrade
  uint256 public stEthPercentageForUscStaking;
  uint256 public stEthPercentageForChiStaking;
  uint256 public stEthPercentageForChiLocking;
  uint256 public stEthPercentageForChiVesting;
  uint256 public stEthPercentageForUscEthLPStaking;
  uint256 public stEthPercentageForChiEthLPStaking;

  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 setStEthPercentages(
    uint256 _stEthPercentageForUscStaking,
    uint256 _stEthPercentageForChiStaking,
    uint256 _stEthPercentageForChiLocking,
    uint256 _stEthPercentageForChiVesting,
    uint256 _stEthPercentageForUscEthLPStaking,
    uint256 _stEthPercentageForChiEthLPStaking
  ) external onlyOwner {
    uint256 sumOfPercentages = _stEthPercentageForUscStaking +
      _stEthPercentageForChiStaking +
      _stEthPercentageForChiLocking +
      _stEthPercentageForChiVesting +
      _stEthPercentageForUscEthLPStaking +
      _stEthPercentageForChiEthLPStaking;

    if (sumOfPercentages != MAX_PERCENTAGE) {
      revert StEthYieldPercentagesNotCorrect();
    }

    stEthPercentageForUscStaking = _stEthPercentageForUscStaking;
    stEthPercentageForChiStaking = _stEthPercentageForChiStaking;
    stEthPercentageForChiLocking = _stEthPercentageForChiLocking;
    stEthPercentageForChiVesting = _stEthPercentageForChiVesting;
    stEthPercentageForUscEthLPStaking = _stEthPercentageForUscEthLPStaking;
    stEthPercentageForChiEthLPStaking = _stEthPercentageForChiEthLPStaking;
  }

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

    ChiIncentives memory chiIncentives = _updateAndGetChiIncentives();

    _updateEpochsInSubcontracts(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 totalChiIncentives = chiIncentives.uscStakingChiIncentives +
      chiIncentives.chiLockingChiIncentives +
      chiIncentives.chiVestingChiIncentives +
      chiIncentivesForUscEthLPStaking +
      chiIncentivesForChiEthLPStaking;
    emit UpdateEpoch(currentEpoch - 1, 0, 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 rescueTokens(address token, address to, uint256 amount) external onlyOwner {
    IERC20(token).safeTransfer(to, amount);
  }

  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(ChiIncentives memory chiIncentives, uint256 uscReward) internal {
    uscStaking.updateEpoch(chiIncentives.uscStakingChiIncentives, uscReward, 0);
    chiStaking.updateEpoch(0);
    chiLocking.updateEpoch(chiIncentives.chiLockingChiIncentives, 0);
    chiVesting.updateEpoch(chiIncentives.chiVestingChiIncentives, 0);
    uscEthLPStaking.updateEpoch(chiIncentivesForUscEthLPStaking, 0);
    chiEthLPStaking.updateEpoch(chiIncentivesForChiEthLPStaking, 0);
  }
}

@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 {Initializable} from "../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/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 (last updated v4.9.4) (utils/Context.sol)

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

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

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

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

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }

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

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

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

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

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

  /// @notice Sets percentages of stETH rewards for each staking, locking and vesting contract
  /// @param _uscStakingStEthPercentage Percentage of stETH rewards for USC staking contract
  /// @param _chiStakingStEthPercentage Percentage of stETH rewards for CHI staking contract
  /// @param _chiLockingStEthPercentage Percentage of stETH rewards for CHI locking contract
  /// @param _chiVestingStEthPercentage Percentage of stETH rewards for CHI vesting contract
  /// @param _uscEthLPStakingStEthPercentage Percentage of stETH rewards for USC-ETH LP staking contract
  /// @param _chiEthLPStakingStEthPercentage Percentage of stETH rewards for CHI-ETH LP staking contract
  /// @dev Percentages should be in range 0-100, and sum of all percentages should be 100, 100% = 10000
  /// @dev Only owner can call this function
  function setStEthPercentages(
    uint256 _uscStakingStEthPercentage,
    uint256 _chiStakingStEthPercentage,
    uint256 _chiLockingStEthPercentage,
    uint256 _chiVestingStEthPercentage,
    uint256 _uscEthLPStakingStEthPercentage,
    uint256 _chiEthLPStakingStEthPercentage
  ) external;

  /// @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/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;
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 1000,
    "enabled": true
  },
  "evmVersion": "paris",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.