{
    "Function": "slitherConstructorConstantVariables",
    "File": "contracts/AuraLocker.sol",
    "Parent Contracts": [
        "contracts/Interfaces.sol",
        "node_modules/@openzeppelin/contracts-0.8/access/Ownable.sol",
        "node_modules/@openzeppelin/contracts-0.8/utils/Context.sol",
        "node_modules/@openzeppelin/contracts-0.8/security/ReentrancyGuard.sol"
    ],
    "High-Level Calls": [],
    "Internal Calls": [],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "contract AuraLocker is ReentrancyGuard, Ownable, IAuraLocker {\n    using AuraMath for uint256;\n    using AuraMath224 for uint224;\n    using AuraMath112 for uint112;\n    using AuraMath32 for uint32;\n    using SafeERC20 for IERC20;\n\n    /* ==========     STRUCTS     ========== */\n\n    struct RewardData {\n        /// Timestamp for current period finish\n        uint32 periodFinish;\n        /// Last time any user took action\n        uint32 lastUpdateTime;\n        /// RewardRate for the rest of the period\n        uint96 rewardRate;\n        /// Ever increasing rewardPerToken rate, based on % of total supply\n        uint96 rewardPerTokenStored;\n    }\n    struct UserData {\n        uint128 rewardPerTokenPaid;\n        uint128 rewards;\n    }\n    struct EarnedData {\n        address token;\n        uint256 amount;\n    }\n    struct Balances {\n        uint112 locked;\n        uint32 nextUnlockIndex;\n    }\n    struct LockedBalance {\n        uint112 amount;\n        uint32 unlockTime;\n    }\n    struct Epoch {\n        uint224 supply;\n        uint32 date; //epoch start date\n    }\n    struct DelegateeCheckpoint {\n        uint224 votes;\n        uint32 epochStart;\n    }\n\n    /* ========== STATE VARIABLES ========== */\n\n    // Rewards\n    address[] public rewardTokens;\n    uint256 public queuedCvxCrvRewards = 0;\n    uint256 public constant newRewardRatio = 830;\n    //     Core reward data\n    mapping(address => RewardData) public rewardData;\n    //     Reward token -> distributor -> is approved to add rewards\n    mapping(address => mapping(address => bool)) public rewardDistributors;\n    //     User -> reward token -> amount\n    mapping(address => mapping(address => UserData)) public userData;\n    //     Duration that rewards are streamed over\n    uint256 public constant rewardsDuration = 86400 * 7;\n    //     Duration of lock/earned penalty period\n    uint256 public constant lockDuration = rewardsDuration * 17;\n\n    // Balances\n    //     Supplies and historic supply\n    uint256 public lockedSupply;\n    //     Epochs contains only the tokens that were locked at that epoch, not a cumulative supply\n    Epoch[] public epochs;\n    //     Mappings for balance data\n    mapping(address => Balances) public balances;\n    mapping(address => LockedBalance[]) public userLocks;\n\n    // Voting\n    //     Stored delegations\n    mapping(address => address) private _delegates;\n    //     Checkpointed votes\n    mapping(address => DelegateeCheckpoint[]) private _checkpointedVotes;\n    //     Delegatee balances (user -> unlock timestamp -> amount)\n    mapping(address => mapping(uint256 => uint256)) public delegateeUnlocks;\n\n    // Config\n    //     Tokens\n    IERC20 public immutable stakingToken;\n    address public immutable cvxCrv;\n    //     Denom for calcs\n    uint256 public constant denominator = 10000;\n    //     Staking cvxCrv\n    address public immutable cvxcrvStaking;\n    //     Incentives\n    uint256 public kickRewardPerEpoch = 100;\n    uint256 public kickRewardEpochDelay = 3;\n    //     Shutdown\n    bool public isShutdown = false;\n\n    // Basic token data\n    string private _name;\n    string private _symbol;\n    uint8 private immutable _decimals;\n\n    /* ========== EVENTS ========== */\n\n    event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);\n    event DelegateCheckpointed(address indexed delegate);\n\n    event Recovered(address _token, uint256 _amount);\n    event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);\n    event Staked(address indexed _user, uint256 _paidAmount, uint256 _lockedAmount);\n    event Withdrawn(address indexed _user, uint256 _amount, bool _relocked);\n    event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);\n    event RewardAdded(address indexed _token, uint256 _reward);\n\n    event KickIncentiveSet(uint256 rate, uint256 delay);\n    event Shutdown();\n\n    /***************************************\n                    CONSTRUCTOR\n    ****************************************/\n\n    /**\n     * @param _nameArg          Token name, simples\n     * @param _symbolArg        Token symbol\n     * @param _stakingToken     CVX (0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B)\n     * @param _cvxCrv           cvxCRV (0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7)\n     * @param _cvxCrvStaking    cvxCRV rewards (0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e)\n     */\n    constructor(\n        string memory _nameArg,\n        string memory _symbolArg,\n        address _stakingToken,\n        address _cvxCrv,\n        address _cvxCrvStaking\n    ) Ownable() {\n        _name = _nameArg;\n        _symbol = _symbolArg;\n        _decimals = 18;\n\n        stakingToken = IERC20(_stakingToken);\n        cvxCrv = _cvxCrv;\n        cvxcrvStaking = _cvxCrvStaking;\n\n        uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);\n        epochs.push(Epoch({ supply: 0, date: uint32(currentEpoch) }));\n    }\n\n    /***************************************\n                    MODIFIER\n    ****************************************/\n\n    modifier updateReward(address _account) {\n        {\n            Balances storage userBalance = balances[_account];\n            uint256 rewardTokensLength = rewardTokens.length;\n            for (uint256 i = 0; i < rewardTokensLength; i++) {\n                address token = rewardTokens[i];\n                uint256 newRewardPerToken = _rewardPerToken(token);\n                rewardData[token].rewardPerTokenStored = newRewardPerToken.to96();\n                rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(rewardData[token].periodFinish).to32();\n                if (_account != address(0)) {\n                    userData[_account][token] = UserData({\n                        rewardPerTokenPaid: newRewardPerToken.to128(),\n                        rewards: _earned(_account, token, userBalance.locked).to128()\n                    });\n                }\n            }\n        }\n        _;\n    }\n\n    /***************************************\n                    ADMIN\n    ****************************************/\n\n    // Add a new reward token to be distributed to stakers\n    function addReward(address _rewardsToken, address _distributor) external onlyOwner {\n        require(rewardData[_rewardsToken].lastUpdateTime == 0, \"Reward already exists\");\n        require(_rewardsToken != address(stakingToken), \"Cannot add StakingToken as reward\");\n        rewardTokens.push(_rewardsToken);\n        rewardData[_rewardsToken].lastUpdateTime = uint32(block.timestamp);\n        rewardData[_rewardsToken].periodFinish = uint32(block.timestamp);\n        rewardDistributors[_rewardsToken][_distributor] = true;\n    }\n\n    // Modify approval for an address to call notifyRewardAmount\n    function approveRewardDistributor(\n        address _rewardsToken,\n        address _distributor,\n        bool _approved\n    ) external onlyOwner {\n        require(rewardData[_rewardsToken].lastUpdateTime > 0, \"Reward does not exist\");\n        rewardDistributors[_rewardsToken][_distributor] = _approved;\n    }\n\n    //set kick incentive\n    function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {\n        require(_rate <= 500, \"over max rate\"); //max 5% per epoch\n        require(_delay >= 2, \"min delay\"); //minimum 2 epochs of grace\n        kickRewardPerEpoch = _rate;\n        kickRewardEpochDelay = _delay;\n\n        emit KickIncentiveSet(_rate, _delay);\n    }\n\n    //shutdown the contract. unstake all tokens. release all locks\n    function shutdown() external onlyOwner {\n        isShutdown = true;\n        emit Shutdown();\n    }\n\n    // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders\n    function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {\n        require(_tokenAddress != address(stakingToken), \"Cannot withdraw staking token\");\n        require(rewardData[_tokenAddress].lastUpdateTime == 0, \"Cannot withdraw reward token\");\n        IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);\n        emit Recovered(_tokenAddress, _tokenAmount);\n    }\n\n    // Set approvals for staking cvx and cvxcrv\n    function setApprovals() external {\n        IERC20(cvxCrv).safeApprove(cvxcrvStaking, 0);\n        IERC20(cvxCrv).safeApprove(cvxcrvStaking, type(uint256).max);\n    }\n\n    /***************************************\n                    ACTIONS\n    ****************************************/\n\n    // Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards\n    function lock(address _account, uint256 _amount) external nonReentrant updateReward(_account) {\n        //pull tokens\n        stakingToken.safeTransferFrom(msg.sender, address(this), _amount);\n\n        //lock\n        _lock(_account, _amount);\n    }\n\n    //lock tokens\n    function _lock(address _account, uint256 _amount) internal {\n        require(_amount > 0, \"Cannot stake 0\");\n        require(!isShutdown, \"shutdown\");\n\n        Balances storage bal = balances[_account];\n\n        //must try check pointing epoch first\n        _checkpointEpoch();\n\n        //add user balances\n        uint112 lockAmount = _amount.to112();\n        bal.locked = bal.locked.add(lockAmount);\n\n        //add to total supplies\n        lockedSupply = lockedSupply.add(_amount);\n\n        //add user lock records or add to current\n        uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);\n        uint256 unlockTime = currentEpoch.add(lockDuration);\n        uint256 idx = userLocks[_account].length;\n        if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {\n            userLocks[_account].push(LockedBalance({ amount: lockAmount, unlockTime: uint32(unlockTime) }));\n        } else {\n            LockedBalance storage userL = userLocks[_account][idx - 1];\n            userL.amount = userL.amount.add(lockAmount);\n        }\n\n        address delegatee = delegates(_account);\n        if (delegatee != address(0)) {\n            delegateeUnlocks[delegatee][unlockTime] += lockAmount;\n            _checkpointDelegate(delegatee, lockAmount, 0);\n        }\n\n        //update epoch supply, epoch checkpointed above so safe to add to latest\n        Epoch storage e = epochs[epochs.length - 1];\n        e.supply = e.supply.add(lockAmount);\n\n        emit Staked(_account, lockAmount, lockAmount);\n    }\n\n    // claim all pending rewards\n    function getReward(address _account) external {\n        getReward(_account, false);\n    }\n\n    // Claim all pending rewards\n    function getReward(address _account, bool _stake) public nonReentrant updateReward(_account) {\n        uint256 rewardTokensLength = rewardTokens.length;\n        for (uint256 i; i < rewardTokensLength; i++) {\n            address _rewardsToken = rewardTokens[i];\n            uint256 reward = userData[_account][_rewardsToken].rewards;\n            if (reward > 0) {\n                userData[_account][_rewardsToken].rewards = 0;\n                if (_rewardsToken == cvxCrv && _stake && _account == msg.sender) {\n                    IRewardStaking(cvxcrvStaking).stakeFor(_account, reward);\n                } else {\n                    IERC20(_rewardsToken).safeTransfer(_account, reward);\n                }\n                emit RewardPaid(_account, _rewardsToken, reward);\n            }\n        }\n    }\n\n    function checkpointEpoch() external {\n        _checkpointEpoch();\n    }\n\n    //insert a new epoch if needed. fill in any gaps\n    function _checkpointEpoch() internal {\n        uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(rewardsDuration);\n        uint256 epochindex = epochs.length;\n\n        //first epoch add in constructor, no need to check 0 length\n        //check to add\n        if (epochs[epochindex - 1].date < currentEpoch) {\n            //fill any epoch gaps until the next epoch date.\n            while (epochs[epochs.length - 1].date != currentEpoch) {\n                uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date).add(rewardsDuration);\n                epochs.push(Epoch({ supply: 0, date: uint32(nextEpochDate) }));\n            }\n        }\n    }\n\n    // Withdraw/relock all currently locked tokens where the unlock time has passed\n    function processExpiredLocks(bool _relock) external nonReentrant {\n        _processExpiredLocks(msg.sender, _relock, msg.sender, 0);\n    }\n\n    function kickExpiredLocks(address _account) external nonReentrant {\n        //allow kick after grace period of 'kickRewardEpochDelay'\n        _processExpiredLocks(_account, false, msg.sender, rewardsDuration.mul(kickRewardEpochDelay));\n    }\n\n    // Withdraw without checkpointing or accruing any rewards, providing system is shutdown\n    function emergencyWithdraw() external nonReentrant {\n        require(isShutdown, \"Must be shutdown\");\n\n        LockedBalance[] memory locks = userLocks[msg.sender];\n        Balances storage userBalance = balances[msg.sender];\n\n        uint256 amt = userBalance.locked;\n        require(amt > 0, \"Nothing locked\");\n\n        userBalance.locked = 0;\n        userBalance.nextUnlockIndex = locks.length.to32();\n        lockedSupply -= amt;\n\n        emit Withdrawn(msg.sender, amt, false);\n\n        stakingToken.safeTransfer(msg.sender, amt);\n    }\n\n    // Withdraw all currently locked tokens where the unlock time has passed\n    function _processExpiredLocks(\n        address _account,\n        bool _relock,\n        address _rewardAddress,\n        uint256 _checkDelay\n    ) internal updateReward(_account) {\n        LockedBalance[] storage locks = userLocks[_account];\n        Balances storage userBalance = balances[_account];\n        uint112 locked;\n        uint256 length = locks.length;\n        uint256 reward = 0;\n        uint256 expiryTime = _checkDelay == 0 && _relock\n            ? block.timestamp.add(rewardsDuration)\n            : block.timestamp.sub(_checkDelay);\n        require(length > 0, \"no locks\");\n        // e.g. now = 16\n        // if contract is shutdown OR latest lock unlock time (e.g. 17) <= now - (1)\n        // e.g. 17 <= (16 + 1)\n        if (isShutdown || locks[length - 1].unlockTime <= expiryTime) {\n            //if time is beyond last lock, can just bundle everything together\n            locked = userBalance.locked;\n\n            //dont delete, just set next index\n            userBalance.nextUnlockIndex = length.to32();\n\n            //check for kick reward\n            //this wont have the exact reward rate that you would get if looped through\n            //but this section is supposed to be for quick and easy low gas processing of all locks\n            //we'll assume that if the reward was good enough someone would have processed at an earlier epoch\n            if (_checkDelay > 0) {\n                uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);\n                uint256 epochsover = currentEpoch.sub(uint256(locks[length - 1].unlockTime)).div(rewardsDuration);\n                uint256 rRate = AuraMath.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);\n                reward = uint256(locks[length - 1].amount).mul(rRate).div(denominator);\n            }\n        } else {\n            //use a processed index(nextUnlockIndex) to not loop as much\n            //deleting does not change array length\n            uint32 nextUnlockIndex = userBalance.nextUnlockIndex;\n            for (uint256 i = nextUnlockIndex; i < length; i++) {\n                //unlock time must be less or equal to time\n                if (locks[i].unlockTime > expiryTime) break;\n\n                //add to cumulative amounts\n                locked = locked.add(locks[i].amount);\n\n                //check for kick reward\n                //each epoch over due increases reward\n                if (_checkDelay > 0) {\n                    uint256 currentEpoch = block.timestamp.sub(_checkDelay).div(rewardsDuration).mul(rewardsDuration);\n                    uint256 epochsover = currentEpoch.sub(uint256(locks[i].unlockTime)).div(rewardsDuration);\n                    uint256 rRate = AuraMath.min(kickRewardPerEpoch.mul(epochsover + 1), denominator);\n                    reward = reward.add(uint256(locks[i].amount).mul(rRate).div(denominator));\n                }\n                //set next unlock index\n                nextUnlockIndex++;\n            }\n            //update next unlock index\n            userBalance.nextUnlockIndex = nextUnlockIndex;\n        }\n        require(locked > 0, \"no exp locks\");\n\n        //update user balances and total supplies\n        userBalance.locked = userBalance.locked.sub(locked);\n        lockedSupply = lockedSupply.sub(locked);\n\n        //checkpoint the delegatee\n        _checkpointDelegate(delegates(_account), 0, 0);\n\n        emit Withdrawn(_account, locked, _relock);\n\n        //send process incentive\n        if (reward > 0) {\n            //reduce return amount by the kick reward\n            locked = locked.sub(reward.to112());\n\n            //transfer reward\n            stakingToken.safeTransfer(_rewardAddress, reward);\n            emit KickReward(_rewardAddress, _account, reward);\n        }\n\n        //relock or return to user\n        if (_relock) {\n            _lock(_account, locked);\n        } else {\n            stakingToken.safeTransfer(_account, locked);\n        }\n    }\n\n    /***************************************\n            DELEGATION & VOTE BALANCE\n    ****************************************/\n\n    /**\n     * @dev Delegate votes from the sender to `newDelegatee`.\n     */\n    function delegate(address newDelegatee) external virtual nonReentrant {\n        // Step 1: Get lock data\n        LockedBalance[] storage locks = userLocks[msg.sender];\n        uint256 len = locks.length;\n        require(len > 0, \"Nothing to delegate\");\n        require(newDelegatee != address(0), \"Must delegate to someone\");\n\n        // Step 2: Update delegatee storage\n        address oldDelegatee = delegates(msg.sender);\n        require(newDelegatee != oldDelegatee, \"Must choose new delegatee\");\n        _delegates[msg.sender] = newDelegatee;\n\n        emit DelegateChanged(msg.sender, oldDelegatee, newDelegatee);\n\n        // Step 3: Move balances around\n        //         Delegate for the upcoming epoch\n        uint256 upcomingEpoch = block.timestamp.add(rewardsDuration).div(rewardsDuration).mul(rewardsDuration);\n        uint256 i = len - 1;\n        uint256 futureUnlocksSum = 0;\n        LockedBalance memory currentLock = locks[i];\n        // Step 3.1: Add future unlocks and sum balances\n        while (currentLock.unlockTime > upcomingEpoch) {\n            futureUnlocksSum += currentLock.amount;\n\n            if (oldDelegatee != address(0)) {\n                delegateeUnlocks[oldDelegatee][currentLock.unlockTime] -= currentLock.amount;\n            }\n            delegateeUnlocks[newDelegatee][currentLock.unlockTime] += currentLock.amount;\n\n            if (i > 0) {\n                i--;\n                currentLock = locks[i];\n            } else {\n                break;\n            }\n        }\n\n        // Step 3.2: Checkpoint old delegatee\n        _checkpointDelegate(oldDelegatee, 0, futureUnlocksSum);\n\n        // Step 3.3: Checkpoint new delegatee\n        _checkpointDelegate(newDelegatee, futureUnlocksSum, 0);\n    }\n\n    function _checkpointDelegate(\n        address _account,\n        uint256 _upcomingAddition,\n        uint256 _upcomingDeduction\n    ) internal {\n        // This would only skip on first checkpointing\n        if (_account != address(0)) {\n            uint256 upcomingEpoch = block.timestamp.add(rewardsDuration).div(rewardsDuration).mul(rewardsDuration);\n            DelegateeCheckpoint[] storage ckpts = _checkpointedVotes[_account];\n            if (ckpts.length > 0) {\n                DelegateeCheckpoint memory prevCkpt = ckpts[ckpts.length - 1];\n                // If there has already been a record for the upcoming epoch, no need to deduct the unlocks\n                if (prevCkpt.epochStart == upcomingEpoch) {\n                    ckpts[ckpts.length - 1] = DelegateeCheckpoint({\n                        votes: (prevCkpt.votes + _upcomingAddition - _upcomingDeduction).to224(),\n                        epochStart: upcomingEpoch.to32()\n                    });\n                }\n                // else if it has been over 16 weeks since the previous checkpoint, all locks have since expired\n                // e.g. week 1 + 17 <= 18\n                else if (prevCkpt.epochStart + lockDuration <= upcomingEpoch) {\n                    ckpts.push(\n                        DelegateeCheckpoint({\n                            votes: (_upcomingAddition - _upcomingDeduction).to224(),\n                            epochStart: upcomingEpoch.to32()\n                        })\n                    );\n                } else {\n                    uint256 nextEpoch = upcomingEpoch;\n                    uint256 unlocksSinceLatestCkpt = 0;\n                    // Should be maximum 18 iterations\n                    while (nextEpoch > prevCkpt.epochStart) {\n                        unlocksSinceLatestCkpt += delegateeUnlocks[_account][nextEpoch];\n                        nextEpoch -= rewardsDuration;\n                    }\n                    ckpts.push(\n                        DelegateeCheckpoint({\n                            votes: (prevCkpt.votes - unlocksSinceLatestCkpt + _upcomingAddition - _upcomingDeduction)\n                                .to224(),\n                            epochStart: upcomingEpoch.to32()\n                        })\n                    );\n                }\n            } else {\n                ckpts.push(\n                    DelegateeCheckpoint({\n                        votes: (_upcomingAddition - _upcomingDeduction).to224(),\n                        epochStart: upcomingEpoch.to32()\n                    })\n                );\n            }\n            emit DelegateCheckpointed(_account);\n        }\n    }\n\n    /**\n     * @dev Get the address `account` is currently delegating to.\n     */\n    function delegates(address account) public view virtual returns (address) {\n        return _delegates[account];\n    }\n\n    /**\n     * @dev Gets the current votes balance for `account`\n     */\n    function getVotes(address account) external view returns (uint256) {\n        return getPastVotes(account, block.timestamp);\n    }\n\n    /**\n     * @dev Get the `pos`-th checkpoint for `account`.\n     */\n    function checkpoints(address account, uint32 pos) external view virtual returns (DelegateeCheckpoint memory) {\n        return _checkpointedVotes[account][pos];\n    }\n\n    /**\n     * @dev Get number of checkpoints for `account`.\n     */\n    function numCheckpoints(address account) external view virtual returns (uint32) {\n        return _checkpointedVotes[account].length.to32();\n    }\n\n    /**\n     * @dev Retrieve the number of votes for `account` at the end of `blockNumber`.\n     */\n    function getPastVotes(address account, uint256 timestamp) public view returns (uint256 votes) {\n        require(timestamp <= block.timestamp, \"ERC20Votes: block not yet mined\");\n        uint256 epoch = timestamp.div(rewardsDuration).mul(rewardsDuration);\n        DelegateeCheckpoint memory ckpt = _checkpointsLookup(_checkpointedVotes[account], epoch);\n        votes = ckpt.votes;\n        if (votes == 0 || ckpt.epochStart + lockDuration <= epoch) {\n            return 0;\n        }\n        while (epoch > ckpt.epochStart) {\n            votes -= delegateeUnlocks[account][epoch];\n            epoch -= rewardsDuration;\n        }\n    }\n\n    /**\n     * @dev Retrieve the `totalSupply` at the end of `timestamp`. Note, this value is the sum of all balances.\n     * It is but NOT the sum of all the delegated votes!\n     */\n    function getPastTotalSupply(uint256 timestamp) external view returns (uint256) {\n        require(timestamp < block.timestamp, \"ERC20Votes: block not yet mined\");\n        return totalSupplyAtEpoch(findEpochId(timestamp));\n    }\n\n    /**\n     * @dev Lookup a value in a list of (sorted) checkpoints.\n     *      Copied from oz/ERC20Votes.sol\n     */\n    function _checkpointsLookup(DelegateeCheckpoint[] storage ckpts, uint256 epochStart)\n        private\n        view\n        returns (DelegateeCheckpoint memory)\n    {\n        uint256 high = ckpts.length;\n        uint256 low = 0;\n        while (low < high) {\n            uint256 mid = AuraMath.average(low, high);\n            if (ckpts[mid].epochStart > epochStart) {\n                high = mid;\n            } else {\n                low = mid + 1;\n            }\n        }\n\n        return high == 0 ? DelegateeCheckpoint(0, 0) : ckpts[high - 1];\n    }\n\n    /***************************************\n                VIEWS - BALANCES\n    ****************************************/\n\n    // Balance of an account which only includes properly locked tokens as of the most recent eligible epoch\n    function balanceOf(address _user) external view returns (uint256 amount) {\n        return balanceAtEpochOf(findEpochId(block.timestamp), _user);\n    }\n\n    // Balance of an account which only includes properly locked tokens at the given epoch\n    function balanceAtEpochOf(uint256 _epoch, address _user) public view returns (uint256 amount) {\n        uint256 epochStart = uint256(epochs[0].date).add(uint256(_epoch).mul(rewardsDuration));\n        require(epochStart < block.timestamp, \"Epoch is in the future\");\n\n        uint256 cutoffEpoch = epochStart.sub(lockDuration);\n\n        LockedBalance[] storage locks = userLocks[_user];\n\n        //need to add up since the range could be in the middle somewhere\n        //traverse inversely to make more current queries more gas efficient\n        uint256 locksLength = locks.length;\n        for (uint256 i = locksLength; i > 0; i--) {\n            uint256 lockEpoch = uint256(locks[i - 1].unlockTime).sub(lockDuration);\n            //lock epoch must be less or equal to the epoch we're basing from.\n            //also not include the current epoch\n            if (lockEpoch < epochStart) {\n                if (lockEpoch > cutoffEpoch) {\n                    amount = amount.add(locks[i - 1].amount);\n                } else {\n                    //stop now as no futher checks matter\n                    break;\n                }\n            }\n        }\n\n        return amount;\n    }\n\n    // Information on a user's locked balances\n    function lockedBalances(address _user)\n        external\n        view\n        returns (\n            uint256 total,\n            uint256 unlockable,\n            uint256 locked,\n            LockedBalance[] memory lockData\n        )\n    {\n        LockedBalance[] storage locks = userLocks[_user];\n        Balances storage userBalance = balances[_user];\n        uint256 nextUnlockIndex = userBalance.nextUnlockIndex;\n        uint256 idx;\n        for (uint256 i = nextUnlockIndex; i < locks.length; i++) {\n            if (locks[i].unlockTime > block.timestamp) {\n                if (idx == 0) {\n                    lockData = new LockedBalance[](locks.length - i);\n                }\n                lockData[idx] = locks[i];\n                idx++;\n                locked = locked.add(locks[i].amount);\n            } else {\n                unlockable = unlockable.add(locks[i].amount);\n            }\n        }\n        return (userBalance.locked, unlockable, locked, lockData);\n    }\n\n    // Supply of all properly locked balances at most recent eligible epoch\n    function totalSupply() external view returns (uint256 supply) {\n        return totalSupplyAtEpoch(findEpochId(block.timestamp));\n    }\n\n    // Supply of all properly locked balances at the given epoch\n    function totalSupplyAtEpoch(uint256 _epoch) public view returns (uint256 supply) {\n        uint256 epochStart = uint256(epochs[0].date).add(uint256(_epoch).mul(rewardsDuration));\n        require(epochStart < block.timestamp, \"Epoch is in the future\");\n\n        uint256 cutoffEpoch = epochStart.sub(lockDuration);\n        uint256 lastIndex = epochs.length - 1;\n\n        uint256 epochIndex = _epoch > lastIndex ? lastIndex : _epoch;\n\n        for (uint256 i = epochIndex + 1; i > 0; i--) {\n            Epoch memory e = epochs[i - 1];\n            if (e.date == epochStart) {\n                continue;\n            } else if (e.date <= cutoffEpoch) {\n                break;\n            } else {\n                supply += e.supply;\n            }\n        }\n    }\n\n    // Get an epoch index based on timestamp\n    function findEpochId(uint256 _time) public view returns (uint256 epoch) {\n        return _time.sub(epochs[0].date).div(rewardsDuration);\n    }\n\n    /***************************************\n                VIEWS - GENERAL\n    ****************************************/\n\n    // Number of epochs\n    function epochCount() external view returns (uint256) {\n        return epochs.length;\n    }\n\n    function decimals() external view returns (uint8) {\n        return _decimals;\n    }\n\n    function name() external view returns (string memory) {\n        return _name;\n    }\n\n    function symbol() external view returns (string memory) {\n        return _symbol;\n    }\n\n    /***************************************\n                VIEWS - REWARDS\n    ****************************************/\n\n    // Address and claimable amount of all reward tokens for the given account\n    function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards) {\n        userRewards = new EarnedData[](rewardTokens.length);\n        Balances storage userBalance = balances[_account];\n        uint256 userRewardsLength = userRewards.length;\n        for (uint256 i = 0; i < userRewardsLength; i++) {\n            address token = rewardTokens[i];\n            userRewards[i].token = token;\n            userRewards[i].amount = _earned(_account, token, userBalance.locked);\n        }\n        return userRewards;\n    }\n\n    function lastTimeRewardApplicable(address _rewardsToken) external view returns (uint256) {\n        return _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);\n    }\n\n    function rewardPerToken(address _rewardsToken) external view returns (uint256) {\n        return _rewardPerToken(_rewardsToken);\n    }\n\n    function _earned(\n        address _user,\n        address _rewardsToken,\n        uint256 _balance\n    ) internal view returns (uint256) {\n        UserData memory data = userData[_user][_rewardsToken];\n        return _balance.mul(_rewardPerToken(_rewardsToken).sub(data.rewardPerTokenPaid)).div(1e18).add(data.rewards);\n    }\n\n    function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {\n        return AuraMath.min(block.timestamp, _finishTime);\n    }\n\n    function _rewardPerToken(address _rewardsToken) internal view returns (uint256) {\n        if (lockedSupply == 0) {\n            return rewardData[_rewardsToken].rewardPerTokenStored;\n        }\n        return\n            uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(\n                _lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish)\n                    .sub(rewardData[_rewardsToken].lastUpdateTime)\n                    .mul(rewardData[_rewardsToken].rewardRate)\n                    .mul(1e18)\n                    .div(lockedSupply)\n            );\n    }\n\n    /***************************************\n                REWARD FUNDING\n    ****************************************/\n\n    function queueNewRewards(uint256 _rewards) external nonReentrant {\n        require(rewardDistributors[cvxCrv][msg.sender], \"!authorized\");\n        require(_rewards > 0, \"No reward\");\n\n        RewardData storage rdata = rewardData[cvxCrv];\n\n        IERC20(cvxCrv).safeTransferFrom(msg.sender, address(this), _rewards);\n\n        _rewards = _rewards.add(queuedCvxCrvRewards);\n        if (block.timestamp >= rdata.periodFinish) {\n            _notifyReward(cvxCrv, _rewards);\n            queuedCvxCrvRewards = 0;\n            return;\n        }\n\n        //et = now - (finish-duration)\n        uint256 elapsedTime = block.timestamp.sub(rdata.periodFinish.sub(rewardsDuration.to32()));\n        //current at now: rewardRate * elapsedTime\n        uint256 currentAtNow = rdata.rewardRate * elapsedTime;\n        uint256 queuedRatio = currentAtNow.mul(1000).div(_rewards);\n        if (queuedRatio < newRewardRatio) {\n            _notifyReward(cvxCrv, _rewards);\n            queuedCvxCrvRewards = 0;\n        } else {\n            queuedCvxCrvRewards = _rewards;\n        }\n    }\n\n    function notifyRewardAmount(address _rewardsToken, uint256 _reward) external {\n        require(_rewardsToken != cvxCrv, \"Use queueNewRewards\");\n        require(rewardDistributors[_rewardsToken][msg.sender], \"Must be rewardsDistributor\");\n        require(_reward > 0, \"No reward\");\n\n        _notifyReward(_rewardsToken, _reward);\n\n        // handle the transfer of reward tokens via `transferFrom` to reduce the number\n        // of transactions required and ensure correctness of the _reward amount\n        IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), _reward);\n    }\n\n    function _notifyReward(address _rewardsToken, uint256 _reward) internal updateReward(address(0)) {\n        RewardData storage rdata = rewardData[_rewardsToken];\n\n        if (block.timestamp >= rdata.periodFinish) {\n            rdata.rewardRate = _reward.div(rewardsDuration).to96();\n        } else {\n            uint256 remaining = uint256(rdata.periodFinish).sub(block.timestamp);\n            uint256 leftover = remaining.mul(rdata.rewardRate);\n            rdata.rewardRate = _reward.add(leftover).div(rewardsDuration).to96();\n        }\n\n        rdata.lastUpdateTime = block.timestamp.to32();\n        rdata.periodFinish = block.timestamp.add(rewardsDuration).to32();\n\n        emit RewardAdded(_rewardsToken, _reward);\n    }\n}"
}