Skip to content
Verified contractExactMIT

ResupplyVoteExecutor

Address0xeac960e8bb7f24bcd566d148d9ac1dad66e07950
Balance

0 ETH

 

Transactions

8

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 200 runs
EVM version
prague
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,478,271
Creation transaction
0xe71ff28c17…06d3c8f9f0

src/ResupplyVoteExecutor.sol

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

import "./DaoVotePlatform.sol";
import "./interface/IvlCVX.sol";
import "openzeppelin-contracts/contracts/access/Ownable2Step.sol";

interface IResupplyStaker {
    function safeExecute(address target, bytes calldata data) external returns (bytes memory);
    function claimAndStake() external returns (uint256 amount);
}

interface IResupplyVoter {
    function voteForProposal(address account, uint256 id, uint256 pctYes, uint256 pctNo) external;
}

contract ResupplyVoteExecutor is Ownable2Step {
    string public name;

    error NotFinished();
    error AlreadyExecuted();
    error QuorumNotMet();
    error ZeroSupply();
    error InvalidQuorum();

    uint256 public constant WEIGHT_BPS = 10000;
    uint256 public constant MAX_QUORUM_BPS = 10000;
    address public constant RESUPPLY_STAKER = 0xCCCCCccc94bFeCDd365b4Ee6B86108fC91848901;
    address public constant RESUPPLY_VOTER = 0x11111111063874cE8dC6232cb5C1C849359476E6;

    DaoVotePlatform public immutable votePlatform;

    uint256 public quorumBps;
    mapping(address => bool) public guardians;
    mapping(uint256 => bool) public executed;

    event DaoVoteExecuted(uint256 indexed proposalId, uint256 yay, uint256 nay);
    event GuardianSet(address indexed guardian, bool active);
    event QuorumSet(uint256 quorumBps);

    /// @notice Creates a new ResupplyVoteExecutor contract
    /// @param _name Contract name identifier
    /// @param _owner Address of the contract owner
    /// @param _votePlatform Address of the DaoVotePlatform contract
    /// @param _quorumBps Minimum quorum in basis points
    constructor(string memory _name, address _owner, address _votePlatform, uint256 _quorumBps) Ownable(_owner) {
        name = _name;
        if (_quorumBps > MAX_QUORUM_BPS) revert InvalidQuorum();
        votePlatform = DaoVotePlatform(_votePlatform);
        quorumBps = _quorumBps;
    }

    /// @notice Executes a finalized DAO vote on Resupply
    /// @param _proposalId Proposal identifier to execute
    function executeDaoVote(uint256 _proposalId) external {
        if (executed[_proposalId]) revert AlreadyExecuted();
        if (!votePlatform.isFinished(_proposalId)) revert NotFinished();
        if (!votePlatform.isFinalized(_proposalId) && !guardians[msg.sender]) revert NotFinished();

        (,, uint48 epoch, , uint256 proposalId) = votePlatform.proposals(_proposalId);
        uint256 yesVotes = votePlatform.getYes(_proposalId);
        uint256 totalVotes = yesVotes + votePlatform.getNo(_proposalId);

        uint256 totalSupply = IvlCVX(votePlatform.vlCVX()).totalSupplyAtEpoch(epoch);
        if (totalSupply == 0) revert ZeroSupply();

        if (quorumBps > 0 && totalVotes * WEIGHT_BPS / totalSupply < quorumBps) revert QuorumNotMet();

        uint256 yay = totalVotes > 0 ? yesVotes * WEIGHT_BPS / totalVotes : 0;
        uint256 nay = WEIGHT_BPS - yay;

        executed[_proposalId] = true;

        bytes memory voterCall = abi.encodeWithSelector(
            IResupplyVoter.voteForProposal.selector,
            RESUPPLY_STAKER,
            proposalId,
            yay,
            nay
        );

        IResupplyStaker(RESUPPLY_STAKER).safeExecute(RESUPPLY_VOTER, voterCall);
        emit DaoVoteExecuted(_proposalId, yay, nay);
    }

    /// @notice Checks if a proposal has been executed
    /// @param _proposalId Proposal identifier
    /// @return True if proposal was executed
    function isDone(uint256 _proposalId) external view returns (bool) {
        return executed[_proposalId];
    }

    /// @notice Sets a guardian address
    /// @param _guardian Guardian address
    /// @param _active True to add, false to remove
    function setGuardian(address _guardian, bool _active) external onlyOwner {
        guardians[_guardian] = _active;
        emit GuardianSet(_guardian, _active);
    }

    /// @notice Sets the quorum threshold in basis points
    /// @param _quorumBps Quorum in basis points
    function setQuorum(uint256 _quorumBps) external onlyOwner {
        if (_quorumBps > MAX_QUORUM_BPS) revert InvalidQuorum();
        quorumBps = _quorumBps;
        emit QuorumSet(_quorumBps);
    }

    /// @notice Claims and stakes rewards from the Resupply staker
    /// @return amount Amount claimed and staked
    function claimAndStake() external returns (uint256 amount) {
        amount = IResupplyStaker(RESUPPLY_STAKER).claimAndStake();
    }

    /// @notice Returns the contract version
    /// @return _major Major version
    /// @return _minor Minor version
    /// @return _patch Patch version
    function version() external pure returns (uint256 _major, uint256 _minor, uint256 _patch) {
        _major = 1;
        _minor = 0;
        _patch = 0;
    }
}

lib/openzeppelin-contracts/contracts/access/Ownable.sol

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

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

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

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

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

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

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

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

lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

lib/openzeppelin-contracts/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

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

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

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

src/DaoVotePlatform.sol

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

import "./Delegation.sol";
import "./SurrogateRegistry.sol";
import "./interface/IvlCVX.sol";
import "openzeppelin-contracts/contracts/access/Ownable2Step.sol";

contract DaoVotePlatform is Ownable2Step {
    string public name;

    error NotStarted();
    error Ended();
    error NoWeight();
    error PrevNotEnded();
    error BadTime();
    error AlreadyVoted();
    error NotVoteAuth();
    error NotSigner();
    error NotOperator();
    error MaxWeight();
    error DelegateOverSubtracted();

    mapping(address => bool) public operators;

    IvlCVX public immutable vlCVX;
    SurrogateRegistry public immutable surrogateRegistry;
    Delegation public immutable delegation;

    uint256 public constant epochDuration = 86400 * 7;
    uint256 public constant finalizationTime = 12 hours;
    uint256 public constant max_weight = 10000;
    uint256 public constant MIN_PROPOSAL_DURATION = 1 days;
    uint256 public constant MAX_PROPOSAL_DURATION = 6 days;
    uint256 private constant WEIGHT_DIVISOR = 1e17;

    enum VoteStatus {
        None,
        VotedViaSurrogate,
        Voted
    }

    struct UserInfo {
        uint96 baseWeight;
        int96 adjustedWeight;
        uint48 lastVoteSyncNonce;
        uint16 yesWeight;
        uint16 noWeight;
        uint8 voteStatus;
        address delegate;
        uint96 totalDelegationWeight;
    }

    struct Proposal {
        uint48 startTime;
        uint48 endTime;
        uint48 epoch;
        uint8 voteType;
        uint104 proposalId;
    }

    struct VoteTotals {
        uint128 yes;
        uint128 no;
    }

    enum VoteType {
        Ownership,
        Parameter
    }

    mapping(uint256 => mapping(address => UserInfo)) public userInfo;
    mapping(uint256 => address[]) public votedUsers;
    Proposal[] public proposals;
    mapping(uint256 => VoteTotals) internal _voteTotals;
    mapping(uint256 => mapping(address => int96)) public pendingWeightAdjustment;

    event VoteCast(uint256 indexed _proposalId, address indexed user, uint256 yesWeight, uint256 noWeight);
    event NewProposal(uint256 indexed id, uint256 start, uint256 end, VoteType voteType);
    event ForceEndProposal(uint256 indexed id);
    event UserWeightChange(uint256 indexed pid, address indexed user, uint256 baseWeight, int256 adjustedWeight);
    event PendingWeightAdjustment(uint256 indexed pid, address indexed delegate, int256 diff);
    event OperatorSet(address indexed op, bool active);

    /// @notice Creates a new DaoVotePlatform contract
    /// @param _name Contract name identifier
    /// @param _owner Address of the contract owner
    /// @param _vlCVX Address of the vlCVX contract
    /// @param _surrogateRegistry Address of the SurrogateRegistry
    /// @param _delegation Address of the Delegation contract
    constructor(string memory _name, address _owner, address _vlCVX, address _surrogateRegistry, address _delegation)
        Ownable(_owner)
    {
        name = _name;
        operators[_owner] = true;
        vlCVX = IvlCVX(_vlCVX);
        surrogateRegistry = SurrogateRegistry(_surrogateRegistry);
        delegation = Delegation(_delegation);
    }

    /// @notice Returns the current epoch start timestamp
    /// @return Current epoch start time
    function currentEpoch() public view returns (uint256) {
        return block.timestamp / epochDuration * epochDuration;
    }

    /// @notice Returns the total number of proposals
    /// @return Proposal count
    function proposalCount() external view returns (uint256) {
        return proposals.length;
    }

    /// @notice Returns the number of voters for a proposal
    /// @param _proposalId Proposal identifier
    /// @return Voter count
    function getVoterCount(uint256 _proposalId) external view returns (uint256) {
        return votedUsers[_proposalId].length;
    }

    /// @notice Returns the voter at a given index for a proposal
    /// @param _proposalId Proposal identifier
    /// @param _index Voter index
    /// @return Voter address
    function getVoterAtIndex(uint256 _proposalId, uint256 _index) external view returns (address) {
        return votedUsers[_proposalId][_index];
    }

    /// @notice Returns the total yes votes for a proposal
    /// @param _proposalId Proposal identifier
    /// @return Yes vote total
    function getYes(uint256 _proposalId) external view returns (uint256) {
        return _voteTotals[_proposalId].yes;
    }

    /// @notice Returns the total no votes for a proposal
    /// @param _proposalId Proposal identifier
    /// @return No vote total
    function getNo(uint256 _proposalId) external view returns (uint256) {
        return _voteTotals[_proposalId].no;
    }

    /// @notice Returns the total votes cast for a proposal
    /// @param _proposalId Proposal identifier
    /// @return Total vote sum
    function voteTotals(uint256 _proposalId) external view returns (uint256) {
        return uint256(_voteTotals[_proposalId].yes) + uint256(_voteTotals[_proposalId].no);
    }

    /// @notice Returns vote details for a user on a proposal
    /// @param _proposalId Proposal identifier
    /// @param _user User address
    /// @return voted Whether user has voted
    /// @return yesWeight Yes weight allocation
    /// @return noWeight No weight allocation
    /// @return baseWeight User's base voting weight
    /// @return adjustedWeight User's adjusted weight
    function getVote(uint256 _proposalId, address _user) public view returns (
        bool voted, uint256 yesWeight, uint256 noWeight, uint256 baseWeight, int256 adjustedWeight
    ) {
        UserInfo storage u = userInfo[_proposalId][_user];
        voted = u.voteStatus > 0;
        yesWeight = u.yesWeight;
        noWeight = u.noWeight;
        baseWeight = u.baseWeight;
        adjustedWeight = u.adjustedWeight;
    }

    /// @notice Checks if a proposal is finalized (voting ended + finalization window)
    /// @param _proposalId Proposal identifier
    /// @return True if finalized
    function isFinalized(uint256 _proposalId) public view returns (bool) {
        return proposals[_proposalId].endTime > 0 && block.timestamp > proposals[_proposalId].endTime + finalizationTime;
    }

    /// @notice Checks if a proposal's voting period has ended
    /// @param _proposalId Proposal identifier
    /// @return True if voting has ended
    function isFinished(uint256 _proposalId) public view returns (bool) {
        return proposals[_proposalId].endTime > 0 && block.timestamp > proposals[_proposalId].endTime;
    }

    /// @notice Updates vote totals with a delta and yes/no distribution
    function _changeVoteTotals(uint256 _proposalId, int256 _delta, uint256 _yesWeight) internal {
        VoteTotals storage totals = _voteTotals[_proposalId];
        int256 yesDelta = _delta * int256(_yesWeight) / int256(max_weight);
        int256 noDelta = _delta - yesDelta;
        if (yesDelta >= 0) {
            totals.yes += uint128(uint256(yesDelta));
        } else {
            totals.yes -= uint128(uint256(-yesDelta));
        }
        if (noDelta >= 0) {
            totals.no += uint128(uint256(noDelta));
        } else {
            totals.no -= uint128(uint256(-noDelta));
        }
    }

    /// @notice Initializes base voting info for an account
    function _initBaseInfo(address _account, uint256 _proposalId) internal {
        UserInfo memory user = userInfo[_proposalId][_account];
        if (user.delegate != address(0)) return;

        uint256 epoch = proposals[_proposalId].epoch;

        uint256 baseWeight = vlCVX.balanceAtEpochOf(epoch, _account);
        address delegate = delegation.getDelegateAtEpoch(_account, epoch);

        if (delegate == address(0)) {
            delegate = _account;
        }

        if (delegate != _account) {
            uint256 delWeight = delegation.userWeightAtEpochOf(epoch, _account);
            uint256 truncatedBase = (baseWeight / WEIGHT_DIVISOR) * WEIGHT_DIVISOR;
            if (truncatedBase != delWeight) {
                delegation.syncAtEpoch(_account, epoch);
            }
        }

        uint256 totalDelWeight = delegation.balanceAtEpochOf(epoch, _account);

        user.baseWeight = uint96(baseWeight);
        user.delegate = delegate;
        user.adjustedWeight += int96(int256(totalDelWeight));
        user.totalDelegationWeight = uint96(totalDelWeight);

        userInfo[_proposalId][_account] = user;

        emit UserWeightChange(_proposalId, _account, baseWeight, user.adjustedWeight);

        if (delegate != _account) {
            UserInfo storage del = userInfo[_proposalId][delegate];

            if (del.voteStatus == 0) {
                del.adjustedWeight -= int96(int256(delegation.userWeightAtEpochOf(epoch, _account)));
            } else {
                uint256 currentDelWeight = delegation.userWeightAtEpochOf(epoch, _account);
                (uint256 snapWeight, uint256 snapNonce) = delegation.getSyncSnapshot(_account, epoch);
                int256 weightToRemove;

                if (snapNonce > 0 && snapNonce <= uint256(del.lastVoteSyncNonce)) {
                    weightToRemove = int256(currentDelWeight);
                } else if (snapNonce > 0) {
                    weightToRemove = int256(snapWeight);
                    int256 diff = int256(currentDelWeight) - int256(snapWeight);
                    if (diff > 0) {
                        pendingWeightAdjustment[_proposalId][delegate] -= int96(diff);
                        emit PendingWeightAdjustment(_proposalId, delegate, -diff);
                    }
                } else {
                    weightToRemove = int256(currentDelWeight);
                }

                _changeVoteTotals(_proposalId, -weightToRemove, del.yesWeight);
                del.adjustedWeight -= int96(weightToRemove);
                if (del.adjustedWeight < 0) revert DelegateOverSubtracted();
            }

            emit UserWeightChange(_proposalId, delegate, del.baseWeight, del.adjustedWeight);
        }
    }

    /// @notice Casts or updates a vote for an account on a specific proposal
    /// @param _proposalId Proposal identifier
    /// @param _account Account to vote for
    /// @param _yesWeight Yes weight allocation (0-10000)
    /// @param _noWeight No weight allocation (0-10000)
    function _vote(uint256 _proposalId, address _account, uint256 _yesWeight, uint256 _noWeight) internal {
        Proposal storage prop = proposals[_proposalId];
        if (block.timestamp < prop.startTime) revert NotStarted();
        if (block.timestamp > prop.endTime) revert Ended();
        if (_yesWeight + _noWeight != max_weight) revert MaxWeight();

        _initBaseInfo(_account, _proposalId);

        UserInfo storage user = userInfo[_proposalId][_account];

        if (user.voteStatus > 0) {
            int256 oldUserWeight = int256(uint256(user.baseWeight)) + int256(user.adjustedWeight);
            _changeVoteTotals(_proposalId, -oldUserWeight, user.yesWeight);

            uint256 currentBalance = vlCVX.balanceAtEpochOf(prop.epoch, _account);
            uint256 userBaseDiff = currentBalance - user.baseWeight;
            user.baseWeight = uint96(currentBalance);

            uint256 currentDelBal = delegation.balanceAtEpochOf(prop.epoch, _account);
            int256 delDelta = int256(currentDelBal) - int256(uint256(user.totalDelegationWeight));
            user.adjustedWeight += int96(delDelta);
            user.totalDelegationWeight = uint96(currentDelBal);

            if (userBaseDiff > 0 && user.delegate != address(0) && user.delegate != _account) {
                delegation.syncAtEpoch(_account, prop.epoch);

                uint256 currentDelWeight = delegation.userWeightAtEpochOf(prop.epoch, _account);
                (uint256 preSyncWeight, uint256 snapNonce) = delegation.getSyncSnapshot(_account, prop.epoch);
                int256 realDiff = int256(currentDelWeight) - int256(preSyncWeight);
                if (realDiff > 0) {
                    UserInfo storage del = userInfo[_proposalId][user.delegate];
                    if (del.voteStatus > 0) {
                        if (snapNonce > 0 && snapNonce <= uint256(del.lastVoteSyncNonce)) {
                            _changeVoteTotals(_proposalId, -realDiff, del.yesWeight);
                            del.adjustedWeight -= int96(realDiff);
                            if (del.adjustedWeight < 0) revert DelegateOverSubtracted();
                        } else {
                            pendingWeightAdjustment[_proposalId][user.delegate] -= int96(realDiff);
                            emit PendingWeightAdjustment(_proposalId, user.delegate, -realDiff);
                        }
                    } else {
                        del.adjustedWeight -= int96(realDiff);
                    }
                }
            }

            int96 pend = pendingWeightAdjustment[_proposalId][_account];
            if (pend != 0) {
                pendingWeightAdjustment[_proposalId][_account] = 0;
                user.adjustedWeight += pend;
            }

            emit UserWeightChange(_proposalId, _account, user.baseWeight, user.adjustedWeight);
        }

        int256 userWeight = int256(uint256(user.baseWeight)) + int256(user.adjustedWeight);
        if (userWeight <= 0) revert NoWeight();

        user.yesWeight = uint16(_yesWeight);
        user.noWeight = uint16(_noWeight);
        _changeVoteTotals(_proposalId, userWeight, _yesWeight);

        emit VoteCast(_proposalId, _account, _yesWeight, _noWeight);

        user.lastVoteSyncNonce = uint48(delegation.syncNonce());

        if (user.voteStatus == 0) {
            user.voteStatus = msg.sender == _account ? uint8(VoteStatus.Voted) : uint8(VoteStatus.VotedViaSurrogate);
            votedUsers[_proposalId].push(_account);
        }
    }

    /// @notice Casts or updates a vote on the latest proposal
    /// @param _account Account to vote for
    /// @param _yesWeight Yes weight allocation (0-10000)
    /// @param _noWeight No weight allocation (0-10000)
    function vote(uint256 _proposalId, address _account, uint256 _yesWeight, uint256 _noWeight) external onlyAcceptedSigner(_account) {

        uint8 vs = userInfo[_proposalId][_account].voteStatus;
        if (msg.sender != _account && vs >= uint8(VoteStatus.Voted)) revert NotVoteAuth();

        _vote(_proposalId, _account, _yesWeight, _noWeight);

        if (msg.sender == _account && vs == uint8(VoteStatus.VotedViaSurrogate)) {
            userInfo[_proposalId][_account].voteStatus = uint8(VoteStatus.Voted);
        }
    }

    /// @notice Creates a new DAO proposal
    /// @param _startTime Unix timestamp when voting begins
    /// @param _endTime Unix timestamp when voting ends
    /// @param _voteType Type of proposal (Ownership or Parameter)
    /// @param _proposalId External proposal identifier
    function createProposal(uint256 _startTime, uint256 _endTime, VoteType _voteType, uint256 _proposalId) public onlyOperator {
        if (_endTime <= _startTime) revert BadTime();
        if (_endTime <= block.timestamp) revert BadTime();
        uint256 votingStart = _startTime > block.timestamp ? _startTime : block.timestamp;
        uint256 votingDuration = _endTime - votingStart;
        if (votingDuration < MIN_PROPOSAL_DURATION) revert BadTime();
        if (votingDuration > MAX_PROPOSAL_DURATION) revert BadTime();

        vlCVX.checkpointEpoch();
        uint256 epoch = vlCVX.epochCount() - 2;
        (, uint32 epochStart) = vlCVX.epochs(epoch);
        while (epoch > 0 && uint256(epochStart) > _startTime) {
            unchecked { --epoch; }
            (, epochStart) = vlCVX.epochs(epoch);
        }

        proposals.push(Proposal({
            startTime: uint48(_startTime),
            endTime: uint48(_endTime),
            epoch: uint48(epoch),
            voteType: uint8(_voteType),
            proposalId: uint104(_proposalId)
        }));
        emit NewProposal(proposals.length - 1, _startTime, _endTime, _voteType);
    }

    /// @notice Forces a specific proposal to end immediately
    /// @param _proposalId Proposal identifier
    function forceEndProposal(uint256 _proposalId) public onlyOperator {
        if (proposals[_proposalId].startTime == 0) revert NotStarted();
        if (block.timestamp > proposals[_proposalId].endTime + finalizationTime) revert Ended();

        proposals[_proposalId].startTime = 0;
        proposals[_proposalId].endTime = 0;
        proposals[_proposalId].epoch = 0;
        emit ForceEndProposal(_proposalId);
    }

    /// @notice Sets an operator address
    /// @param _op Operator address
    /// @param _active True to add, false to remove
    function setOperator(address _op, bool _active) external onlyOwner {
        operators[_op] = _active;
        emit OperatorSet(_op, _active);
    }

    modifier onlyOperator() {
        if (!operators[msg.sender] && owner() != msg.sender) revert NotOperator();
        _;
    }

    modifier onlyAcceptedSigner(address _account) {
        if (msg.sender != _account && !surrogateRegistry.isSurrogate(msg.sender, _account)) revert NotSigner();
        _;
    }

    /// @notice Returns the contract version
    /// @return _major Major version
    /// @return _minor Minor version
    /// @return _patch Patch version
    function version() external pure returns (uint256 _major, uint256 _minor, uint256 _patch) {
        _major = 1;
        _minor = 0;
        _patch = 0;
    }
}

src/Delegation.sol

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

import "./interface/IvlCVX.sol";
import "openzeppelin-contracts/contracts/access/Ownable2Step.sol";

contract Delegation is Ownable2Step {
    string public name;
    IvlCVX public immutable vlCVX;
    uint32 public immutable epoch0Date;
    uint256 public constant FILL_EPOCHS = 16;
    uint256 public constant WEIGHT_DIVISOR = 1e17;
    uint256 public constant EPOCHS_PER_ENTRY = 8;
    uint256 public constant REWARDS_DURATION = 86400 * 7;
    uint256 public constant LOCK_DURATION = REWARDS_DURATION * 16;

    struct EpochWeightingEntry {
        uint32 w0;
        uint32 w1;
        uint32 w2;
        uint32 w3;
        uint32 w4;
        uint32 w5;
        uint32 w6;
        uint32 w7;
    }

    struct SetDelegateRecord {
        address delegate;
        uint32 startingEpoch;
    }

    struct SyncSnapshot {
        uint96 syncNonce;
        uint32 preSyncWeight;
        uint96 timestamp;
    }

    error NoDelegate();
    error SelfDelegation();
    error ExpiredLocks();
    error InitializationClosed();
    error ArrayLengthMismatch();

    event UserLocksGasLimitSet(uint256 userLocksGasLimit);

    bool public initializationComplete;

    uint256 public syncNonce;

    uint256 public userLocksGasLimit = 10_000;

    mapping(address => SetDelegateRecord[]) public delegateHistory;
    mapping(address => mapping(uint256 => EpochWeightingEntry)) public userEpochWeights;
    mapping(address => mapping(uint256 => EpochWeightingEntry)) public delegateEpochWeights;
    mapping(address => uint256) public syncedUserEpoch;
    mapping(address => mapping(uint256 => SyncSnapshot)) public syncSnapshots;

    /// @notice Creates a new Delegation contract
    /// @param _name Contract name identifier
    /// @param _owner Address of the contract owner
    /// @param _vlCVX Address of the vlCVX contract
    constructor(string memory _name, address _owner, address _vlCVX) Ownable(_owner) {
        name = _name;
        vlCVX = IvlCVX(_vlCVX);
        (, epoch0Date) = vlCVX.epochs(0);
    }

    /// @notice Seeds initial delegate assignments for multiple users
    /// @param _users Array of user addresses
    /// @param _delegates Array of delegate addresses
    function seedDelegates(address[] calldata _users, address[] calldata _delegates) external onlyOwner {
        if (initializationComplete) revert InitializationClosed();
        uint256 len = _users.length;
        if (len != _delegates.length) revert ArrayLengthMismatch();

        vlCVX.checkpointEpoch();
        uint256 nextEpoch = vlCVX.epochCount() - 1;
        uint256 gasLimit = userLocksGasLimit;

        for (uint256 i = 0; i < len;) {
            address user = _users[i];
            address delegate = _delegates[i];
            if (delegate == address(0)) revert NoDelegate();
            if (delegate == user) revert SelfDelegation();

            SetDelegateRecord[] storage history = delegateHistory[user];
            if (history.length != 0) {
                unchecked { ++i; }
                continue;
            }

            history.push(SetDelegateRecord({delegate: delegate, startingEpoch: uint32(nextEpoch)}));
            (uint112 locked, , uint32 nextUnlockIndex) = vlCVX.balances(user);
            if (locked > 0) {
                try vlCVX.userLocks{gas: gasLimit}(user, nextUnlockIndex) returns (
                    uint112 firstAmount, uint112, uint32 firstUnlockTime
                ) {
                    if (firstAmount > 0 && firstUnlockTime > block.timestamp) {
                        _syncUser(user, delegate, nextEpoch, FILL_EPOCHS);
                    }
                } catch {}
            }
            emit DelegateSet(user, delegate);
            unchecked { ++i; }
        }
    }

    /// @notice Marks initialization as complete, preventing further seeding
    function completeInitialization() external onlyOwner {
        initializationComplete = true;
        emit InitializationComplete();
    }

    /// @notice Sets gas forwarded to vlCVX userLocks probes
    function setUserLocksGasLimit(uint256 _userLocksGasLimit) external onlyOwner {
        userLocksGasLimit = _userLocksGasLimit;
        emit UserLocksGasLimitSet(_userLocksGasLimit);
    }

    /// @notice Sets or changes a delegate for the caller
    /// @param _delegate Delegate address to assign
    function setDelegate(address _delegate) external {
        if (_delegate == msg.sender) revert SelfDelegation();
        vlCVX.checkpointEpoch();
        uint256 nextEpoch = vlCVX.epochCount() - 1;

        SetDelegateRecord[] storage history = delegateHistory[msg.sender];
        address oldDelegate;
        uint256 len = history.length;

        if (len == 0) {
            history.push(SetDelegateRecord({
                delegate: _delegate,
                startingEpoch: uint32(nextEpoch)
            }));
        } else {
            SetDelegateRecord storage tail = history[len - 1];
            oldDelegate = tail.delegate;

            if (tail.startingEpoch == uint32(nextEpoch)) {
                tail.delegate = _delegate;
            } else {
                history.push(SetDelegateRecord({
                    delegate: _delegate,
                    startingEpoch: uint32(nextEpoch)
                }));
            }
        }

        if (oldDelegate != address(0) && oldDelegate != _delegate) {
            _removeUser(msg.sender, oldDelegate);
        }

        if (_delegate != address(0)) {
            _syncUser(msg.sender, _delegate, vlCVX.epochCount() - 1, FILL_EPOCHS);
        }

        emit DelegateSet(msg.sender, _delegate);
    }

    /// @notice Syncs a user's weight for future epochs
    /// @param _user User address to sync
    function sync(address _user) external {
        vlCVX.checkpointEpoch();
        uint256 currentEpoch = vlCVX.epochCount() - 2;

        SetDelegateRecord[] storage history = delegateHistory[_user];
        uint256 len = history.length;
        if (len == 0) return;

        address currentDelegate = _getDelegateAtEpoch(history, currentEpoch);
        address futureDelegate = history[len - 1].delegate;

        uint256 offset = currentEpoch & 7;
        uint256 entryIdx = currentEpoch >> 3;
        EpochWeightingEntry memory entry = userEpochWeights[_user][entryIdx];
        uint256 prePacked;
        assembly {
            prePacked := mload(add(entry, mul(offset, 32)))
        }

        if (currentDelegate != address(0)) {
            if (currentDelegate == futureDelegate) {
                _syncUser(_user, currentDelegate, currentEpoch, FILL_EPOCHS + 1);
            } else {
                _syncUser(_user, currentDelegate, currentEpoch, 1);
                if (futureDelegate != address(0)) {
                    _syncUser(_user, futureDelegate, vlCVX.epochCount() - 1, FILL_EPOCHS);
                }
            }
        } else if (futureDelegate != address(0)) {
            _syncUser(_user, futureDelegate, vlCVX.epochCount() - 1, FILL_EPOCHS);
        }

        entry = userEpochWeights[_user][entryIdx];
        uint256 postPacked;
        assembly {
            postPacked := mload(add(entry, mul(offset, 32)))
        }

        if (postPacked != prePacked) {
            syncSnapshots[_user][currentEpoch] = SyncSnapshot({
                preSyncWeight: uint32(prePacked),
                syncNonce: uint96(++syncNonce),
                timestamp: uint96(block.timestamp)
            });
        }
    }

    /// @notice Syncs a user's weight at a specific epoch
    /// @param _user User address to sync
    /// @param _epoch Epoch to sync at
    function syncAtEpoch(address _user, uint256 _epoch) external {
        if (_epoch >= vlCVX.epochCount() - 1) return;

        (uint112 _locked, , uint32 nextUnlockIndex) = vlCVX.balances(_user);
        if (_locked > 0) {
            (uint112 firstAmount, , uint32 firstUnlockTime) =
                vlCVX.userLocks{gas: userLocksGasLimit}(_user, nextUnlockIndex);
            if (firstAmount > 0 && firstUnlockTime <= block.timestamp) revert ExpiredLocks();
        }

        SetDelegateRecord[] storage history = delegateHistory[_user];
        uint256 len = history.length;
        if (len == 0) return;

        address delegate = _getDelegateAtEpoch(history, _epoch);
        if (delegate == address(0)) return;

        uint256 offset = _epoch & 7;
        uint256 entryIdx = _epoch >> 3;
        EpochWeightingEntry memory userEntry = userEpochWeights[_user][entryIdx];
        uint256 prePacked;
        assembly {
            prePacked := mload(add(userEntry, mul(offset, 32)))
        }

        if (syncSnapshots[_user][_epoch].syncNonce != 0) return;

        uint256 newWeight = vlCVX.balanceAtEpochOf(_epoch, _user);
        uint256 newPacked = newWeight / WEIGHT_DIVISOR;

        syncSnapshots[_user][_epoch] = SyncSnapshot({
            preSyncWeight: uint32(prePacked),
            syncNonce: uint96(++syncNonce),
            timestamp: uint96(block.timestamp)
        });

        if (newPacked == prePacked) return;

        EpochWeightingEntry memory delegateEntry = delegateEpochWeights[delegate][entryIdx];
        unchecked {
            uint256 delta = newPacked - prePacked;
            assembly {
                mstore(add(delegateEntry, mul(offset, 32)), add(mload(add(delegateEntry, mul(offset, 32))), delta))
            }
        }
        assembly {
            mstore(add(userEntry, mul(offset, 32)), newPacked)
        }

        userEpochWeights[_user][entryIdx] = userEntry;
        delegateEpochWeights[delegate][entryIdx] = delegateEntry;

        emit Synced(_user, delegate);
    }

    /// @notice Returns the delegate for a user at a given epoch
    /// @param _user User address
    /// @param _epoch Epoch to query
    /// @return Delegate address at that epoch
    function getDelegateAtEpoch(address _user, uint256 _epoch) external view returns (address) {
        SetDelegateRecord[] storage history = delegateHistory[_user];
        return _getDelegateAtEpoch(history, _epoch);
    }

    /// @notice Finds the delegate for a user at a given epoch from history
    function _getDelegateAtEpoch(SetDelegateRecord[] storage history, uint256 _epoch) internal view returns (address) {
        uint256 len = history.length;
        for (uint256 i = len; i > 0;) {
            unchecked { --i; }
            if (history[i].startingEpoch <= _epoch) {
                return history[i].delegate;
            }
        }
        return address(0);
    }

    /// @notice Syncs a user's weight to a delegate across a range of epochs
    function _syncUser(address _user, address _delegate, uint256 _startEpoch, uint256 _numEpochs) internal {
        uint256 endEpoch;
        unchecked { endEpoch = _startEpoch + _numEpochs; }

        (uint112 _locked, , uint32 nextUnlockIndex) = vlCVX.balances(_user);
        uint256 gasLimit = userLocksGasLimit;

        uint256[17] memory epochWeights;

        if (_locked > 0) {
            for (uint256 i = nextUnlockIndex; i < nextUnlockIndex + 17;) {
                uint112 lockBoosted;
                uint32 unlockTime;
                try vlCVX.userLocks{gas: gasLimit}(_user, i) returns (
                    uint112 _amount, uint112 _boosted, uint32 _lockUnlockTime
                ) {
                    if (_amount > 0 && _lockUnlockTime <= block.timestamp) revert ExpiredLocks();
                    lockBoosted = _boosted;
                    unlockTime = _lockUnlockTime;
                } catch {
                    break;
                }

                uint256 _lockBoosted = uint256(lockBoosted);
                uint256 _unlockTime = uint256(unlockTime);
                uint256 lockEpochTime = _unlockTime - LOCK_DURATION;

                uint256 firstContrib = (lockEpochTime - uint256(epoch0Date)) / REWARDS_DURATION;
                uint256 lastContrib = (_unlockTime - uint256(epoch0Date)) / REWARDS_DURATION - 1;

                if (lastContrib < _startEpoch) {
                    unchecked { ++i; }
                    continue;
                }
                if (firstContrib >= endEpoch) break;

                uint256 eStart = firstContrib > _startEpoch ? firstContrib : _startEpoch;
                uint256 eEnd = lastContrib < endEpoch - 1 ? lastContrib : endEpoch - 1;

                for (uint256 e = eStart; e <= eEnd;) {
                    epochWeights[e - _startEpoch] += _lockBoosted;
                    unchecked { ++e; }
                }

                unchecked { ++i; }
            }
        }

        uint256 startEntry = _startEpoch >> 3;
        uint256 endEntry = (endEpoch - 1) >> 3;

        for (uint256 entryIdx = startEntry; entryIdx <= endEntry;) {
            EpochWeightingEntry memory userEntry = userEpochWeights[_user][entryIdx];
            EpochWeightingEntry memory delegateEntry = delegateEpochWeights[_delegate][entryIdx];

            uint256 entryStartEpoch;
            uint256 entryEndEpoch;
            unchecked {
                entryStartEpoch = entryIdx << 3;
                entryEndEpoch = entryStartEpoch + EPOCHS_PER_ENTRY;
            }

            uint256 loopStart = _startEpoch > entryStartEpoch ? _startEpoch : entryStartEpoch;
            uint256 loopEnd = endEpoch < entryEndEpoch ? endEpoch : entryEndEpoch;

            for (uint256 epoch = loopStart; epoch < loopEnd;) {
                uint256 newWeight = epochWeights[epoch - _startEpoch];
                uint256 offset = epoch & 7;
                uint256 oldWeightPacked;
                uint256 delegateSlot;
                assembly {
                    oldWeightPacked := mload(add(userEntry, mul(offset, 32)))
                    delegateSlot := add(delegateEntry, mul(offset, 32))
                }
                uint256 newWeightPacked = newWeight / WEIGHT_DIVISOR;
                unchecked {
                    uint256 delta = newWeightPacked - oldWeightPacked;
                    assembly {
                        mstore(delegateSlot, add(mload(delegateSlot), delta))
                    }
                }
                assembly {
                    mstore(add(userEntry, mul(offset, 32)), newWeightPacked)
                }
                unchecked { ++epoch; }
            }

            userEpochWeights[_user][entryIdx] = userEntry;
            delegateEpochWeights[_delegate][entryIdx] = delegateEntry;
            unchecked { ++entryIdx; }
        }

        syncedUserEpoch[_user] = endEpoch;

        emit Synced(_user, _delegate);
    }

    /// @notice Removes a user's weight from a delegate's totals
    function _removeUser(address _user, address _delegate) internal {
        uint256 nextEpoch = vlCVX.epochCount() - 1;
        uint256 endEpoch = syncedUserEpoch[_user];

        if (endEpoch <= nextEpoch) {
            syncedUserEpoch[_user] = 0;
            return;
        }

        uint256 startEntry = nextEpoch >> 3;
        uint256 endEntry = (endEpoch - 1) >> 3;

        for (uint256 entryIdx = startEntry; entryIdx <= endEntry;) {
            EpochWeightingEntry memory userEntry = userEpochWeights[_user][entryIdx];
            EpochWeightingEntry memory delegateEntry = delegateEpochWeights[_delegate][entryIdx];

            uint256 entryStartEpoch;
            uint256 entryEndEpoch;
            unchecked {
                entryStartEpoch = entryIdx << 3;
                entryEndEpoch = entryStartEpoch + EPOCHS_PER_ENTRY;
            }

            uint256 loopStart = nextEpoch > entryStartEpoch ? nextEpoch : entryStartEpoch;
            uint256 loopEnd = endEpoch < entryEndEpoch ? endEpoch : entryEndEpoch;

            for (uint256 epoch = loopStart; epoch < loopEnd;) {
                uint256 offset = epoch & 7;
                uint256 weight;
                uint256 delegateSlot;
                assembly {
                    weight := mload(add(userEntry, mul(offset, 32)))
                    delegateSlot := add(delegateEntry, mul(offset, 32))
                }
                assembly {
                    mstore(delegateSlot, sub(mload(delegateSlot), weight))
                }
                assembly {
                    mstore(add(userEntry, mul(offset, 32)), 0)
                }
                unchecked { ++epoch; }
            }

            delegateEpochWeights[_delegate][entryIdx] = delegateEntry;
            userEpochWeights[_user][entryIdx] = userEntry;
            unchecked { ++entryIdx; }
        }

        syncedUserEpoch[_user] = 0;
    }

    /// @notice Returns the current weight of a delegate
    /// @param _delegate Delegate address
    /// @return Current delegated weight
    function balanceOf(address _delegate) external view returns (uint256) {
        uint256 currentEpoch = vlCVX.findEpochId(block.timestamp);
        return _readMemWeight(delegateEpochWeights[_delegate][currentEpoch >> 3], currentEpoch & 7);
    }

    /// @notice Returns a delegate's weight at a specific epoch
    /// @param _epoch Epoch to query
    /// @param _delegate Delegate address
    /// @return Delegated weight at that epoch
    function balanceAtEpochOf(uint256 _epoch, address _delegate) external view returns (uint256) {
        return _readMemWeight(delegateEpochWeights[_delegate][_epoch >> 3], _epoch & 7);
    }

    /// @notice Returns a user's own weight at the current epoch
    /// @param _user User address
    /// @return User's weight
    function getUserWeight(address _user) external view returns (uint256) {
        uint256 currentEpoch = vlCVX.findEpochId(block.timestamp);
        return _readMemWeight(userEpochWeights[_user][currentEpoch >> 3], currentEpoch & 7);
    }

    /// @notice Returns a user's weight at a specific epoch
    /// @param _epoch Epoch to query
    /// @param _user User address
    /// @return User's weight at that epoch
    function userWeightAtEpochOf(uint256 _epoch, address _user) external view returns (uint256) {
        return _readMemWeight(userEpochWeights[_user][_epoch >> 3], _epoch & 7);
    }

    /// @notice Returns the sync snapshot for a user at an epoch
    /// @param _user User address
    /// @param _epoch Epoch to query
    /// @return preSyncWeight Weight before sync
    /// @return snapshotNonce Monotonic nonce at time of snapshot
    function getSyncSnapshot(address _user, uint256 _epoch) external view returns (uint256 preSyncWeight, uint256 snapshotNonce) {
        SyncSnapshot memory snap = syncSnapshots[_user][_epoch];
        return (uint256(snap.preSyncWeight) * WEIGHT_DIVISOR, uint256(snap.syncNonce));
    }

    /// @notice Reads a packed weight from an epoch weighting entry
    function _readMemWeight(EpochWeightingEntry memory entry, uint256 offset) internal pure returns (uint256) {
        uint256 raw;
        assembly {
            raw := mload(add(entry, mul(offset, 32)))
        }
        return raw * WEIGHT_DIVISOR;
    }

    /// @notice Returns the current epoch count from vlCVX
    /// @return Current epoch count
    function epochCount() external view returns (uint256) {
        return vlCVX.epochCount();
    }

    event DelegateSet(address indexed user, address indexed delegate);
    event Synced(address indexed user, address indexed delegate);
    event InitializationComplete();

    /// @notice Returns the contract version
    /// @return _major Major version
    /// @return _minor Minor version
    /// @return _patch Patch version
    function version() external pure returns (uint256 _major, uint256 _minor, uint256 _patch) {
        _major = 1;
        _minor = 0;
        _patch = 0;
    }
}

src/SurrogateRegistry.sol

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


contract SurrogateRegistry {
    string public name;

    /// @notice Creates a new SurrogateRegistry contract
    /// @param _name Contract name identifier
    constructor(string memory _name) {
        name = _name;
    }

    struct Info {
        address surrogate;
        uint32 timestamp;
    }

    mapping(address => Info) public surrogateInfo;

    event SurrogateSet(address indexed account, address indexed surrogate);

    /// @notice Checks if an address is the surrogate for an account
    /// @param _surrogate Address to check
    /// @param _account Account to check against
    /// @return True if surrogate matches account
    function isSurrogate(address _surrogate, address _account) external view returns (bool) {
        return surrogateInfo[_account].surrogate == _surrogate;
    }

    /// @notice Sets the surrogate address for the caller
    /// @param _surrogate Address to set as surrogate
    function setSurrogate(address _surrogate) external {
        surrogateInfo[msg.sender] = Info({
            surrogate: _surrogate,
            timestamp: uint32(block.timestamp)
        });
        emit SurrogateSet(msg.sender, _surrogate);
    }

    /// @notice Returns the contract version
    /// @return _major Major version
    /// @return _minor Minor version
    /// @return _patch Patch version
    function version() external pure returns (uint256 _major, uint256 _minor, uint256 _patch) {
        _major = 1;
        _minor = 0;
        _patch = 0;
    }
}

src/interface/IvlCVX.sol

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

interface IvlCVX {
    struct Reward {
        bool useBoost;
        uint40 periodFinish;
        uint208 rewardRate;
        uint40 lastUpdateTime;
        uint208 rewardPerTokenStored;
    }

    struct Balances {
        uint112 locked;
        uint112 boosted;
        uint32 nextUnlockIndex;
    }

    struct LockedBalance {
        uint112 amount;
        uint112 boosted;
        uint32 unlockTime;
    }

    struct EarnedData {
        address token;
        uint256 amount;
    }

    struct Epoch {
        uint224 supply;
        uint32 date;
    }

    /* ========== STATE VARIABLES ========== */

    function stakingToken() external view returns (address);
    function cvxCrv() external view returns (address);
    function rewardTokens(uint256 index) external view returns (address);
    function rewardsDuration() external view returns (uint256);
    function lockDuration() external view returns (uint256);
    function rewardDistributors(address _rewardsToken, address _distributor) external view returns (bool);
    function userRewardPerTokenPaid(address _user, address _rewardsToken) external view returns (uint256);
    function rewards(address _user, address _rewardsToken) external view returns (uint256);
    function lockedSupply() external view returns (uint256);
    function boostedSupply() external view returns (uint256);
    function epochs(uint256 index) external view returns (uint224 supply, uint32 date);
    function balances(address _user) external view returns (uint112 locked, uint112 boosted, uint32 nextUnlockIndex);
    function userLocks(address _user, uint256 index) external view returns (uint112 amount, uint112 boosted, uint32 unlockTime);
    function boostPayment() external view returns (address);
    function maximumBoostPayment() external view returns (uint256);
    function boostRate() external view returns (uint256);
    function nextMaximumBoostPayment() external view returns (uint256);
    function nextBoostRate() external view returns (uint256);
    function denominator() external view returns (uint256);
    function minimumStake() external view returns (uint256);
    function maximumStake() external view returns (uint256);
    function stakingProxy() external view returns (address);
    function cvxcrvStaking() external view returns (address);
    function stakeOffsetOnLock() external view returns (uint256);
    function kickRewardPerEpoch() external view returns (uint256);
    function kickRewardEpochDelay() external view returns (uint256);
    function isShutdown() external view returns (bool);

    /* ========== ERC20-LIKE INTERFACE ========== */

    function decimals() external view returns (uint8);
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function version() external view returns (uint256);

    /* ========== ADMIN CONFIGURATION ========== */

    function addReward(address _rewardsToken, address _distributor, bool _useBoost) external;
    function approveRewardDistributor(address _rewardsToken, address _distributor, bool _approved) external;
    function setStakingContract(address _staking) external;
    function setStakeLimits(uint256 _minimum, uint256 _maximum) external;
    function setBoost(uint256 _max, uint256 _rate, address _receivingAddress) external;
    function setKickIncentive(uint256 _rate, uint256 _delay) external;
    function shutdown() external;
    function setApprovals() external;

    /* ========== VIEWS ========== */

    function lastTimeRewardApplicable(address _rewardsToken) external view returns (uint256);
    function rewardPerToken(address _rewardsToken) external view returns (uint256);
    function getRewardForDuration(address _rewardsToken) external view returns (uint256);
    function claimableRewards(address _account) external view returns (EarnedData[] memory userRewards);
    function rewardWeightOf(address _user) external view returns (uint256 amount);
    function lockedBalanceOf(address _user) external view returns (uint256 amount);
    function balanceOf(address _user) external view returns (uint256 amount);
    function balanceAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount);
    function pendingLockOf(address _user) external view returns (uint256 amount);
    function pendingLockAtEpochOf(uint256 _epoch, address _user) external view returns (uint256 amount);
    function totalSupply() external view returns (uint256 supply);
    function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply);
    function findEpochId(uint256 _time) external view returns (uint256 epoch);
    function lockedBalances(address _user) external view returns (uint256 total, uint256 unlockable, uint256 locked, LockedBalance[] memory lockData);
    function epochCount() external view returns (uint256);

    /* ========== MUTATIVE FUNCTIONS ========== */

    function checkpointEpoch() external;
    function lock(address _account, uint256 _amount, uint256 _spendRatio) external;
    function withdrawExpiredLocksTo(address _withdrawTo) external;
    function processExpiredLocks(bool _relock) external;
    function kickExpiredLocks(address _account) external;
    function getReward(address _account, bool _stake) external;
    function getReward(address _account) external;

    /* ========== RESTRICTED FUNCTIONS ========== */

    function notifyRewardAmount(address _rewardsToken, uint256 _reward) external;
    function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external;

    /* ========== EVENTS ========== */

    event RewardAdded(address indexed _token, uint256 _reward);
    event Staked(address indexed _user, uint256 indexed _epoch, uint256 _paidAmount, uint256 _lockedAmount, uint256 _boostedAmount);
    event Withdrawn(address indexed _user, uint256 _amount, bool _relocked);
    event KickReward(address indexed _user, address indexed _kicked, uint256 _reward);
    event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward);
    event Recovered(address _token, uint256 _amount);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.