{
    "Function": "slitherConstructorConstantVariables",
    "File": "src/UniStaker.sol",
    "Parent Contracts": [
        "lib/openzeppelin-contracts/contracts/utils/Nonces.sol",
        "lib/openzeppelin-contracts/contracts/utils/cryptography/EIP712.sol",
        "lib/openzeppelin-contracts/contracts/interfaces/IERC5267.sol",
        "lib/openzeppelin-contracts/contracts/utils/Multicall.sol",
        "src/interfaces/INotifiableRewardReceiver.sol"
    ],
    "High-Level Calls": [],
    "Internal Calls": [
        "keccak256(bytes)",
        "keccak256(bytes)",
        "keccak256(bytes)",
        "keccak256(bytes)",
        "keccak256(bytes)",
        "keccak256(bytes)"
    ],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "contract UniStaker is INotifiableRewardReceiver, Multicall, EIP712, Nonces {\n  type DepositIdentifier is uint256;\n\n  /// @notice Emitted when stake is deposited by a depositor, either to a new deposit or one that\n  /// already exists.\n  event StakeDeposited(\n    address owner, DepositIdentifier indexed depositId, uint256 amount, uint256 depositBalance\n  );\n\n  /// @notice Emitted when a depositor withdraws some portion of stake from a given deposit.\n  event StakeWithdrawn(DepositIdentifier indexed depositId, uint256 amount, uint256 depositBalance);\n\n  /// @notice Emitted when a deposit's delegatee is changed.\n  event DelegateeAltered(\n    DepositIdentifier indexed depositId, address oldDelegatee, address newDelegatee\n  );\n\n  /// @notice Emitted when a deposit's beneficiary is changed.\n  event BeneficiaryAltered(\n    DepositIdentifier indexed depositId,\n    address indexed oldBeneficiary,\n    address indexed newBeneficiary\n  );\n\n  /// @notice Emitted when a beneficiary claims their earned reward.\n  event RewardClaimed(address indexed beneficiary, uint256 amount);\n\n  /// @notice Emitted when this contract is notified of a new reward.\n  event RewardNotified(uint256 amount, address notifier);\n\n  /// @notice Emitted when the admin address is set.\n  event AdminSet(address indexed oldAdmin, address indexed newAdmin);\n\n  /// @notice Emitted when a reward notifier address is enabled or disabled.\n  event RewardNotifierSet(address indexed account, bool isEnabled);\n\n  /// @notice Emitted when a surrogate contract is deployed.\n  event SurrogateDeployed(address indexed delegatee, address indexed surrogate);\n\n  /// @notice Thrown when an account attempts a call for which it lacks appropriate permission.\n  /// @param reason Human readable code explaining why the call is unauthorized.\n  /// @param caller The address that attempted the unauthorized call.\n  error UniStaker__Unauthorized(bytes32 reason, address caller);\n\n  /// @notice Thrown if the new rate after a reward notification would be zero.\n  error UniStaker__InvalidRewardRate();\n\n  /// @notice Thrown if the following invariant is broken after a new reward: the contract should\n  /// always have a reward balance sufficient to distribute at the reward rate across the reward\n  /// duration.\n  error UniStaker__InsufficientRewardBalance();\n\n  /// @notice Thrown if a caller attempts to specify address zero for certain designated addresses.\n  error UniStaker__InvalidAddress();\n\n  /// @notice Thrown if a caller supplies an invalid signature to a method that requires one.\n  error UniStaker__InvalidSignature();\n\n  /// @notice Metadata associated with a discrete staking deposit.\n  /// @param balance The deposit's staked balance.\n  /// @param owner The owner of this deposit.\n  /// @param delegatee The governance delegate who receives the voting weight for this deposit.\n  /// @param beneficiary The address that accrues staking rewards earned by this deposit.\n  struct Deposit {\n    uint256 balance;\n    address owner;\n    address delegatee;\n    address beneficiary;\n  }\n\n  /// @notice Type hash used when encoding data for `stakeOnBehalf` calls.\n  bytes32 public constant STAKE_TYPEHASH = keccak256(\n    \"Stake(uint256 amount,address delegatee,address beneficiary,address depositor,uint256 nonce)\"\n  );\n  /// @notice Type hash used when encoding data for `stakeMoreOnBehalf` calls.\n  bytes32 public constant STAKE_MORE_TYPEHASH =\n    keccak256(\"StakeMore(uint256 depositId,uint256 amount,address depositor,uint256 nonce)\");\n  /// @notice Type hash used when encoding data for `alterDelegateeOnBehalf` calls.\n  bytes32 public constant ALTER_DELEGATEE_TYPEHASH = keccak256(\n    \"AlterDelegatee(uint256 depositId,address newDelegatee,address depositor,uint256 nonce)\"\n  );\n  /// @notice Type hash used when encoding data for `alterBeneficiaryOnBehalf` calls.\n  bytes32 public constant ALTER_BENEFICIARY_TYPEHASH = keccak256(\n    \"AlterBeneficiary(uint256 depositId,address newBeneficiary,address depositor,uint256 nonce)\"\n  );\n  /// @notice Type hash used when encoding data for `withdrawOnBehalf` calls.\n  bytes32 public constant WITHDRAW_TYPEHASH =\n    keccak256(\"Withdraw(uint256 depositId,uint256 amount,address depositor,uint256 nonce)\");\n  /// @notice Type hash used when encoding data for `claimRewardOnBehalf` calls.\n  bytes32 public constant CLAIM_REWARD_TYPEHASH =\n    keccak256(\"ClaimReward(address beneficiary,uint256 nonce)\");\n\n  /// @notice ERC20 token in which rewards are denominated and distributed.\n  IERC20 public immutable REWARD_TOKEN;\n\n  /// @notice Delegable governance token which users stake to earn rewards.\n  IERC20Delegates public immutable STAKE_TOKEN;\n\n  /// @notice Length of time over which rewards sent to this contract are distributed to stakers.\n  uint256 public constant REWARD_DURATION = 30 days;\n\n  /// @notice Scale factor used in reward calculation math to reduce rounding errors caused by\n  /// truncation during division.\n  uint256 public constant SCALE_FACTOR = 1e36;\n\n  /// @dev Unique identifier that will be used for the next deposit.\n  DepositIdentifier private nextDepositId;\n\n  /// @notice Permissioned actor that can enable/disable `rewardNotifier` addresses.\n  address public admin;\n\n  /// @notice Global amount currently staked across all deposits.\n  uint256 public totalStaked;\n\n  /// @notice Tracks the total staked by a depositor across all unique deposits.\n  mapping(address depositor => uint256 amount) public depositorTotalStaked;\n\n  /// @notice Tracks the total stake actively earning rewards for a given beneficiary account.\n  mapping(address beneficiary => uint256 amount) public earningPower;\n\n  /// @notice Stores the metadata associated with a given deposit.\n  mapping(DepositIdentifier depositId => Deposit deposit) public deposits;\n\n  /// @notice Maps the account of each governance delegate with the surrogate contract which holds\n  /// the staked tokens from deposits which assign voting weight to said delegate.\n  mapping(address delegatee => DelegationSurrogate surrogate) public surrogates;\n\n  /// @notice Time at which rewards distribution will complete if there are no new rewards.\n  uint256 public rewardEndTime;\n\n  /// @notice Last time at which the global rewards accumulator was updated.\n  uint256 public lastCheckpointTime;\n\n  /// @notice Global rate at which rewards are currently being distributed to stakers,\n  /// denominated in scaled reward tokens per second, using the SCALE_FACTOR.\n  uint256 public scaledRewardRate;\n\n  /// @notice Checkpoint value of the global reward per token accumulator.\n  uint256 public rewardPerTokenAccumulatedCheckpoint;\n\n  /// @notice Checkpoint of the reward per token accumulator on a per account basis. It represents\n  /// the value of the global accumulator at the last time a given beneficiary's rewards were\n  /// calculated and stored. The difference between the global value and this value can be\n  /// used to calculate the interim rewards earned by given account.\n  mapping(address account => uint256) public beneficiaryRewardPerTokenCheckpoint;\n\n  /// @notice Checkpoint of the unclaimed rewards earned by a given beneficiary. This value is\n  /// stored any time an action is taken that specifically impacts the rate at which rewards are\n  /// earned by a given beneficiary account. Total unclaimed rewards for an account are thus this\n  /// value plus all rewards earned after this checkpoint was taken. This value is reset to zero\n  /// when a beneficiary account claims their earned rewards.\n  mapping(address account => uint256 amount) public unclaimedRewardCheckpoint;\n\n  /// @notice Maps addresses to whether they are authorized to call `notifyRewardAmount`.\n  mapping(address rewardNotifier => bool) public isRewardNotifier;\n\n  /// @param _rewardToken ERC20 token in which rewards will be denominated.\n  /// @param _stakeToken Delegable governance token which users will stake to earn rewards.\n  /// @param _admin Address which will have permission to manage rewardNotifiers.\n  constructor(IERC20 _rewardToken, IERC20Delegates _stakeToken, address _admin)\n    EIP712(\"UniStaker\", \"1\")\n  {\n    REWARD_TOKEN = _rewardToken;\n    STAKE_TOKEN = _stakeToken;\n    _setAdmin(_admin);\n  }\n\n  /// @notice Set the admin address.\n  /// @param _newAdmin Address of the new admin.\n  /// @dev Caller must be the current admin.\n  function setAdmin(address _newAdmin) external {\n    _revertIfNotAdmin();\n    _setAdmin(_newAdmin);\n  }\n\n  /// @notice Enables or disables a reward notifier address.\n  /// @param _rewardNotifier Address of the reward notifier.\n  /// @param _isEnabled `true` to enable the `_rewardNotifier`, or `false` to disable.\n  /// @dev Caller must be the current admin.\n  function setRewardNotifier(address _rewardNotifier, bool _isEnabled) external {\n    _revertIfNotAdmin();\n    isRewardNotifier[_rewardNotifier] = _isEnabled;\n    emit RewardNotifierSet(_rewardNotifier, _isEnabled);\n  }\n\n  /// @notice Timestamp representing the last time at which rewards have been distributed, which is\n  /// either the current timestamp (because rewards are still actively being streamed) or the time\n  /// at which the reward duration ended (because all rewards to date have already been streamed).\n  /// @return Timestamp representing the last time at which rewards have been distributed.\n  function lastTimeRewardDistributed() public view returns (uint256) {\n    if (rewardEndTime <= block.timestamp) return rewardEndTime;\n    else return block.timestamp;\n  }\n\n  /// @notice Live value of the global reward per token accumulator. It is the sum of the last\n  /// checkpoint value with the live calculation of the value that has accumulated in the interim.\n  /// This number should monotonically increase over time as more rewards are distributed.\n  /// @return Live value of the global reward per token accumulator.\n  function rewardPerTokenAccumulated() public view returns (uint256) {\n    if (totalStaked == 0) return rewardPerTokenAccumulatedCheckpoint;\n\n    return rewardPerTokenAccumulatedCheckpoint\n      + (scaledRewardRate * (lastTimeRewardDistributed() - lastCheckpointTime)) / totalStaked;\n  }\n\n  /// @notice Live value of the unclaimed rewards earned by a given beneficiary account. It is the\n  /// sum of the last checkpoint value of their unclaimed rewards with the live calculation of the\n  /// rewards that have accumulated for this account in the interim. This value can only increase,\n  /// until it is reset to zero once the beneficiary account claims their unearned rewards.\n  /// @return Live value of the unclaimed rewards earned by a given beneficiary account.\n  function unclaimedReward(address _beneficiary) public view returns (uint256) {\n    return unclaimedRewardCheckpoint[_beneficiary]\n      + (\n        earningPower[_beneficiary]\n          * (rewardPerTokenAccumulated() - beneficiaryRewardPerTokenCheckpoint[_beneficiary])\n      ) / SCALE_FACTOR;\n  }\n\n  /// @notice Stake tokens to a new deposit. The caller must pre-approve the staking contract to\n  /// spend at least the would-be staked amount of the token.\n  /// @param _amount The amount of the staking token to stake.\n  /// @param _delegatee The address to assign the governance voting weight of the staked tokens.\n  /// @return _depositId The unique identifier for this deposit.\n  /// @dev The delegatee may not be the zero address. The deposit will be owned by the message\n  /// sender, and the beneficiary will also be the message sender.\n  function stake(uint256 _amount, address _delegatee)\n    external\n    returns (DepositIdentifier _depositId)\n  {\n    _depositId = _stake(msg.sender, _amount, _delegatee, msg.sender);\n  }\n\n  /// @notice Method to stake tokens to a new deposit. The caller must pre-approve the staking\n  /// contract to spend at least the would-be staked amount of the token.\n  /// @param _amount Quantity of the staking token to stake.\n  /// @param _delegatee Address to assign the governance voting weight of the staked tokens.\n  /// @param _beneficiary Address that will accrue rewards for this stake.\n  /// @return _depositId Unique identifier for this deposit.\n  /// @dev Neither the delegatee nor the beneficiary may be the zero address. The deposit will be\n  /// owned by the message sender.\n  function stake(uint256 _amount, address _delegatee, address _beneficiary)\n    external\n    returns (DepositIdentifier _depositId)\n  {\n    _depositId = _stake(msg.sender, _amount, _delegatee, _beneficiary);\n  }\n\n  /// @notice Method to stake tokens to a new deposit. The caller must approve the staking\n  /// contract to spend at least the would-be staked amount of the token via a signature which is\n  /// is also provided, and is passed to the token contract's permit method before the staking\n  /// operation occurs.\n  /// @param _amount Quantity of the staking token to stake.\n  /// @param _delegatee Address to assign the governance voting weight of the staked tokens.\n  /// @param _beneficiary Address that will accrue rewards for this stake.\n  /// @param _deadline The timestamp at which the permit signature should expire.\n  /// @param _v ECDSA signature component: Parity of the `y` coordinate of point `R`\n  /// @param _r ECDSA signature component: x-coordinate of `R`\n  /// @param _s ECDSA signature component: `s` value of the signature\n  /// @return _depositId Unique identifier for this deposit.\n  /// @dev Neither the delegatee nor the beneficiary may be the zero address. The deposit will be\n  /// owned by the message sender.\n  function permitAndStake(\n    uint256 _amount,\n    address _delegatee,\n    address _beneficiary,\n    uint256 _deadline,\n    uint8 _v,\n    bytes32 _r,\n    bytes32 _s\n  ) external returns (DepositIdentifier _depositId) {\n    STAKE_TOKEN.permit(msg.sender, address(this), _amount, _deadline, _v, _r, _s);\n    _depositId = _stake(msg.sender, _amount, _delegatee, _beneficiary);\n  }\n\n  /// @notice Stake tokens to a new deposit on behalf of a user, using a signature to validate the\n  /// user's intent. The caller must pre-approve the staking contract to spend at least the\n  /// would-be staked amount of the token.\n  /// @param _amount Quantity of the staking token to stake.\n  /// @param _delegatee Address to assign the governance voting weight of the staked tokens.\n  /// @param _beneficiary Address that will accrue rewards for this stake.\n  /// @param _depositor Address of the user on whose behalf this stake is being made.\n  /// @param _signature Signature of the user authorizing this stake.\n  /// @return _depositId Unique identifier for this deposit.\n  /// @dev Neither the delegatee nor the beneficiary may be the zero address.\n  function stakeOnBehalf(\n    uint256 _amount,\n    address _delegatee,\n    address _beneficiary,\n    address _depositor,\n    bytes memory _signature\n  ) external returns (DepositIdentifier _depositId) {\n    _revertIfSignatureIsNotValidNow(\n      _depositor,\n      _hashTypedDataV4(\n        keccak256(\n          abi.encode(\n            STAKE_TYPEHASH, _amount, _delegatee, _beneficiary, _depositor, _useNonce(_depositor)\n          )\n        )\n      ),\n      _signature\n    );\n    _depositId = _stake(_depositor, _amount, _delegatee, _beneficiary);\n  }\n\n  /// @notice Add more staking tokens to an existing deposit. A staker should call this method when\n  /// they have an existing deposit, and wish to stake more while retaining the same delegatee and\n  /// beneficiary.\n  /// @param _depositId Unique identifier of the deposit to which stake will be added.\n  /// @param _amount Quantity of stake to be added.\n  /// @dev The message sender must be the owner of the deposit.\n  function stakeMore(DepositIdentifier _depositId, uint256 _amount) external {\n    Deposit storage deposit = deposits[_depositId];\n    _revertIfNotDepositOwner(deposit, msg.sender);\n    _stakeMore(deposit, _depositId, _amount);\n  }\n\n  /// @notice Add more staking tokens to an existing deposit. A staker should call this method when\n  /// they have an existing deposit, and wish to stake more while retaining the same delegatee and\n  /// beneficiary. The caller must approve the staking contract to spend at least the would-be\n  /// staked amount of the token via a signature which is is also provided, and is passed to the\n  /// token contract's permit method before the staking operation occurs.\n  /// @param _depositId Unique identifier of the deposit to which stake will be added.\n  /// @param _amount Quantity of stake to be added.\n  /// @param _deadline The timestamp at which the permit signature should expire.\n  /// @param _v ECDSA signature component: Parity of the `y` coordinate of point `R`\n  /// @param _r ECDSA signature component: x-coordinate of `R`\n  /// @param _s ECDSA signature component: `s` value of the signature\n  /// @dev The message sender must be the owner of the deposit.\n  function permitAndStakeMore(\n    DepositIdentifier _depositId,\n    uint256 _amount,\n    uint256 _deadline,\n    uint8 _v,\n    bytes32 _r,\n    bytes32 _s\n  ) external {\n    Deposit storage deposit = deposits[_depositId];\n    _revertIfNotDepositOwner(deposit, msg.sender);\n\n    STAKE_TOKEN.permit(msg.sender, address(this), _amount, _deadline, _v, _r, _s);\n    _stakeMore(deposit, _depositId, _amount);\n  }\n\n  /// @notice Add more staking tokens to an existing deposit on behalf of a user, using a signature\n  /// to validate the user's intent. A staker should call this method when they have an existing\n  /// deposit, and wish to stake more while retaining the same delegatee and beneficiary.\n  /// @param _depositId Unique identifier of the deposit to which stake will be added.\n  /// @param _amount Quantity of stake to be added.\n  /// @param _depositor Address of the user on whose behalf this stake is being made.\n  /// @param _signature Signature of the user authorizing this stake.\n  function stakeMoreOnBehalf(\n    DepositIdentifier _depositId,\n    uint256 _amount,\n    address _depositor,\n    bytes memory _signature\n  ) external {\n    Deposit storage deposit = deposits[_depositId];\n    _revertIfNotDepositOwner(deposit, _depositor);\n\n    _revertIfSignatureIsNotValidNow(\n      _depositor,\n      _hashTypedDataV4(\n        keccak256(\n          abi.encode(STAKE_MORE_TYPEHASH, _depositId, _amount, _depositor, _useNonce(_depositor))\n        )\n      ),\n      _signature\n    );\n\n    _stakeMore(deposit, _depositId, _amount);\n  }\n\n  /// @notice For an existing deposit, change the address to which governance voting power is\n  /// assigned.\n  /// @param _depositId Unique identifier of the deposit which will have its delegatee altered.\n  /// @param _newDelegatee Address of the new governance delegate.\n  /// @dev The new delegatee may not be the zero address. The message sender must be the owner of\n  /// the deposit.\n  function alterDelegatee(DepositIdentifier _depositId, address _newDelegatee) external {\n    Deposit storage deposit = deposits[_depositId];\n    _revertIfNotDepositOwner(deposit, msg.sender);\n    _alterDelegatee(deposit, _depositId, _newDelegatee);\n  }\n\n  /// @notice For an existing deposit, change the address to which governance voting power is\n  /// assigned on behalf of a user, using a signature to validate the user's intent.\n  /// @param _depositId Unique identifier of the deposit which will have its delegatee altered.\n  /// @param _newDelegatee Address of the new governance delegate.\n  /// @param _depositor Address of the user on whose behalf this stake is being made.\n  /// @param _signature Signature of the user authorizing this stake.\n  /// @dev The new delegatee may not be the zero address.\n  function alterDelegateeOnBehalf(\n    DepositIdentifier _depositId,\n    address _newDelegatee,\n    address _depositor,\n    bytes memory _signature\n  ) external {\n    Deposit storage deposit = deposits[_depositId];\n    _revertIfNotDepositOwner(deposit, _depositor);\n\n    _revertIfSignatureIsNotValidNow(\n      _depositor,\n      _hashTypedDataV4(\n        keccak256(\n          abi.encode(\n            ALTER_DELEGATEE_TYPEHASH, _depositId, _newDelegatee, _depositor, _useNonce(_depositor)\n          )\n        )\n      ),\n      _signature\n    );\n\n    _alterDelegatee(deposit, _depositId, _newDelegatee);\n  }\n\n  /// @notice For an existing deposit, change the beneficiary to which staking rewards are\n  /// accruing.\n  /// @param _depositId Unique identifier of the deposit which will have its beneficiary altered.\n  /// @param _newBeneficiary Address of the new rewards beneficiary.\n  /// @dev The new beneficiary may not be the zero address. The message sender must be the owner of\n  /// the deposit.\n  function alterBeneficiary(DepositIdentifier _depositId, address _newBeneficiary) external {\n    Deposit storage deposit = deposits[_depositId];\n    _revertIfNotDepositOwner(deposit, msg.sender);\n    _alterBeneficiary(deposit, _depositId, _newBeneficiary);\n  }\n\n  /// @notice For an existing deposit, change the beneficiary to which staking rewards are\n  /// accruing on behalf of a user, using a signature to validate the user's intent.\n  /// @param _depositId Unique identifier of the deposit which will have its beneficiary altered.\n  /// @param _newBeneficiary Address of the new rewards beneficiary.\n  /// @param _depositor Address of the user on whose behalf this stake is being made.\n  /// @param _signature Signature of the user authorizing this stake.\n  /// @dev The new beneficiary may not be the zero address.\n  function alterBeneficiaryOnBehalf(\n    DepositIdentifier _depositId,\n    address _newBeneficiary,\n    address _depositor,\n    bytes memory _signature\n  ) external {\n    Deposit storage deposit = deposits[_depositId];\n    _revertIfNotDepositOwner(deposit, _depositor);\n\n    _revertIfSignatureIsNotValidNow(\n      _depositor,\n      _hashTypedDataV4(\n        keccak256(\n          abi.encode(\n            ALTER_BENEFICIARY_TYPEHASH,\n            _depositId,\n            _newBeneficiary,\n            _depositor,\n            _useNonce(_depositor)\n          )\n        )\n      ),\n      _signature\n    );\n\n    _alterBeneficiary(deposit, _depositId, _newBeneficiary);\n  }\n\n  /// @notice Withdraw staked tokens from an existing deposit.\n  /// @param _depositId Unique identifier of the deposit from which stake will be withdrawn.\n  /// @param _amount Quantity of staked token to withdraw.\n  /// @dev The message sender must be the owner of the deposit. Stake is withdrawn to the message\n  /// sender's account.\n  function withdraw(DepositIdentifier _depositId, uint256 _amount) external {\n    Deposit storage deposit = deposits[_depositId];\n    _revertIfNotDepositOwner(deposit, msg.sender);\n    _withdraw(deposit, _depositId, _amount);\n  }\n\n  /// @notice Withdraw staked tokens from an existing deposit on behalf of a user, using a\n  /// signature to validate the user's intent.\n  /// @param _depositId Unique identifier of the deposit from which stake will be withdrawn.\n  /// @param _amount Quantity of staked token to withdraw.\n  /// @param _depositor Address of the user on whose behalf this stake is being made.\n  /// @param _signature Signature of the user authorizing this stake.\n  /// @dev Stake is withdrawn to the deposit owner's account.\n  function withdrawOnBehalf(\n    DepositIdentifier _depositId,\n    uint256 _amount,\n    address _depositor,\n    bytes memory _signature\n  ) external {\n    Deposit storage deposit = deposits[_depositId];\n    _revertIfNotDepositOwner(deposit, _depositor);\n\n    _revertIfSignatureIsNotValidNow(\n      _depositor,\n      _hashTypedDataV4(\n        keccak256(\n          abi.encode(WITHDRAW_TYPEHASH, _depositId, _amount, _depositor, _useNonce(_depositor))\n        )\n      ),\n      _signature\n    );\n\n    _withdraw(deposit, _depositId, _amount);\n  }\n\n  /// @notice Claim reward tokens the message sender has earned as a stake beneficiary. Tokens are\n  /// sent to the message sender.\n  function claimReward() external {\n    _claimReward(msg.sender);\n  }\n\n  /// @notice Claim earned reward tokens for a beneficiary, using a signature to validate the\n  /// beneficiary's intent. Tokens are sent to the beneficiary.\n  /// @param _beneficiary Address of the beneficiary who will receive the reward.\n  /// @param _signature Signature of the beneficiary authorizing this reward claim.\n  function claimRewardOnBehalf(address _beneficiary, bytes memory _signature) external {\n    _revertIfSignatureIsNotValidNow(\n      _beneficiary,\n      _hashTypedDataV4(\n        keccak256(abi.encode(CLAIM_REWARD_TYPEHASH, _beneficiary, _useNonce(_beneficiary)))\n      ),\n      _signature\n    );\n    _claimReward(_beneficiary);\n  }\n\n  /// @notice Called by an authorized rewards notifier to alert the staking contract that a new\n  /// reward has been transferred to it. It is assumed that the reward has already been\n  /// transferred to this staking contract before the rewards notifier calls this method.\n  /// @param _amount Quantity of reward tokens the staking contract is being notified of.\n  /// @dev It is critical that only well behaved contracts are approved by the admin to call this\n  /// method, for two reasons.\n  ///\n  /// 1. A misbehaving contract could grief stakers by frequently notifying this contract of tiny\n  ///    rewards, thereby continuously stretching out the time duration over which real rewards are\n  ///    distributed. It is required that reward notifiers supply reasonable rewards at reasonable\n  ///    intervals.\n  //  2. A misbehaving contract could falsely notify this contract of rewards that were not actually\n  ///    distributed, creating a shortfall for those claiming their rewards after others. It is\n  ///    required that a notifier contract always transfers the `_amount` to this contract before\n  ///    calling this method.\n  function notifyRewardAmount(uint256 _amount) external {\n    if (!isRewardNotifier[msg.sender]) revert UniStaker__Unauthorized(\"not notifier\", msg.sender);\n\n    // We checkpoint the accumulator without updating the timestamp at which it was updated, because\n    // that second operation will be done after updating the reward rate.\n    rewardPerTokenAccumulatedCheckpoint = rewardPerTokenAccumulated();\n\n    if (block.timestamp >= rewardEndTime) {\n      scaledRewardRate = (_amount * SCALE_FACTOR) / REWARD_DURATION;\n    } else {\n      uint256 _remainingReward = scaledRewardRate * (rewardEndTime - block.timestamp);\n      scaledRewardRate = (_remainingReward + _amount * SCALE_FACTOR) / REWARD_DURATION;\n    }\n\n    rewardEndTime = block.timestamp + REWARD_DURATION;\n    lastCheckpointTime = block.timestamp;\n\n    if ((scaledRewardRate / SCALE_FACTOR) == 0) revert UniStaker__InvalidRewardRate();\n\n    // This check cannot _guarantee_ sufficient rewards have been transferred to the contract,\n    // because it cannot isolate the unclaimed rewards owed to stakers left in the balance. While\n    // this check is useful for preventing degenerate cases, it is not sufficient. Therefore, it is\n    // critical that only safe reward notifier contracts are approved to call this method by the\n    // admin.\n    if (\n      (scaledRewardRate * REWARD_DURATION) > (REWARD_TOKEN.balanceOf(address(this)) * SCALE_FACTOR)\n    ) revert UniStaker__InsufficientRewardBalance();\n\n    emit RewardNotified(_amount, msg.sender);\n  }\n\n  /// @notice Internal method which finds the existing surrogate contract\u2014or deploys a new one if\n  /// none exists\u2014for a given delegatee.\n  /// @param _delegatee Account for which a surrogate is sought.\n  /// @return _surrogate The address of the surrogate contract for the delegatee.\n  function _fetchOrDeploySurrogate(address _delegatee)\n    internal\n    returns (DelegationSurrogate _surrogate)\n  {\n    _surrogate = surrogates[_delegatee];\n\n    if (address(_surrogate) == address(0)) {\n      _surrogate = new DelegationSurrogate(STAKE_TOKEN, _delegatee);\n      surrogates[_delegatee] = _surrogate;\n      emit SurrogateDeployed(_delegatee, address(_surrogate));\n    }\n  }\n\n  /// @notice Internal convenience method which calls the `transferFrom` method on the stake token\n  /// contract and reverts on failure.\n  /// @param _from Source account from which stake token is to be transferred.\n  /// @param _to Destination account of the stake token which is to be transferred.\n  /// @param _value Quantity of stake token which is to be transferred.\n  function _stakeTokenSafeTransferFrom(address _from, address _to, uint256 _value) internal {\n    SafeERC20.safeTransferFrom(IERC20(address(STAKE_TOKEN)), _from, _to, _value);\n  }\n\n  /// @notice Internal method which generates and returns a unique, previously unused deposit\n  /// identifier.\n  /// @return _depositId Previously unused deposit identifier.\n  function _useDepositId() internal returns (DepositIdentifier _depositId) {\n    _depositId = nextDepositId;\n    nextDepositId = DepositIdentifier.wrap(DepositIdentifier.unwrap(_depositId) + 1);\n  }\n\n  /// @notice Internal convenience methods which performs the staking operations.\n  /// @dev This method must only be called after proper authorization has been completed.\n  /// @dev See public stake methods for additional documentation.\n  function _stake(address _depositor, uint256 _amount, address _delegatee, address _beneficiary)\n    internal\n    returns (DepositIdentifier _depositId)\n  {\n    _revertIfAddressZero(_delegatee);\n    _revertIfAddressZero(_beneficiary);\n\n    _checkpointGlobalReward();\n    _checkpointReward(_beneficiary);\n\n    DelegationSurrogate _surrogate = _fetchOrDeploySurrogate(_delegatee);\n    _depositId = _useDepositId();\n\n    totalStaked += _amount;\n    depositorTotalStaked[_depositor] += _amount;\n    earningPower[_beneficiary] += _amount;\n    deposits[_depositId] = Deposit({\n      balance: _amount,\n      owner: _depositor,\n      delegatee: _delegatee,\n      beneficiary: _beneficiary\n    });\n    _stakeTokenSafeTransferFrom(_depositor, address(_surrogate), _amount);\n    emit StakeDeposited(_depositor, _depositId, _amount, _amount);\n    emit BeneficiaryAltered(_depositId, address(0), _beneficiary);\n    emit DelegateeAltered(_depositId, address(0), _delegatee);\n  }\n\n  /// @notice Internal convenience method which adds more stake to an existing deposit.\n  /// @dev This method must only be called after proper authorization has been completed.\n  /// @dev See public stakeMore methods for additional documentation.\n  function _stakeMore(Deposit storage deposit, DepositIdentifier _depositId, uint256 _amount)\n    internal\n  {\n    _checkpointGlobalReward();\n    _checkpointReward(deposit.beneficiary);\n\n    DelegationSurrogate _surrogate = surrogates[deposit.delegatee];\n\n    totalStaked += _amount;\n    depositorTotalStaked[deposit.owner] += _amount;\n    earningPower[deposit.beneficiary] += _amount;\n    deposit.balance += _amount;\n    _stakeTokenSafeTransferFrom(deposit.owner, address(_surrogate), _amount);\n    emit StakeDeposited(deposit.owner, _depositId, _amount, deposit.balance);\n  }\n\n  /// @notice Internal convenience method which alters the delegatee of an existing deposit.\n  /// @dev This method must only be called after proper authorization has been completed.\n  /// @dev See public alterDelegatee methods for additional documentation.\n  function _alterDelegatee(\n    Deposit storage deposit,\n    DepositIdentifier _depositId,\n    address _newDelegatee\n  ) internal {\n    _revertIfAddressZero(_newDelegatee);\n    DelegationSurrogate _oldSurrogate = surrogates[deposit.delegatee];\n    emit DelegateeAltered(_depositId, deposit.delegatee, _newDelegatee);\n    deposit.delegatee = _newDelegatee;\n    DelegationSurrogate _newSurrogate = _fetchOrDeploySurrogate(_newDelegatee);\n    _stakeTokenSafeTransferFrom(address(_oldSurrogate), address(_newSurrogate), deposit.balance);\n  }\n\n  /// @notice Internal convenience method which alters the beneficiary of an existing deposit.\n  /// @dev This method must only be called after proper authorization has been completed.\n  /// @dev See public alterBeneficiary methods for additional documentation.\n  function _alterBeneficiary(\n    Deposit storage deposit,\n    DepositIdentifier _depositId,\n    address _newBeneficiary\n  ) internal {\n    _revertIfAddressZero(_newBeneficiary);\n    _checkpointGlobalReward();\n    _checkpointReward(deposit.beneficiary);\n    earningPower[deposit.beneficiary] -= deposit.balance;\n\n    _checkpointReward(_newBeneficiary);\n    emit BeneficiaryAltered(_depositId, deposit.beneficiary, _newBeneficiary);\n    deposit.beneficiary = _newBeneficiary;\n    earningPower[_newBeneficiary] += deposit.balance;\n  }\n\n  /// @notice Internal convenience method which withdraws the stake from an existing deposit.\n  /// @dev This method must only be called after proper authorization has been completed.\n  /// @dev See public withdraw methods for additional documentation.\n  function _withdraw(Deposit storage deposit, DepositIdentifier _depositId, uint256 _amount)\n    internal\n  {\n    _checkpointGlobalReward();\n    _checkpointReward(deposit.beneficiary);\n\n    deposit.balance -= _amount; // overflow prevents withdrawing more than balance\n    totalStaked -= _amount;\n    depositorTotalStaked[deposit.owner] -= _amount;\n    earningPower[deposit.beneficiary] -= _amount;\n    _stakeTokenSafeTransferFrom(address(surrogates[deposit.delegatee]), deposit.owner, _amount);\n    emit StakeWithdrawn(_depositId, _amount, deposit.balance);\n  }\n\n  /// @notice Internal convenience method which claims earned rewards.\n  /// @dev This method must only be called after proper authorization has been completed.\n  /// @dev See public claimReward methods for additional documentation.\n  function _claimReward(address _beneficiary) internal {\n    _checkpointGlobalReward();\n    _checkpointReward(_beneficiary);\n\n    uint256 _reward = unclaimedRewardCheckpoint[_beneficiary];\n    if (_reward == 0) return;\n    unclaimedRewardCheckpoint[_beneficiary] = 0;\n    emit RewardClaimed(_beneficiary, _reward);\n\n    SafeERC20.safeTransfer(REWARD_TOKEN, _beneficiary, _reward);\n  }\n\n  /// @notice Checkpoints the global reward per token accumulator.\n  function _checkpointGlobalReward() internal {\n    rewardPerTokenAccumulatedCheckpoint = rewardPerTokenAccumulated();\n    lastCheckpointTime = lastTimeRewardDistributed();\n  }\n\n  /// @notice Checkpoints the unclaimed rewards and reward per token accumulator of a given\n  /// beneficiary account.\n  /// @param _beneficiary The account for which reward parameters will be checkpointed.\n  /// @dev This is a sensitive internal helper method that must only be called after global rewards\n  /// accumulator has been checkpointed. It assumes the global `rewardPerTokenCheckpoint` is up to\n  /// date.\n  function _checkpointReward(address _beneficiary) internal {\n    unclaimedRewardCheckpoint[_beneficiary] = unclaimedReward(_beneficiary);\n    beneficiaryRewardPerTokenCheckpoint[_beneficiary] = rewardPerTokenAccumulatedCheckpoint;\n  }\n\n  /// @notice Internal helper method which sets the admin address.\n  /// @param _newAdmin Address of the new admin.\n  function _setAdmin(address _newAdmin) internal {\n    _revertIfAddressZero(_newAdmin);\n    emit AdminSet(admin, _newAdmin);\n    admin = _newAdmin;\n  }\n\n  /// @notice Internal helper method which reverts UniStaker__Unauthorized if the message sender is\n  /// not the admin.\n  function _revertIfNotAdmin() internal view {\n    if (msg.sender != admin) revert UniStaker__Unauthorized(\"not admin\", msg.sender);\n  }\n\n  /// @notice Internal helper method which reverts UniStaker__Unauthorized if the alleged owner is\n  /// not the true owner of the deposit.\n  /// @param deposit Deposit to validate.\n  /// @param owner Alleged owner of deposit.\n  function _revertIfNotDepositOwner(Deposit storage deposit, address owner) internal view {\n    if (owner != deposit.owner) revert UniStaker__Unauthorized(\"not owner\", owner);\n  }\n\n  /// @notice Internal helper method which reverts with UniStaker__InvalidAddress if the account in\n  /// question is address zero.\n  /// @param _account Account to verify.\n  function _revertIfAddressZero(address _account) internal pure {\n    if (_account == address(0)) revert UniStaker__InvalidAddress();\n  }\n\n  /// @notice Internal helper method which reverts with UniStaker__InvalidSignature if the signature\n  /// is invalid.\n  /// @param _signer Address of the signer.\n  /// @param _hash Hash of the message.\n  /// @param _signature Signature to validate.\n  function _revertIfSignatureIsNotValidNow(address _signer, bytes32 _hash, bytes memory _signature)\n    internal\n    view\n  {\n    bool _isValid = SignatureChecker.isValidSignatureNow(_signer, _hash, _signature);\n    if (!_isValid) revert UniStaker__InvalidSignature();\n  }\n}"
}