creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "contracts/8.10/xGF.sol": {
        "content": "// SPDX-License-Identifier: MIT\n/**\nPorted to Solidity from: https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/VotingEscrow.vy\n**/\n\npragma solidity 0.8.10;\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\n\nimport \"./interfaces/IRewardManager.sol\";\nimport \"./interfaces/IStakingERC20.sol\";\n\nimport \"./SafeToken.sol\";\n\n/// @title xGF - The goverance token of GuildFi\n// solhint-disable not-rely-on-time\n// solhint-disable-next-line contract-name-camelcase\ncontract xGF is Initializable, ReentrancyGuardUpgradeable, OwnableUpgradeable {\n  using SafeToken for address;\n\n  // --- Events ---\n  event LogDeposit(\n    address indexed locker,\n    uint256 value,\n    uint256 indexed lockTime,\n    uint256 lockType,\n    uint256 timestamp\n  );\n  event LogWithdraw(address indexed locker, uint256 value, uint256 timestamp);\n  event LogEarlyWithdraw(address indexed locker, uint256 value, uint256 timestamp);\n  event LogSetBreaker(uint256 previousBreaker, uint256 breaker);\n  event LogSupply(uint256 previousSupply, uint256 supply);\n  event LogSetEarlyWithdrawConfig(\n    address indexed caller,\n    uint64 oldEarlyWithdrawFeeBps,\n    uint64 newEarlyWithdrawFeeBps,\n    uint64 oldRedistributeBps,\n    uint64 newRedistribiteBps,\n    address oldTreasuryAddr,\n    address newTreasuryAddr,\n    address oldRedistributeAddr,\n    address newRedistributeAddr\n  );\n  event LogRedistribute(address indexed caller, address destination, uint256 amount);\n  event LogSetWhitelistedCaller(address indexed caller, address indexed addr, bool ok);\n  event LogSetWhitelistedRedistributors(address indexed caller, address indexed addr, bool ok);\n  event LogMigrated(address indexed to, uint256 amount);\n\n  struct Point {\n    int128 bias; // Voting weight\n    int128 slope; // Multiplier factor to get voting weight at a given time\n    uint256 timestamp;\n    uint256 blockNumber;\n  }\n\n  struct LockedBalance {\n    int128 amount;\n    uint256 end;\n  }\n\n  // --- Constants ---\n  uint256 public constant ACTION_DEPOSIT_FOR = 0;\n  uint256 public constant ACTION_CREATE_LOCK = 1;\n  uint256 public constant ACTION_INCREASE_LOCK_AMOUNT = 2;\n  uint256 public constant ACTION_INCREASE_UNLOCK_TIME = 3;\n  uint256 public constant ACTION_ADJUST_LOCK = 4;\n\n  uint256 public constant WEEK = 7 days;\n  // MAX_LOCK 53 weeks - 1 seconds\n  uint256 public constant MAX_LOCK = (53 * WEEK) - 1;\n  uint256 public constant MULTIPLIER = 10 ** 18;\n\n  // Token to be locked (GF)\n  address public token;\n  // Total supply of GF that get locked\n  uint256 public supply;\n\n  // Mapping (user => LockedBalance) to keep locking information for each user\n  mapping(address => LockedBalance) public locks;\n\n  // A global point of time.\n  uint256 public epoch;\n  // An array of points (global).\n  Point[] public pointHistory;\n  // Mapping (user => Point) to keep track of user point of a given epoch (index of Point is epoch)\n  mapping(address => Point[]) public userPointHistory;\n  // Mapping (user => epoch) to keep track which epoch user at\n  mapping(address => uint256) public userPointEpoch;\n  // Mapping (round off timestamp to week => slopeDelta) to keep track slope changes over epoch\n  mapping(uint256 => int128) public slopeChanges;\n\n  // Circuit breaker\n  uint256 public breaker;\n\n  // --- ERC20 compatible variables ---\n  string public name;\n  string public symbol;\n  uint8 public decimals;\n\n  // --- Early Withdrawal Configs ---\n  uint64 public earlyWithdrawBpsPerWeek;\n  uint64 public redistributeBps;\n  uint256 public accumRedistribute;\n  address public treasuryAddr;\n  address public redistributeAddr;\n  address public rewardManager;\n\n  // --- whitelist address  ---\n  mapping(address => bool) public whitelistedCallers;\n  mapping(address => bool) public whitelistedRedistributors;\n\n  address public xGFMigrator;\n  bool public migrationEnabled;\n\n\n  modifier onlyRedistributors() {\n    require(whitelistedRedistributors[msg.sender], \"not redistributors\");\n    _;\n  }\n\n  modifier onlyEOAorWhitelisted() {\n    if (!whitelistedCallers[msg.sender]) {\n      require(msg.sender == tx.origin, \"not eoa\");\n    }\n    _;\n  }\n\n  modifier onlyMigrationEnabled() {\n    require(migrationEnabled, \"Migration is disabled\");\n    _;\n  }\n\n  modifier onlyMigrationDisable() {\n    require(!migrationEnabled, \"Not allowed while migration is enabled\");\n    _;\n  }\n\n  /// @notice Initialize xGF\n  /// @param _token The address of GF token\n  /// @param _name name of this token\n  /// @param _symbol symbol of this token\n  function initialize(address _token, string memory _name, string memory _symbol) external initializer {\n    OwnableUpgradeable.__Ownable_init();\n    ReentrancyGuardUpgradeable.__ReentrancyGuard_init();\n\n    token = _token;\n\n    pointHistory.push(Point({ bias: 0, slope: 0, timestamp: block.timestamp, blockNumber: block.number }));\n\n    uint8 _decimals = IStakingERC20(_token).decimals();\n    decimals = _decimals;\n\n    name = _name;\n    symbol = _symbol;\n  }\n\n  /// @notice Return the balance of xGF at a given \"_blockNumber\"\n  /// @param _user The address to get a balance of xGF\n  /// @param _blockNumber The speicific block number that you want to check the balance of xGF\n  function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256) {\n    require(_blockNumber <= block.number, \"bad _blockNumber\");\n\n    // Get most recent user Point to block\n    uint256 _userEpoch = _findUserBlockEpoch(_user, _blockNumber);\n    if (_userEpoch == 0) {\n      return 0;\n    }\n    Point memory _userPoint = userPointHistory[_user][_userEpoch];\n\n    // Get most recent global point to block\n    uint256 _maxEpoch = epoch;\n    uint256 _epoch = _findBlockEpoch(_blockNumber, _maxEpoch);\n    Point memory _point0 = pointHistory[_epoch];\n\n    uint256 _blockDelta = 0;\n    uint256 _timeDelta = 0;\n    if (_epoch < _maxEpoch) {\n      Point memory _point1 = pointHistory[_epoch + 1];\n      _blockDelta = _point1.blockNumber - _point0.blockNumber;\n      _timeDelta = _point1.timestamp - _point0.timestamp;\n    } else {\n      _blockDelta = block.number - _point0.blockNumber;\n      _timeDelta = block.timestamp - _point0.timestamp;\n    }\n    uint256 _blockTime = _point0.timestamp;\n    if (_blockDelta != 0) {\n      _blockTime += (_timeDelta * (_blockNumber - _point0.blockNumber)) / _blockDelta;\n    }\n\n    _userPoint.bias -= (_userPoint.slope * SafeCastUpgradeable.toInt128(int256(_blockTime - _userPoint.timestamp)));\n\n    if (_userPoint.bias < 0) {\n      return 0;\n    }\n\n    return SafeCastUpgradeable.toUint256(_userPoint.bias);\n  }\n\n  /// @notice Return the voting weight of a givne user\n  /// @param _user The address of a user\n  function balanceOf(address _user) external view returns (uint256) {\n    uint256 _epoch = userPointEpoch[_user];\n    if (_epoch == 0) {\n      return 0;\n    }\n    Point memory _lastPoint = userPointHistory[_user][_epoch];\n    _lastPoint.bias =\n      _lastPoint.bias -\n      (_lastPoint.slope * SafeCastUpgradeable.toInt128(int256(block.timestamp - _lastPoint.timestamp)));\n    if (_lastPoint.bias < 0) {\n      _lastPoint.bias = 0;\n    }\n    return SafeCastUpgradeable.toUint256(_lastPoint.bias);\n  }\n\n  /// @notice Record global and per-user slope to checkpoint\n  /// @param _address User's wallet address. Only global if 0x0\n  /// @param _prevLocked User's previous locked balance and end lock time\n  /// @param _newLocked User's new locked balance and end lock time\n  function _checkpoint(address _address, LockedBalance memory _prevLocked, LockedBalance memory _newLocked) internal {\n    Point memory _userPrevPoint = Point({ slope: 0, bias: 0, timestamp: 0, blockNumber: 0 });\n    Point memory _userNewPoint = Point({ slope: 0, bias: 0, timestamp: 0, blockNumber: 0 });\n\n    int128 _prevSlopeDelta = 0;\n    int128 _newSlopeDelta = 0;\n    uint256 _epoch = epoch;\n\n    // if not 0x0, then update user's point\n    if (_address != address(0)) {\n      // Calculate slopes and biases according to linear decay graph\n      // slope = lockedAmount / MAX_LOCK => Get the slope of a linear decay graph\n      // bias = slope * (lockedEnd - currentTimestamp) => Get the voting weight at a given time\n      // Kept at zero when they have to\n      if (_prevLocked.end > block.timestamp && _prevLocked.amount > 0) {\n        // Calculate slope and bias for the prev point\n        _userPrevPoint.slope = _prevLocked.amount / SafeCastUpgradeable.toInt128(int256(MAX_LOCK));\n        _userPrevPoint.bias =\n          _userPrevPoint.slope *\n          SafeCastUpgradeable.toInt128(int256(_prevLocked.end - block.timestamp));\n      }\n      if (_newLocked.end > block.timestamp && _newLocked.amount > 0) {\n        // Calculate slope and bias for the new point\n        _userNewPoint.slope = _newLocked.amount / SafeCastUpgradeable.toInt128(int256(MAX_LOCK));\n        _userNewPoint.bias =\n          _userNewPoint.slope *\n          SafeCastUpgradeable.toInt128(int256(_newLocked.end - block.timestamp));\n      }\n\n      // Handle user history here\n      // Do it here to prevent stack overflow\n      uint256 _userEpoch = userPointEpoch[_address];\n      // If user never ever has any point history, push it here for him.\n      if (_userEpoch == 0) {\n        userPointHistory[_address].push(_userPrevPoint);\n      }\n\n      // Shift user's epoch by 1 as we are writing a new point for a user\n      userPointEpoch[_address] = _userEpoch + 1;\n\n      // Update timestamp & block number then push new point to user's history\n      _userNewPoint.timestamp = block.timestamp;\n      _userNewPoint.blockNumber = block.number;\n      userPointHistory[_address].push(_userNewPoint);\n\n      // Read values of scheduled changes in the slope\n      // _prevLocked.end can be in the past and in the future\n      // _newLocked.end can ONLY be in the FUTURE unless everything expired (anything more than zeros)\n      _prevSlopeDelta = slopeChanges[_prevLocked.end];\n      if (_newLocked.end != 0) {\n        // Handle when _newLocked.end != 0\n        if (_newLocked.end == _prevLocked.end) {\n          // This will happen when user adjust lock but end remains the same\n          // Possibly when user deposited more GF to his locker\n          _newSlopeDelta = _prevSlopeDelta;\n        } else {\n          // This will happen when user increase lock\n          _newSlopeDelta = slopeChanges[_newLocked.end];\n        }\n      }\n    }\n\n    // Handle global states here\n    Point memory _lastPoint = Point({ bias: 0, slope: 0, timestamp: block.timestamp, blockNumber: block.number });\n    if (_epoch > 0) {\n      // If _epoch > 0, then there is some history written\n      // Hence, _lastPoint should be pointHistory[_epoch]\n      // else _lastPoint should an empty point\n      _lastPoint = pointHistory[_epoch];\n    }\n    // _lastCheckpoint => timestamp of the latest point\n    // if no history, _lastCheckpoint should be block.timestamp\n    // else _lastCheckpoint should be the timestamp of latest pointHistory\n    uint256 _lastCheckpoint = _lastPoint.timestamp;\n\n    // initialLastPoint is used for extrapolation to calculate block number\n    // (approximately, for xxxAt methods) and save them\n    // as we cannot figure that out exactly from inside contract\n    Point memory _initialLastPoint = Point({\n      bias: 0,\n      slope: 0,\n      timestamp: _lastPoint.timestamp,\n      blockNumber: _lastPoint.blockNumber\n    });\n\n    // If last point is already recorded in this block, _blockSlope=0\n    // That is ok because we know the block in such case\n    uint256 _blockSlope = 0;\n    if (block.timestamp > _lastPoint.timestamp) {\n      // Recalculate _blockSlope if _lastPoint.timestamp < block.timestamp\n      // Possiblity when epoch = 0 or _blockSlope hasn't get updated in this block\n      _blockSlope = (MULTIPLIER * (block.number - _lastPoint.blockNumber)) / (block.timestamp - _lastPoint.timestamp);\n    }\n\n    // Go over weeks to fill history and calculate what the current point is\n    uint256 _weekCursor = _timestampToFloorWeek(_lastCheckpoint);\n    for (uint256 i = 0; i < 255; i++) {\n      // This logic will works for 5 years, if more than that vote power will be broken 😟\n      // Bump _weekCursor a week\n      _weekCursor = _weekCursor + WEEK;\n      int128 _slopeDelta = 0;\n      if (_weekCursor > block.timestamp) {\n        // If the given _weekCursor go beyond block.timestamp,\n        // We take block.timestamp as the cursor\n        _weekCursor = block.timestamp;\n      } else {\n        // If the given _weekCursor is behind block.timestamp\n        // We take _slopeDelta from the recorded slopeChanges\n        // We can use _weekCursor directly because key of slopeChanges is timestamp round off to week\n        _slopeDelta = slopeChanges[_weekCursor];\n      }\n      // Calculate _biasDelta = _lastPoint.slope * (_weekCursor - _lastCheckpoint)\n      int128 _biasDelta = _lastPoint.slope * SafeCastUpgradeable.toInt128(int256((_weekCursor - _lastCheckpoint)));\n      _lastPoint.bias = _lastPoint.bias - _biasDelta;\n      _lastPoint.slope = _lastPoint.slope + _slopeDelta;\n      if (_lastPoint.bias < 0) {\n        // This can happen\n        _lastPoint.bias = 0;\n      }\n      if (_lastPoint.slope < 0) {\n        // This cannot happen, just make sure\n        _lastPoint.slope = 0;\n      }\n      // Update _lastPoint to the new one\n      _lastCheckpoint = _weekCursor;\n      _lastPoint.timestamp = _weekCursor;\n      // As we cannot figure that out block timestamp -> block number exactly\n      // when query states from xxxAt methods, we need to calculate block number\n      // based on _initalLastPoint\n      _lastPoint.blockNumber =\n        _initialLastPoint.blockNumber +\n        ((_blockSlope * ((_weekCursor - _initialLastPoint.timestamp))) / MULTIPLIER);\n      _epoch = _epoch + 1;\n      if (_weekCursor == block.timestamp) {\n        // Hard to be happened, but better handling this case too\n        _lastPoint.blockNumber = block.number;\n        break;\n      } else {\n        pointHistory.push(_lastPoint);\n      }\n    }\n    // Now, each week pointHistory has been filled until current timestamp (round off by week)\n    // Update epoch to be the latest state\n    epoch = _epoch;\n\n    if (_address != address(0)) {\n      // If the last point was in the block, the slope change should have been applied already\n      // But in such case slope shall be 0\n      _lastPoint.slope = _lastPoint.slope + _userNewPoint.slope - _userPrevPoint.slope;\n      _lastPoint.bias = _lastPoint.bias + _userNewPoint.bias - _userPrevPoint.bias;\n      if (_lastPoint.slope < 0) {\n        _lastPoint.slope = 0;\n      }\n      if (_lastPoint.bias < 0) {\n        _lastPoint.bias = 0;\n      }\n    }\n\n    // Record the new point to pointHistory\n    // This would be the latest point for global epoch\n    pointHistory.push(_lastPoint);\n\n    if (_address != address(0)) {\n      // Schedule the slope changes (slope is going downward)\n      // We substract _newSlopeDelta from `_newLocked.end`\n      // and add _prevSlopeDelta to `_prevLocked.end`\n      if (_prevLocked.end > block.timestamp) {\n        // _prevSlopeDelta was <something> - _userPrevPoint.slope, so we offset that first\n        _prevSlopeDelta = _prevSlopeDelta + _userPrevPoint.slope;\n        if (_newLocked.end == _prevLocked.end) {\n          // Handle the new deposit. Not increasing lock.\n          _prevSlopeDelta = _prevSlopeDelta - _userNewPoint.slope;\n        }\n        slopeChanges[_prevLocked.end] = _prevSlopeDelta;\n      }\n      if (_newLocked.end > block.timestamp) {\n        if (_newLocked.end > _prevLocked.end) {\n          // At this line, the old slope should gone\n          _newSlopeDelta = _newSlopeDelta - _userNewPoint.slope;\n          slopeChanges[_newLocked.end] = _newSlopeDelta;\n        }\n      }\n    }\n  }\n\n  /// @notice Trigger global checkpoint\n  function checkpoint() external {\n    LockedBalance memory empty = LockedBalance({ amount: 0, end: 0 });\n    _checkpoint(address(0), empty, empty);\n  }\n\n  /// @notice Create a new lock.\n  /// @dev This will crate a new lock and deposit GF to xGF Vault\n  /// @param _amount the amount that user wishes to deposit\n  /// @param _unlockTime the timestamp when GF get unlocked, it will be\n  /// floored down to whole weeks\n  function createLock(uint256 _amount, uint256 _unlockTime) external onlyEOAorWhitelisted nonReentrant onlyMigrationDisable {\n    _unlockTime = _timestampToFloorWeek(_unlockTime);\n    LockedBalance memory _locked = locks[msg.sender];\n\n    require(_amount > 0, \"bad amount\");\n    require(_locked.amount == 0, \"already lock\");\n    require(_unlockTime > block.timestamp, \"can only lock until future\");\n    require(_unlockTime <= block.timestamp + MAX_LOCK, \"can only lock 1 year max\");\n\n    IRewardManager(rewardManager).claim(msg.sender);\n    _depositFor(msg.sender, _amount, _unlockTime, _locked, ACTION_CREATE_LOCK);\n  }\n\n  /// @notice Deposit `_amount` tokens for `_for` and add to `locks[_for]`\n  /// @dev This function is used for deposit to created lock. Not for extend locktime.\n  /// @param _for The address to do the deposit\n  /// @param _amount The amount that user wishes to deposit\n  function depositFor(address _for, uint256 _amount) external nonReentrant onlyMigrationDisable {\n    LockedBalance memory _lock = LockedBalance({ amount: locks[_for].amount, end: locks[_for].end });\n\n    require(_amount > 0, \"bad _amount\");\n    require(_lock.amount > 0, \"!lock existed\");\n    require(_lock.end > block.timestamp, \"lock expired. please withdraw\");\n\n    _depositFor(_for, _amount, 0, _lock, ACTION_DEPOSIT_FOR);\n  }\n\n  /// @notice Internal function to perform deposit and lock GF for a user\n  /// @param _for The address to be locked and received xGF\n  /// @param _amount The amount to deposit\n  /// @param _unlockTime New time to unlock GF. Pass 0 if no change.\n  /// @param _prevLocked Existed locks[_for]\n  /// @param _actionType The action that user did as this internal function shared among\n  /// several external functions\n  function _depositFor(\n    address _for,\n    uint256 _amount,\n    uint256 _unlockTime,\n    LockedBalance memory _prevLocked,\n    uint256 _actionType\n  ) internal  {\n    // Initiate _supplyBefore & update supply\n    uint256 _supplyBefore = supply;\n    supply = _supplyBefore + _amount;\n\n    // Store _prevLocked\n    LockedBalance memory _newLocked = LockedBalance({ amount: _prevLocked.amount, end: _prevLocked.end });\n\n    // Adding new lock to existing lock, or if lock is expired\n    // - creating a new one\n    _newLocked.amount = _newLocked.amount + SafeCastUpgradeable.toInt128(int256(_amount));\n    if (_unlockTime != 0) {\n      _newLocked.end = _unlockTime;\n    }\n    locks[_for] = _newLocked;\n\n    // Handling checkpoint here\n    _checkpoint(_for, _prevLocked, _newLocked);\n\n    if (_amount != 0) {\n      token.safeTransferFrom(msg.sender, address(this), _amount);\n    }\n\n    emit LogDeposit(_for, _amount, _newLocked.end, _actionType, block.timestamp);\n    emit LogSupply(_supplyBefore, supply);\n  }\n\n  /// @notice Do Binary Search to find out block timestamp for block number\n  /// @param _blockNumber The block number to find timestamp\n  /// @param _maxEpoch No beyond this timestamp\n  function _findBlockEpoch(uint256 _blockNumber, uint256 _maxEpoch) internal view returns (uint256) {\n    uint256 _min = 0;\n    uint256 _max = _maxEpoch;\n    // Loop for 128 times -> enough for 128-bit numbers\n    for (uint256 i = 0; i < 128; i++) {\n      if (_min >= _max) {\n        break;\n      }\n      uint256 _mid = (_min + _max + 1) / 2;\n      if (pointHistory[_mid].blockNumber <= _blockNumber) {\n        _min = _mid;\n      } else {\n        _max = _mid - 1;\n      }\n    }\n    return _min;\n  }\n\n  /// @notice Do Binary Search to find the most recent user point history preceeding block\n  /// @param _user The address of user to find\n  /// @param _blockNumber Find the most recent point history before this block number\n  function _findUserBlockEpoch(address _user, uint256 _blockNumber) internal view returns (uint256) {\n    uint256 _min = 0;\n    uint256 _max = userPointEpoch[_user];\n    for (uint256 i = 0; i < 128; i++) {\n      if (_min >= _max) {\n        break;\n      }\n      uint256 _mid = (_min + _max + 1) / 2;\n      if (userPointHistory[_user][_mid].blockNumber <= _blockNumber) {\n        _min = _mid;\n      } else {\n        _max = _mid - 1;\n      }\n    }\n    return _min;\n  }\n\n  /// @notice Increase lock amount and inrease unlock time\n  /// @param _amount The amount of GF to be added to the lock\n  /// @param _newUnlockTime  The new unlock time to be updated\n  function adjustLock(uint256 _amount, uint256 _newUnlockTime) external onlyEOAorWhitelisted nonReentrant onlyMigrationDisable {\n    LockedBalance memory _lock = LockedBalance({ amount: locks[msg.sender].amount, end: locks[msg.sender].end });\n    _newUnlockTime = _timestampToFloorWeek(_newUnlockTime);\n\n    require(_lock.amount > 0, \"!lock existed\");\n    require(_lock.end > block.timestamp, \"lock expired. please withdraw\");\n    require(_amount > 0 || _newUnlockTime != _lock.end, \"nothing to adjust\");\n\n    if (_newUnlockTime != _lock.end) {\n      require(_newUnlockTime > _lock.end, \"only extend lock\");\n      require(_newUnlockTime <= block.timestamp + MAX_LOCK, \"1 year max\");\n    }\n\n    _depositFor(msg.sender, _amount, _newUnlockTime, _lock, ACTION_ADJUST_LOCK);\n  }\n\n  /// @notice Round off random timestamp to week\n  /// @param _timestamp The timestamp to be rounded off\n  function _timestampToFloorWeek(uint256 _timestamp) internal pure returns (uint256) {\n    return (_timestamp / WEEK) * WEEK;\n  }\n\n  /// @notice Calculate total supply of xGF (voting power)\n  function totalSupply() external view returns (uint256) {\n    return _totalSupplyAt(pointHistory[epoch], block.timestamp);\n  }\n\n  /// @notice Calculate total supply of xGF at specific block\n  /// @param _blockNumber The specific block number to calculate totalSupply\n  function totalSupplyAt(uint256 _blockNumber) external view returns (uint256) {\n    require(_blockNumber <= block.number, \"bad _blockNumber\");\n    uint256 _epoch = epoch;\n    uint256 _targetEpoch = _findBlockEpoch(_blockNumber, _epoch);\n\n    Point memory _point = pointHistory[_targetEpoch];\n    uint256 _timeDelta = 0;\n    if (_targetEpoch < _epoch) {\n      Point memory _nextPoint = pointHistory[_targetEpoch + 1];\n      if (_point.blockNumber != _nextPoint.blockNumber) {\n        _timeDelta =\n          ((_blockNumber - _point.blockNumber) * (_nextPoint.timestamp - _point.timestamp)) /\n          (_nextPoint.blockNumber - _point.blockNumber);\n      }\n    } else {\n      if (_point.blockNumber != block.number) {\n        _timeDelta =\n          ((_blockNumber - _point.blockNumber) * (block.timestamp - _point.timestamp)) /\n          (block.number - _point.blockNumber);\n      }\n    }\n\n    return _totalSupplyAt(_point, _point.timestamp + _timeDelta);\n  }\n\n  /// @notice Calculate total supply of xGF (voting power) at some point in the past\n  /// @param _point The point to start to search from\n  /// @param _timestamp The timestamp to calculate the total voting power at\n  function _totalSupplyAt(Point memory _point, uint256 _timestamp) internal view returns (uint256) {\n    Point memory _lastPoint = _point;\n    uint256 _weekCursor = _timestampToFloorWeek(_point.timestamp);\n    // Iterate through weeks to take slopChanges into the account\n    for (uint256 i = 0; i < 255; i++) {\n      _weekCursor = _weekCursor + WEEK;\n      int128 _slopeDelta = 0;\n      if (_weekCursor > _timestamp) {\n        // If _weekCursor goes beyond _timestamp -> leave _slopeDelta\n        // to be 0 as there is no more slopeChanges\n        _weekCursor = _timestamp;\n      } else {\n        // If _weekCursor still behind _timestamp, then _slopeDelta\n        // should be taken into the account.\n        _slopeDelta = slopeChanges[_weekCursor];\n      }\n      // Update bias at _weekCursor\n      _lastPoint.bias =\n        _lastPoint.bias -\n        (_lastPoint.slope * SafeCastUpgradeable.toInt128(int256(_weekCursor - _lastPoint.timestamp)));\n      if (_weekCursor == _timestamp) {\n        break;\n      }\n      // Update slope and timestamp\n      _lastPoint.slope = _lastPoint.slope + _slopeDelta;\n      _lastPoint.timestamp = _weekCursor;\n    }\n\n    if (_lastPoint.bias < 0) {\n      _lastPoint.bias = 0;\n    }\n\n    return SafeCastUpgradeable.toUint256(_lastPoint.bias);\n  }\n\n  /// @notice Set breaker\n  /// @param _breaker The new value of breaker 0 if off, 1 if on\n  function setBreaker(uint256 _breaker) external onlyOwner {\n    require(_breaker == 0 || _breaker == 1, \"only 0 or 1\");\n    uint256 _previousBreaker = breaker;\n    breaker = _breaker;\n    emit LogSetBreaker(_previousBreaker, breaker);\n  }\n\n  /// @notice Withdraw all GF when lock has expired.\n  function withdraw() external nonReentrant onlyMigrationDisable {\n    LockedBalance memory _lock = locks[msg.sender];\n\n    if (breaker == 0) require(block.timestamp >= _lock.end, \"!lock expired\");\n\n    uint256 _amount = SafeCastUpgradeable.toUint256(_lock.amount);\n    if (_amount != 0) {\n      _unlock(_lock, _amount);\n\n      token.safeTransfer(msg.sender, _amount);\n    }\n\n    IRewardManager(rewardManager).claim(msg.sender);\n    emit LogWithdraw(msg.sender, _amount, block.timestamp);\n  }\n\n  /// @notice Early withdraw GF with penalty.\n  function earlyWithdraw(uint256 _amount) external nonReentrant onlyMigrationDisable {\n    LockedBalance memory _lock = locks[msg.sender];\n\n    require(_amount > 0, \"!>0\");\n    require(block.timestamp < _lock.end, \"!early\");\n    require(breaker == 0, \"breaker\");\n\n    // prevent mutated memory in _unlock() function as it will be used in fee calculation afterward\n    uint256 _prevLockAmount = SafeCastUpgradeable.toUint256(_lock.amount);\n    uint256 _prevLockEnd = _lock.end;\n    _unlock(_lock, _amount);\n\n    // ceil the week by adding 1 week first\n    uint256 remainingWeeks = (_prevLockEnd + WEEK - block.timestamp) / WEEK;\n\n    // calculate penalty\n    uint256 _penalty = (earlyWithdrawBpsPerWeek * remainingWeeks * _amount) / 10000;\n\n    // split penalty into two parts\n    uint256 _redistribute = (_penalty * redistributeBps) / 10000;\n    // accumulate GF for redistribution\n    accumRedistribute += _redistribute;\n\n    // transfer one part of the penalty to treasury\n    token.safeTransfer(treasuryAddr, _penalty - _redistribute);\n    // transfer remaining back to owner\n    token.safeTransfer(msg.sender, _amount - _penalty);\n\n    if (_prevLockAmount == _amount) {\n      // if withdraw all, claim from reward manager\n      IRewardManager(rewardManager).claim(msg.sender);\n    }\n    emit LogEarlyWithdraw(msg.sender, _amount, block.timestamp);\n  }\n\n  function redistribute() external onlyRedistributors nonReentrant {\n    uint256 _amount = accumRedistribute;\n\n    accumRedistribute = 0;\n\n    token.safeTransfer(redistributeAddr, _amount);\n\n    emit LogRedistribute(msg.sender, redistributeAddr, _amount);\n  }\n\n  function _unlock(LockedBalance memory _lock, uint256 _withdrawAmount) internal {\n    // Cast here for readability\n    uint256 _lockedAmount = SafeCastUpgradeable.toUint256(_lock.amount);\n    require(_withdrawAmount <= _lockedAmount, \"!enough\");\n\n    LockedBalance memory _prevLock = LockedBalance({ end: _lock.end, amount: _lock.amount });\n    //_lock.end should remain the same if we do partially withdraw\n    _lock.end = _lockedAmount == _withdrawAmount ? 0 : _lock.end;\n    _lock.amount = SafeCastUpgradeable.toInt128(int256(_lockedAmount - _withdrawAmount));\n    locks[msg.sender] = _lock;\n\n    uint256 _supplyBefore = supply;\n    supply = _supplyBefore - _withdrawAmount;\n\n    // _prevLock can have either block.timstamp >= _lock.end or zero end\n    // _lock has only 0 end\n    // Both can have >= 0 amount\n    _checkpoint(msg.sender, _prevLock, _lock);\n    emit LogSupply(_supplyBefore, supply);\n  }\n\n  function setEarlyWithdrawConfig(\n    uint64 _newEarlyWithdrawBpsPerWeek,\n    uint64 _newRedistributeBps,\n    address _newTreasuryAddr,\n    address _newRedistributeAddr\n  ) external onlyOwner {\n    // Maximum early withdraw fee per week bps = 100% / 52 week = 1.923%)\n    require(_newEarlyWithdrawBpsPerWeek <= 192, \"fee too high\");\n    // Maximum redistributeBps = 10000 (100%)\n    require(_newRedistributeBps <= 10000, \"!valid bps\");\n\n    uint64 _oldEarlyWithdrawBpsPerWeek = earlyWithdrawBpsPerWeek;\n    earlyWithdrawBpsPerWeek = _newEarlyWithdrawBpsPerWeek;\n\n    uint64 _oldRedistributeBps = redistributeBps;\n    redistributeBps = _newRedistributeBps;\n\n    address _oldTreasuryAddr = treasuryAddr;\n    treasuryAddr = _newTreasuryAddr;\n    address _oldRedistributeAddr = redistributeAddr;\n    redistributeAddr = _newRedistributeAddr;\n\n    emit LogSetEarlyWithdrawConfig(\n      msg.sender,\n      _oldEarlyWithdrawBpsPerWeek,\n      _newEarlyWithdrawBpsPerWeek,\n      _oldRedistributeBps,\n      _newRedistributeBps,\n      _oldTreasuryAddr,\n      _newTreasuryAddr,\n      _oldRedistributeAddr,\n      _newRedistributeAddr\n    );\n  }\n\n  function setWhitelistedCallers(address[] calldata callers, bool ok) external onlyOwner {\n    for (uint256 idx = 0; idx < callers.length; idx++) {\n      whitelistedCallers[callers[idx]] = ok;\n      emit LogSetWhitelistedCaller(_msgSender(), callers[idx], ok);\n    }\n  }\n\n  function setRewardManager(address _rewardManager) external onlyOwner {\n    rewardManager = _rewardManager;\n  }\n\n  function setWhitelistedRedistributors(address[] calldata callers, bool ok) external onlyOwner {\n    for (uint256 idx = 0; idx < callers.length; idx++) {\n      whitelistedRedistributors[callers[idx]] = ok;\n      emit LogSetWhitelistedRedistributors(_msgSender(), callers[idx], ok);\n    }\n  }\n\n  function enableMigration() external onlyOwner {\n    require(!migrationEnabled, \"Migration already enabled\");\n     migrationEnabled = true;\n  }\n\n  function setGFMigrator(address _xGFMigrator) external onlyOwner {\n    require(_xGFMigrator != address(0), \"can not set to zero address\");\n    xGFMigrator = _xGFMigrator;\n  }\n\n  function transferToMigrator() external onlyMigrationEnabled {\n    require(msg.sender == xGFMigrator, \"not from migrator\");\n\n    uint256 migrateBalance = token.myBalance() - accumRedistribute;\n    \n    token.safeTransfer(xGFMigrator, migrateBalance);\n    emit LogMigrated(xGFMigrator, migrateBalance);\n  }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    function __Ownable_init() internal onlyInitializing {\n        __Context_init_unchained();\n        __Ownable_init_unchained();\n    }\n\n    function __Ownable_init_unchained() internal onlyInitializing {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n        _;\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n    uint256[49] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the\n * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() initializer {}\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Indicates that the contract has been initialized.\n     */\n    bool private _initialized;\n\n    /**\n     * @dev Indicates that the contract is in the process of being initialized.\n     */\n    bool private _initializing;\n\n    /**\n     * @dev Modifier to protect an initializer function from being invoked twice.\n     */\n    modifier initializer() {\n        // If the contract is initializing we ignore whether _initialized is set in order to support multiple\n        // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the\n        // contract may have been reentered.\n        require(_initializing ? _isConstructor() : !_initialized, \"Initializable: contract is already initialized\");\n\n        bool isTopLevelCall = !_initializing;\n        if (isTopLevelCall) {\n            _initializing = true;\n            _initialized = true;\n        }\n\n        _;\n\n        if (isTopLevelCall) {\n            _initializing = false;\n        }\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} modifier, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        require(_initializing, \"Initializable: contract is not initializing\");\n        _;\n    }\n\n    function _isConstructor() private view returns (bool) {\n        return !AddressUpgradeable.isContract(address(this));\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    function __ReentrancyGuard_init() internal onlyInitializing {\n        __ReentrancyGuard_init_unchained();\n    }\n\n    function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        // On the first call to nonReentrant, _notEntered will be true\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n\n        _;\n\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n    uint256[49] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCastUpgradeable {\n    /**\n     * @dev Returns the downcasted uint224 from uint256, reverting on\n     * overflow (when the input is greater than largest uint224).\n     *\n     * Counterpart to Solidity's `uint224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toUint224(uint256 value) internal pure returns (uint224) {\n        require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n        return uint224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint128 from uint256, reverting on\n     * overflow (when the input is greater than largest uint128).\n     *\n     * Counterpart to Solidity's `uint128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint96 from uint256, reverting on\n     * overflow (when the input is greater than largest uint96).\n     *\n     * Counterpart to Solidity's `uint96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toUint96(uint256 value) internal pure returns (uint96) {\n        require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n        return uint96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint64 from uint256, reverting on\n     * overflow (when the input is greater than largest uint64).\n     *\n     * Counterpart to Solidity's `uint64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint32 from uint256, reverting on\n     * overflow (when the input is greater than largest uint32).\n     *\n     * Counterpart to Solidity's `uint32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint16 from uint256, reverting on\n     * overflow (when the input is greater than largest uint16).\n     *\n     * Counterpart to Solidity's `uint16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n        return uint16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint8 from uint256, reverting on\n     * overflow (when the input is greater than largest uint8).\n     *\n     * Counterpart to Solidity's `uint8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits.\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        require(value >= 0, \"SafeCast: value must be positive\");\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt128(int256 value) internal pure returns (int128) {\n        require(value >= type(int128).min && value <= type(int128).max, \"SafeCast: value doesn't fit in 128 bits\");\n        return int128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt64(int256 value) internal pure returns (int64) {\n        require(value >= type(int64).min && value <= type(int64).max, \"SafeCast: value doesn't fit in 64 bits\");\n        return int64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt32(int256 value) internal pure returns (int32) {\n        require(value >= type(int32).min && value <= type(int32).max, \"SafeCast: value doesn't fit in 32 bits\");\n        return int32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt16(int256 value) internal pure returns (int16) {\n        require(value >= type(int16).min && value <= type(int16).max, \"SafeCast: value doesn't fit in 16 bits\");\n        return int16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits.\n     *\n     * _Available since v3.1._\n     */\n    function toInt8(int256 value) internal pure returns (int8) {\n        require(value >= type(int8).min && value <= type(int8).max, \"SafeCast: value doesn't fit in 8 bits\");\n        return int8(value);\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n        return int256(value);\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize, which returns 0 for contracts in\n        // construction, since the code is only stored at the end of the\n        // constructor execution.\n\n        uint256 size;\n        assembly {\n            size := extcodesize(account)\n        }\n        return size > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCall(target, data, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        require(isContract(target), \"Address: call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        require(isContract(target), \"Address: static call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            // Look for revert reason and bubble it up if present\n            if (returndata.length > 0) {\n                // The easiest way to bubble the revert reason is using memory via assembly\n\n                assembly {\n                    let returndata_size := mload(returndata)\n                    revert(add(32, returndata), returndata_size)\n                }\n            } else {\n                revert(errorMessage);\n            }\n        }\n    }\n}\n"
      },
      "contracts/8.10/interfaces/IRewardManager.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.10;\n\ninterface IRewardManager {\n  function xGF() external view returns (address);\n\n  function rewardToken() external returns (address);\n\n  function feed(uint256 _amount) external returns (bool);\n\n  function claim(address _for) external returns (uint256);\n\n  function pendingRewardsOf(address _user) external returns (uint256);\n\n  function lastTokenBalance() external view returns (uint256);\n\n  function checkpointToken() external view returns (uint256);\n}\n"
      },
      "contracts/8.10/interfaces/IStakingERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.10;\n\nimport \"@openzeppelin/contracts/interfaces/IERC20.sol\";\n\ninterface IStakingERC20 is IERC20 {\n  /// @dev Return token's name\n  function name() external returns (string memory);\n\n  /// @dev Return token's symbol\n  function symbol() external returns (string memory);\n\n  /// @dev Return token's decimals\n  function decimals() external returns (uint8);\n}\n"
      },
      "contracts/8.10/SafeToken.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.10;\n\ninterface ERC20Interface {\n  function balanceOf(address user) external view returns (uint256);\n}\n\nlibrary SafeToken {\n  function myBalance(address token) internal view returns (uint256) {\n    return ERC20Interface(token).balanceOf(address(this));\n  }\n\n  function safeTransfer(address token, address to, uint256 value) internal {\n    // bytes4(keccak256(bytes('transfer(address,uint256)')));\n    // solhint-disable-next-line avoid-low-level-calls\n    require(token.code.length > 0, \"!contract\");\n    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));\n    require(success && (data.length == 0 || abi.decode(data, (bool))), \"!safeTransfer\");\n  }\n\n  function safeTransferFrom(address token, address from, address to, uint256 value) internal {\n    // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));\n    // solhint-disable-next-line avoid-low-level-calls\n    require(token.code.length > 0, \"!contract\");\n    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));\n    require(success && (data.length == 0 || abi.decode(data, (bool))), \"!safeTransferFrom\");\n  }\n\n  function safeApprove(address token, address to, uint256 value) internal {\n    // bytes4(keccak256(bytes('approve(address,uint256)')));\n    require(token.code.length > 0, \"!contract\");\n    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));\n    require(success && (data.length == 0 || abi.decode(data, (bool))), \"!safeApprove\");\n  }\n\n  function safeTransferETH(address to, uint256 value) internal {\n    // solhint-disable-next-line no-call-value\n    (bool success, ) = to.call{ value: value }(new bytes(0));\n    require(success, \"!safeTransferETH\");\n  }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n    function __Context_init() internal onlyInitializing {\n        __Context_init_unchained();\n    }\n\n    function __Context_init_unchained() internal onlyInitializing {\n    }\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n    uint256[50] private __gap;\n}\n"
      },
      "@openzeppelin/contracts/interfaces/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC20/IERC20.sol\";\n"
      },
      "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `recipient`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address recipient, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `sender` to `recipient` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address sender,\n        address recipient,\n        uint256 amount\n    ) external returns (bool);\n\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "metadata": {
        "useLiteralContent": true
      },
      "libraries": {}
    }
  }}