Skip to content
Verified contractExactMIT

TakeoverGovernor

Address0x3cab70d288f2afd2b4c5dc65cafb87fe6102ab42
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,359,872
Creation transaction
0xd333624651…e3eb5f9a51

src/TakeoverGovernor.sol

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

import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {IVotes} from "@openzeppelin/contracts/governance/utils/IVotes.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";

import {ITakeoverGovernor} from "./interfaces/ITakeoverGovernor.sol";
import {ITokenProfileRegistry} from "./interfaces/ITokenProfileRegistry.sol";
import {IBallotGovernor, IVotingScheme} from "./interfaces/IVotingScheme.sol";
import {HoldWeightLib} from "./libraries/HoldWeightLib.sol";

/// @title TakeoverGovernor
/// @notice Lets a token's holders replace the controller of its profile. A proposal is a
///         two-option poll (AGAINST / FOR) on the pluggable voting scheme; a voter's weight is
///         their lowest vote checkpoint over the whole lookback `[snapshot - lookback, snapshot]`,
///         in whole tokens, so voting power cannot be bought or borrowed just for the vote.
/// @dev Timing, quorum and scheme are captured per proposal when it is created, so parameter or
///      scheme changes never affect proposals already running. Quorum and the proposal threshold
///      are fractions of the circulating supply at the snapshot: the total supply minus the votes
///      of the Uniswap PoolManager, whose (self-delegated) balance can never vote. Any number of
///      proposals may run for a token at once, so no proposer can lock others out; each proposer
///      has at most one pending (active, closing or awaiting execution) proposal per token and a
///      cooldown between their own proposals. Executing a proposal supersedes every other
///      proposal of the token created before it, so a stale vote can never be executed over a
///      newer outcome. Supersession is tracked per execution through this governor rather than
///      by comparing controllers, so an incumbent cannot void running proposals by handing the
///      profile to another of their own accounts.
contract TakeoverGovernor is ITakeoverGovernor, IBallotGovernor, Ownable2Step {
    /// @inheritdoc ITakeoverGovernor
    uint8 public constant AGAINST = 0;
    /// @inheritdoc ITakeoverGovernor
    uint8 public constant FOR = 1;

    uint32 public constant MIN_PERIOD = 5 minutes;
    uint32 public constant MAX_PERIOD = 30 days;
    /// @notice Shortest execution window: leaves time for the tally's decryption pipeline.
    uint32 public constant MIN_EXECUTION_WINDOW = 5 minutes;
    uint32 public constant MAX_COOLDOWN = 90 days;
    uint32 public constant MAX_TOKEN_AGE = 90 days;
    uint32 public constant MIN_LOOKBACK = 5 minutes;
    uint32 public constant MAX_LOOKBACK = 90 days;
    uint16 public constant MIN_QUORUM_BPS = 50;
    uint16 public constant MAX_QUORUM_BPS = 5000;
    /// @notice Lowest proposal threshold: proposing always takes a stake in the token.
    uint16 public constant MIN_PROPOSAL_THRESHOLD_BPS = 1;
    /// @notice Oldest snapshot `proposeAt` accepts.
    uint32 public constant MAX_SNAPSHOT_AGE = 1 days;

    uint8 private constant _OPTION_COUNT = 2;
    uint256 private constant _BPS = 10_000;
    /// @dev No proposal can be pending this long after its start (voting + execution window).
    uint256 private constant _PENDING_HORIZON = uint256(MAX_PERIOD) * 2;

    ITokenProfileRegistry private immutable _registry;
    address private immutable _poolManager;
    IVotingScheme private _scheme;
    Params private _params;
    uint256 private _proposalCount;

    mapping(uint256 proposalId => Proposal) private _proposals;
    mapping(uint256 proposalId => IVotingScheme) private _schemeOf;
    mapping(uint256 proposalId => bool) private _closed;
    mapping(uint256 proposalId => mapping(address voter => bool)) private _voted;
    /// @dev Executions of the token at the time the proposal was created.
    mapping(uint256 proposalId => uint256) private _generationOf;

    mapping(address token => uint256[]) private _proposalsOf;
    mapping(address token => uint256) private _executions;

    /// @inheritdoc ITakeoverGovernor
    mapping(address token => uint256) public lastProposalEnd;
    /// @inheritdoc ITakeoverGovernor
    mapping(address token => mapping(address proposer => uint256)) public latestProposalOf;
    /// @inheritdoc ITakeoverGovernor
    mapping(address token => mapping(address proposer => uint256)) public cooldownAnchorOf;
    /// @dev Hold-window scans run ahead of a ballot (`advanceHoldScan`).
    mapping(bytes32 window => HoldWeightLib.Scan) private _holdScans;

    /// @param initialOwner Admin allowed to change parameters and the scheme, and to cancel
    ///        active proposals.
    /// @param registry_ Token profile registry whose controllers are replaced.
    /// @param scheme_ Initial voting scheme.
    /// @param params_ Initial parameters.
    /// @param poolManager_ Uniswap v4 PoolManager, whose votes are excluded from the circulating
    ///        supply.
    constructor(
        address initialOwner,
        ITokenProfileRegistry registry_,
        IVotingScheme scheme_,
        Params memory params_,
        address poolManager_
    ) Ownable(initialOwner) {
        if (
            address(registry_) == address(0) || address(scheme_) == address(0)
                || poolManager_ == address(0)
        ) revert ZeroAddress();
        _registry = registry_;
        _scheme = scheme_;
        _poolManager = poolManager_;
        _setParams(params_);
    }

    // ------------------------------------------------------------------ admin

    /// @inheritdoc ITakeoverGovernor
    function setParams(Params calldata params_) external onlyOwner {
        _setParams(params_);
    }

    /// @inheritdoc ITakeoverGovernor
    function setScheme(address scheme_) external onlyOwner {
        if (scheme_ == address(0)) revert ZeroAddress();
        _scheme = IVotingScheme(scheme_);
        emit SchemeUpdated(scheme_);
    }

    // ------------------------------------------------------------------ lifecycle

    /// @inheritdoc ITakeoverGovernor
    function propose(address token, address newController) external returns (uint256 proposalId) {
        return _propose(token, newController, SafeCast.toUint48(block.timestamp - 1));
    }

    /// @inheritdoc ITakeoverGovernor
    function proposeAt(address token, address newController, uint48 snapshot)
        external
        returns (uint256 proposalId)
    {
        // forge-lint: disable-next-line(block-timestamp)
        if (snapshot >= block.timestamp || uint256(snapshot) + MAX_SNAPSHOT_AGE < block.timestamp) {
            revert InvalidSnapshot(snapshot);
        }
        return _propose(token, newController, snapshot);
    }

    function _propose(address token, address newController, uint48 snapshot)
        private
        returns (uint256 proposalId)
    {
        if (!_registry.isRegistered(token)) revert TokenNotRegistered(token);
        Params memory p = _params;

        uint256 eligibleAt = uint256(_registry.registeredAtOf(token)) + p.minTokenAge;
        // forge-lint: disable-next-line(block-timestamp)
        if (block.timestamp < eligibleAt) revert TokenTooYoung(token, eligibleAt);

        uint256 previous = latestProposalOf[token][msg.sender];
        if (previous != 0 && _isPending(state(previous))) {
            revert ProposalPending(token, previous);
        }

        uint256 anchor = cooldownAnchorOf[token][msg.sender];
        // forge-lint: disable-next-line(block-timestamp)
        if (anchor != 0 && block.timestamp < anchor + p.cooldown) {
            revert CooldownActive(token, anchor + p.cooldown);
        }

        if (newController == address(0) || newController == _registry.controllerOf(token)) {
            revert InvalidNewController(newController);
        }

        uint48 lookbackSnapshot = snapshot - p.lookback;
        uint64 circulatingWeight = _circulatingAt(token, snapshot);
        uint64 weight = _weightAt(token, msg.sender, snapshot, lookbackSnapshot);
        uint64 required =
            SafeCast.toUint64(uint256(circulatingWeight) * p.proposalThresholdBps / _BPS);
        // At least one whole token, even when a small circulating supply rounds the threshold
        // down to zero: an account without voting weight can never propose.
        if (required == 0) required = 1;
        if (weight < required) revert BelowProposalThreshold(weight, required);
        uint64 quorumWeight = SafeCast.toUint64(uint256(circulatingWeight) * p.quorumBps / _BPS);

        uint48 start = SafeCast.toUint48(block.timestamp);
        uint48 end = start + p.votingPeriod;
        uint48 executionDeadline = end + p.executionWindow;

        proposalId = ++_proposalCount;
        _proposals[proposalId] = Proposal({
            token: token,
            proposer: msg.sender,
            newController: newController,
            start: start,
            end: end,
            executionDeadline: executionDeadline,
            snapshot: snapshot,
            executed: false,
            canceled: false,
            quorumWeight: quorumWeight,
            forWeight: 0,
            againstWeight: 0,
            tallied: false,
            lookbackSnapshot: lookbackSnapshot,
            circulatingWeight: circulatingWeight
        });
        _schemeOf[proposalId] = _scheme;
        _generationOf[proposalId] = _executions[token];
        _proposalsOf[token].push(proposalId);
        lastProposalEnd[token] = end;
        latestProposalOf[token][msg.sender] = proposalId;
        cooldownAnchorOf[token][msg.sender] = end;

        _scheme.open(token, proposalId, _OPTION_COUNT);
        emit TakeoverProposed(
            token, proposalId, msg.sender, newController, start, end, quorumWeight
        );
    }

    /// @inheritdoc IBallotGovernor
    /// @dev Called by the proposal's scheme while the voter's `castBallot` transaction executes.
    function authorizeBallot(address token, uint256 scope, address voter, bytes32 ballotRef)
        external
        returns (uint64 weight)
    {
        Proposal storage p = _proposals[scope];
        if (p.token == address(0)) revert UnknownProposal(scope);
        if (msg.sender != address(_schemeOf[scope])) revert NotScheme(msg.sender);
        if (token != p.token) revert InvalidVote();
        if (state(scope) != State.Active) revert VotingClosed(scope);
        if (_voted[scope][voter]) revert AlreadyVoted(voter);

        weight = _weightAt(token, voter, p.snapshot, p.lookbackSnapshot);
        if (weight == 0) revert InvalidVote();

        _voted[scope][voter] = true;
        emit TakeoverVoteCast(token, scope, ballotRef);
    }

    /// @inheritdoc ITakeoverGovernor
    function closeProposal(uint256 proposalId) external {
        State s = state(proposalId);
        if (s == State.None) revert UnknownProposal(proposalId);
        if (s == State.Active) revert VotingNotEnded(proposalId);
        if (_closed[proposalId]) revert AlreadyClosed(proposalId);
        if (s != State.Closing) revert NotClosable(proposalId, s);

        Proposal storage p = _proposals[proposalId];
        _closed[proposalId] = true;
        _schemeOf[proposalId].requestTally(p.token, proposalId);
        emit TakeoverClosed(p.token, proposalId);
    }

    /// @inheritdoc ITakeoverGovernor
    function recordTally(uint256 proposalId) external {
        Proposal storage p = _proposals[proposalId];
        if (p.token == address(0)) revert UnknownProposal(proposalId);
        if (!_closed[proposalId]) revert NotClosed(proposalId);
        if (p.tallied) revert AlreadyTallied(proposalId);

        (bool isFinal, uint64[] memory counts) =
            _schemeOf[proposalId].tallyOf(address(this), p.token, proposalId);
        if (!isFinal || counts.length != _OPTION_COUNT) revert TallyNotFinal(proposalId);

        p.forWeight = counts[FOR];
        p.againstWeight = counts[AGAINST];
        p.tallied = true;
        emit TakeoverTallied(p.token, proposalId, counts[FOR], counts[AGAINST]);
    }

    /// @inheritdoc ITakeoverGovernor
    function execute(uint256 proposalId) external {
        State s = state(proposalId);
        if (s == State.None) revert UnknownProposal(proposalId);
        if (s != State.Succeeded) revert NotExecutable(proposalId, s);

        Proposal storage p = _proposals[proposalId];
        address token = p.token;
        p.executed = true;
        // Every other proposal of the token created before now becomes Superseded.
        unchecked {
            ++_executions[token];
        }
        _registry.setController(token, p.newController);
        emit TakeoverExecuted(token, proposalId, p.newController);
        emit TakeoverSuperseded(token, proposalId);
    }

    /// @inheritdoc ITakeoverGovernor
    /// @dev Only while voting is open: once the vote has ended no one, the owner included, can
    ///      stop its outcome.
    function cancel(uint256 proposalId) external {
        State s = state(proposalId);
        if (s == State.None) revert UnknownProposal(proposalId);
        Proposal storage p = _proposals[proposalId];
        if (msg.sender != p.proposer && msg.sender != owner()) revert NotProposer();
        if (s != State.Active) revert NotCancelable(proposalId, s);
        p.canceled = true;
        // The proposer's cooldown restarts now rather than at the planned end.
        cooldownAnchorOf[p.token][p.proposer] = block.timestamp;
        emit TakeoverCanceled(p.token, proposalId);
    }

    // ------------------------------------------------------------------ views

    /// @inheritdoc ITakeoverGovernor
    function state(uint256 proposalId) public view returns (State) {
        Proposal storage p = _proposals[proposalId];
        if (p.token == address(0)) return State.None;
        if (p.canceled) return State.Canceled;
        if (p.executed) return State.Executed;
        // forge-lint: disable-next-line(block-timestamp)
        bool pastDeadline = block.timestamp > p.executionDeadline;
        State s;
        if (p.tallied) {
            bool passed = p.forWeight >= p.quorumWeight && p.forWeight > p.againstWeight;
            if (!passed) return State.Defeated;
            if (pastDeadline) return State.Expired;
            s = State.Succeeded;
        } else {
            // forge-lint: disable-next-line(block-timestamp)
            if (block.timestamp <= p.end && !_closed[proposalId]) s = State.Active;
            else if (pastDeadline) return State.Expired;
            else s = State.Closing;
        }
        // Still pending, but another proposal of the token was executed after this one was made.
        if (_generationOf[proposalId] != _executions[p.token]) return State.Superseded;
        return s;
    }

    /// @inheritdoc ITakeoverGovernor
    function activeProposalOf(address token) external view returns (uint256) {
        uint256[] storage ids = _proposalsOf[token];
        for (uint256 i = ids.length; i != 0; --i) {
            uint256 id = ids[i - 1];
            if (_pastHorizon(id)) break;
            if (_isPending(state(id))) return id;
        }
        return 0;
    }

    /// @inheritdoc ITakeoverGovernor
    function activeProposalsOf(address token) external view returns (uint256[] memory active) {
        uint256[] storage ids = _proposalsOf[token];
        uint256 n = ids.length;
        uint256 count;
        active = new uint256[](n);
        for (uint256 i = n; i != 0; --i) {
            uint256 id = ids[i - 1];
            if (_pastHorizon(id)) break;
            if (_isPending(state(id))) active[count++] = id;
        }
        // Shrink the array to the entries written.
        assembly ("memory-safe") {
            mstore(active, count)
        }
    }

    /// @inheritdoc ITakeoverGovernor
    function proposalsOf(address token) external view returns (uint256[] memory) {
        return _proposalsOf[token];
    }

    /// @inheritdoc ITakeoverGovernor
    function poolManager() external view returns (address) {
        return _poolManager;
    }

    /// @inheritdoc ITakeoverGovernor
    function getProposal(uint256 proposalId) external view returns (Proposal memory) {
        return _proposals[proposalId];
    }

    /// @inheritdoc ITakeoverGovernor
    function proposalCount() external view returns (uint256) {
        return _proposalCount;
    }

    /// @inheritdoc ITakeoverGovernor
    function params() external view returns (Params memory) {
        return _params;
    }

    /// @inheritdoc ITakeoverGovernor
    function scheme() external view returns (address) {
        return address(_scheme);
    }

    /// @inheritdoc ITakeoverGovernor
    function registry() external view returns (address) {
        return address(_registry);
    }

    /// @inheritdoc ITakeoverGovernor
    function proposalScheme(uint256 proposalId) external view returns (address) {
        return address(_schemeOf[proposalId]);
    }

    /// @inheritdoc ITakeoverGovernor
    function isClosed(uint256 proposalId) external view returns (bool) {
        return _closed[proposalId];
    }

    /// @inheritdoc ITakeoverGovernor
    function hasVoted(uint256 proposalId, address voter) external view returns (bool) {
        return _voted[proposalId][voter];
    }

    /// @inheritdoc ITakeoverGovernor
    function weightOf(uint256 proposalId, address account) external view returns (uint64) {
        Proposal storage p = _proposals[proposalId];
        if (p.token == address(0)) return 0;
        return _weightAt(p.token, account, p.snapshot, p.lookbackSnapshot);
    }

    /// @inheritdoc ITakeoverGovernor
    function advanceHoldScan(uint256 proposalId, address account, uint256 maxReads)
        external
        returns (bool done)
    {
        Proposal storage p = _proposals[proposalId];
        if (p.token == address(0)) revert UnknownProposal(proposalId);
        return HoldWeightLib.advance(
            _holdScans, p.token, account, p.lookbackSnapshot, p.snapshot, maxReads
        );
    }

    /// @inheritdoc ITakeoverGovernor
    function advanceProposeScan(address token, address account, uint48 snapshot, uint256 maxReads)
        external
        returns (bool done)
    {
        return HoldWeightLib.advance(
            _holdScans, token, account, snapshot - _params.lookback, snapshot, maxReads
        );
    }

    // ------------------------------------------------------------------ internals

    function _setParams(Params memory p) private {
        if (p.votingPeriod < MIN_PERIOD || p.votingPeriod > MAX_PERIOD) revert InvalidParams();
        if (p.executionWindow < MIN_EXECUTION_WINDOW || p.executionWindow > MAX_PERIOD) {
            revert InvalidParams();
        }
        if (p.cooldown > MAX_COOLDOWN || p.minTokenAge > MAX_TOKEN_AGE) revert InvalidParams();
        if (p.lookback < MIN_LOOKBACK || p.lookback > MAX_LOOKBACK) revert InvalidParams();
        if (
            p.quorumBps < MIN_QUORUM_BPS || p.quorumBps > MAX_QUORUM_BPS
                || p.proposalThresholdBps < MIN_PROPOSAL_THRESHOLD_BPS
                || p.proposalThresholdBps > p.quorumBps
        ) revert InvalidParams();
        _params = p;
        emit ParamsUpdated(p);
    }

    function _isPending(State s) private pure returns (bool) {
        return s == State.Active || s == State.Closing || s == State.Succeeded;
    }

    /// @dev Whether the proposal started so long ago that it, and every earlier proposal of the
    ///      same token, can no longer be pending.
    function _pastHorizon(uint256 proposalId) private view returns (bool) {
        // forge-lint: disable-next-line(block-timestamp)
        return uint256(_proposals[proposalId].start) + _PENDING_HORIZON < block.timestamp;
    }

    /// @dev Voting weight: the whole-token lowest vote checkpoint over
    ///      `[lookbackSnapshot, snapshot]` (`HoldWeightLib`), so only votes held through the
    ///      whole lookback count.
    function _weightAt(address token, address account, uint48 snapshot, uint48 lookbackSnapshot)
        private
        view
        returns (uint64)
    {
        return HoldWeightLib.lowest(_holdScans, token, account, lookbackSnapshot, snapshot);
    }

    /// @dev Circulating supply at `snapshot` in whole tokens: total supply minus the PoolManager's
    ///      votes (its balance is self-delegated and can never be cast).
    function _circulatingAt(address token, uint48 snapshot) private view returns (uint64) {
        uint256 total = IVotes(token).getPastTotalSupply(snapshot);
        uint256 pooled = IVotes(token).getPastVotes(_poolManager, snapshot);
        uint256 whole = (total > pooled ? total - pooled : 0) / 1e18;
        // Capped, so the cast cannot truncate.
        // forge-lint: disable-next-line(unsafe-typecast)
        return whole > type(uint64).max ? type(uint64).max : uint64(whole);
    }
}

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/governance/utils/IVotes.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (governance/utils/IVotes.sol)

pragma solidity >=0.8.4;

/**
 * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
 */
interface IVotes {
    /**
     * @dev The signature used has expired.
     */
    error VotesExpiredSignature(uint256 expiry);

    /**
     * @dev Emitted when an account changes their delegate.
     */
    event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);

    /**
     * @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of voting units.
     */
    event DelegateVotesChanged(address indexed delegate, uint256 previousVotes, uint256 newVotes);

    /**
     * @dev Returns the current amount of votes that `account` has.
     */
    function getVotes(address account) external view returns (uint256);

    /**
     * @dev Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` is
     * configured to use block numbers, this will return the value at the end of the corresponding block.
     */
    function getPastVotes(address account, uint256 timepoint) external view returns (uint256);

    /**
     * @dev Returns the total supply of votes available at a specific moment in the past. If the `clock()` is
     * configured to use block numbers, this will return the value at the end of the corresponding block.
     *
     * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
     * Votes that have not been delegated are still part of total supply, even though they would not participate in a
     * vote.
     */
    function getPastTotalSupply(uint256 timepoint) external view returns (uint256);

    /**
     * @dev Returns the delegate that `account` has chosen.
     */
    function delegates(address account) external view returns (address);

    /**
     * @dev Delegates votes from the sender to `delegatee`.
     */
    function delegate(address delegatee) external;

    /**
     * @dev Delegates votes from signer to `delegatee`.
     */
    function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external;
}

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.
 *
 * IMPORTANT: Deprecated in favor of accessing `msg.sender` and `msg.data` directly. This contract, along with its
 * `_msgSender`, `_msgData` and `_contextSuffixLength` functions, will be removed in v6.0, where contracts read
 * `msg.sender` and `msg.data` directly. Contracts that override `_msgSender`/`_msgData` (e.g. to support
 * meta-transactions) will lose that extension point; plan the migration before upgrading.
 */
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;
    }
}

lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.sol.eta.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in a uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in a uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev A uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

src/interfaces/ITakeoverGovernor.sol

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

/// @title ITakeoverGovernor
/// @notice Community takeover: holders of a token vote to replace the account controlling the
///         token's profile (ENS records, logo, website). Choices are cast through the pluggable
///         voting scheme; weights come from the token's vote checkpoints at the proposal snapshot.
/// @dev Voters do not call the governor. They call
///      `IVotingScheme.castBallot(address(governor), token, proposalId, ballot)` on the scheme the
///      proposal was opened with; the scheme calls back `IBallotGovernor.authorizeBallot`, which
///      checks the proposal is active, the voter has not voted and returns their weight in whole
///      tokens: their lowest vote checkpoint over `[snapshot - lookback, snapshot]` (the snapshot
///      is the second before the proposal was created), so votes must have been held through
///      the whole lookback.
///      Quorum and the proposal threshold are fractions of the circulating supply at the
///      snapshot, which excludes the Uniswap PoolManager's balance. Several proposals may run
///      for the same token at once (at most one pending per proposer, with a per-proposer
///      cooldown); executing one supersedes every other proposal of that token created before it.
interface ITakeoverGovernor {
    enum State {
        None,
        Active,
        Closing,
        Defeated,
        Succeeded,
        Executed,
        Canceled,
        Expired,
        /// @dev Another proposal of the same token was executed after this one was created.
        Superseded
    }

    struct Params {
        /// @dev Seconds a proposal accepts ballots.
        uint32 votingPeriod;
        /// @dev Seconds after the vote ends during which a successful proposal can be executed.
        uint32 executionWindow;
        /// @dev Seconds after a proposer's proposal ends (or is canceled) before the same
        ///      proposer may propose again for the same token.
        uint32 cooldown;
        /// @dev Seconds after a token's registration before it can be targeted.
        uint32 minTokenAge;
        /// @dev FOR weight needed, in basis points of the circulating supply (whole tokens) at
        ///      the snapshot.
        uint16 quorumBps;
        /// @dev Proposer weight needed, in basis points of the circulating supply (whole tokens).
        ///      At least 1 and at most `quorumBps`; the required weight is never below one
        ///      whole token, so an account without voting weight cannot propose.
        uint16 proposalThresholdBps;
        /// @dev Seconds before the snapshot from which votes must have been held: weights are
        ///      the lowest checkpoint over the whole lookback.
        uint32 lookback;
    }

    struct Proposal {
        address token;
        address proposer;
        address newController;
        uint48 start;
        uint48 end;
        uint48 executionDeadline;
        uint48 snapshot;
        bool executed;
        bool canceled;
        uint64 quorumWeight;
        uint64 forWeight;
        uint64 againstWeight;
        bool tallied;
        /// @dev `snapshot - lookback`: the start of the window weights are read over.
        uint48 lookbackSnapshot;
        /// @dev Circulating supply at the snapshot in whole tokens (total supply minus the
        ///      PoolManager's votes); quorum and threshold are fractions of it.
        uint64 circulatingWeight;
    }

    event TakeoverProposed(
        address indexed token,
        uint256 indexed proposalId,
        address indexed proposer,
        address newController,
        uint48 start,
        uint48 end,
        uint64 quorumWeight
    );
    event TakeoverVoteCast(address indexed token, uint256 indexed proposalId, bytes32 voteRef);
    event TakeoverClosed(address indexed token, uint256 indexed proposalId);
    event TakeoverTallied(
        address indexed token, uint256 indexed proposalId, uint64 forWeight, uint64 againstWeight
    );
    event TakeoverExecuted(
        address indexed token, uint256 indexed proposalId, address indexed newController
    );
    event TakeoverCanceled(address indexed token, uint256 indexed proposalId);
    /// @notice Every proposal of `token` created before `executedProposalId` was executed and not
    ///         yet executed, canceled, defeated or expired is now `Superseded`.
    event TakeoverSuperseded(address indexed token, uint256 indexed executedProposalId);
    event ParamsUpdated(Params params);
    event SchemeUpdated(address indexed scheme);

    error TokenNotRegistered(address token);
    error ProposalPending(address token, uint256 proposalId);
    error CooldownActive(address token, uint256 availableAt);
    error TokenTooYoung(address token, uint256 eligibleAt);
    error InvalidNewController(address newController);
    error BelowProposalThreshold(uint64 weight, uint64 required);
    error NotScheme(address caller);
    error InvalidVote();
    error AlreadyVoted(address voter);
    error VotingClosed(uint256 proposalId);
    error VotingNotEnded(uint256 proposalId);
    error NotClosable(uint256 proposalId, State state);
    error AlreadyClosed(uint256 proposalId);
    error NotClosed(uint256 proposalId);
    error AlreadyTallied(uint256 proposalId);
    error TallyNotFinal(uint256 proposalId);
    error NotExecutable(uint256 proposalId, State state);
    error NotCancelable(uint256 proposalId, State state);
    error NotProposer();
    error UnknownProposal(uint256 proposalId);
    error InvalidParams();
    error ZeroAddress();
    /// @dev `proposeAt` snapshot that is not in the past or is older than `MAX_SNAPSHOT_AGE`.
    error InvalidSnapshot(uint256 snapshot);

    /// @notice Index of the AGAINST option in the poll.
    function AGAINST() external view returns (uint8);
    /// @notice Index of the FOR option in the poll.
    function FOR() external view returns (uint8);

    /// @notice Opens a takeover proposal snapshotted one second ago. The proposer must hold the
    ///         proposal threshold.
    function propose(address token, address newController) external returns (uint256 proposalId);
    /// @notice `propose` with a caller-chosen recent snapshot, at most `MAX_SNAPSHOT_AGE` old. The
    ///         window is then known in advance, so a proposer with very many checkpoints can run
    ///         the threshold scan ahead (`advanceProposeScan`) and still fit in a block.
    function proposeAt(address token, address newController, uint48 snapshot)
        external
        returns (uint256 proposalId);

    /// @notice Closes voting after the period ends and asks the scheme for the tally.
    function closeProposal(uint256 proposalId) external;

    /// @notice Reads the scheme's final tally into the proposal. Permissionless.
    function recordTally(uint256 proposalId) external;

    /// @notice Executes a successful proposal, replacing the token's controller. Supersedes every
    ///         other proposal of the token created before it.
    function execute(uint256 proposalId) external;

    /// @notice Cancels an active proposal (voting still open). Callable by the proposer or the
    ///         owner. The proposer's cooldown restarts from the cancellation.
    function cancel(uint256 proposalId) external;

    /// @notice Replaces the parameters for proposals created from now on. Owner only.
    function setParams(Params calldata params_) external;

    /// @notice Replaces the voting scheme for proposals created from now on. Owner only.
    function setScheme(address scheme_) external;

    function state(uint256 proposalId) external view returns (State);
    function getProposal(uint256 proposalId) external view returns (Proposal memory);
    /// @notice Most recent proposal of `token` that is Active, Closing or Succeeded (zero if none).
    ///         Several may be pending at once; see `activeProposalsOf`.
    function activeProposalOf(address token) external view returns (uint256);
    /// @notice Every proposal of `token` that is Active, Closing or Succeeded, newest first.
    function activeProposalsOf(address token) external view returns (uint256[] memory);
    /// @notice Every proposal id ever created for `token`, oldest first.
    function proposalsOf(address token) external view returns (uint256[] memory);
    /// @notice End of the most recent proposal created for `token` (informational; cooldowns are
    ///         per proposer, see `cooldownAnchorOf`).
    function lastProposalEnd(address token) external view returns (uint256);
    /// @notice Latest proposal `proposer` created for `token` (zero if none).
    function latestProposalOf(address token, address proposer) external view returns (uint256);
    /// @notice Timestamp `proposer`'s cooldown for `token` runs from: the end of their latest
    ///         proposal, or its cancellation time (zero if they never proposed).
    function cooldownAnchorOf(address token, address proposer) external view returns (uint256);
    /// @notice Uniswap v4 PoolManager whose balance is excluded from the circulating supply.
    function poolManager() external view returns (address);
    function proposalCount() external view returns (uint256);
    function params() external view returns (Params memory);
    function scheme() external view returns (address);
    function registry() external view returns (address);
    /// @notice Scheme the proposal was opened with (zero for unknown proposals).
    function proposalScheme(uint256 proposalId) external view returns (address);
    /// @notice Whether the proposal's poll was closed (tally requested).
    function isClosed(uint256 proposalId) external view returns (bool);
    /// @notice Whether `voter` cast a ballot in the proposal.
    function hasVoted(uint256 proposalId, address voter) external view returns (bool);
    /// @notice Voting weight of `account` for `proposalId`: whole tokens, the lowest checkpoint
    ///         over `[lookbackSnapshot, snapshot]`.
    function weightOf(uint256 proposalId, address account) external view returns (uint64);
    /// @notice Reads at most `maxReads` more vote checkpoints of `account`'s hold window for the
    ///         proposal and caches the progress, so a ballot over a window with very many
    ///         checkpoints fits in a block. Anyone may call it; it never changes a weight.
    /// @return done Whether the whole window has been read.
    function advanceHoldScan(uint256 proposalId, address account, uint256 maxReads)
        external
        returns (bool done);
    /// @notice `advanceHoldScan` for the window a `proposeAt(token, _, snapshot)` would read,
    ///         `[snapshot - lookback, snapshot]` under the current parameters. `snapshot` must be
    ///         in the past.
    function advanceProposeScan(address token, address account, uint48 snapshot, uint256 maxReads)
        external
        returns (bool done);
}

src/interfaces/ITokenProfileRegistry.sol

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

/// @title ITokenProfileRegistry
/// @notice Per-token profile written at launch: the ENS label under the Varada parent name, the
///         accounts allowed to edit records, ENS text records and the logo reference. The factory
///         registers; the controller (initially the creator) edits and may delegate to an editor;
///         the takeover governor can replace the controller. Every name serves the one site
///         contenthash set by the owner: no profile can point its subname at another site.
interface ITokenProfileRegistry {
    struct Profile {
        address controller;
        uint48 registeredAt;
        bool suppressed;
        address editor;
        bytes32 labelhash;
        bytes32 logoRef;
        string label;
    }

    struct Reservation {
        bool reserved;
        /// @dev Creator allowed to claim the reserved label; zero means nobody.
        address allowedCreator;
    }

    event TokenRegistered(
        address indexed token,
        bytes32 indexed labelhash,
        string label,
        address controller,
        bytes32 logoRef
    );
    event ControllerChanged(
        address indexed token, address indexed previousController, address indexed newController
    );
    event EditorChanged(address indexed token, address indexed editor);
    event TextChanged(address indexed token, string indexed indexedKey, string key, string value);
    event LogoChanged(address indexed token, bytes32 logoRef);
    event SuppressionChanged(address indexed token, bool suppressed);
    event GovernorChanged(address indexed governor);
    event DefaultContenthashChanged(bytes hash);
    event PlatformAddressChanged(address indexed platformAddress);
    event ParentTextChanged(string indexed indexedKey, string key, string value);
    event ReservationChanged(bytes32 indexed labelhash, bool reserved, address allowedCreator);

    /// @notice Emitted once per token when its cause focus is fixed at launch.
    event FocusSet(address indexed token, uint64 categoryMask, uint16 regionMask);

    error NotFactory();
    error FocusAlreadySet(address token);
    error ZeroFocus();
    error NotController(address token, address caller);
    error NotControllerOrEditor(address token, address caller);
    error NotGovernor();
    error NotRegistered(address token);
    error AlreadyRegistered(address token);
    error LabelTaken(bytes32 labelhash, address token);
    error LabelReserved(bytes32 labelhash);
    error EditorIsController();
    error ContenthashTooLong(uint256 length);
    error ZeroAddress();
    error ZeroParentNode();

    // ------------------------------------------------------------------ factory

    /// @notice Registers a launched token under `label`. Factory only.
    /// @return node ENS node of `<label>.<parent>`.
    function register(address token, string calldata label, address controller, bytes32 logoRef)
        external
        returns (bytes32 node);

    // ------------------------------------------------------------------ controller / governor

    /// @notice Transfers control. The controller may pass zero to renounce; the governor must pass
    ///         a non-zero account. Always clears the editor.
    function setController(address token, address newController) external;

    /// @notice Appoints (or clears, with zero) an editor who may edit records only.
    function setEditor(address token, address editor) external;

    // ------------------------------------------------------------------ controller or editor

    function setLogoRef(address token, bytes32 logoRef) external;
    function setText(address token, string calldata key, string calldata value) external;

    // ------------------------------------------------------------------ owner

    function setGovernor(address governor) external;
    /// @notice Sets the site contenthash served for the parent name and every registered subname.
    function setDefaultContenthash(bytes calldata hash) external;
    function setPlatformAddress(address platformAddress) external;
    function setParentText(string calldata key, string calldata value) external;
    function setReservation(bytes32 labelhash, bool reserved, address allowedCreator) external;
    function setSuppressed(address token, bool suppressed) external;

    // ------------------------------------------------------------------ views

    function factory() external view returns (address);
    function governor() external view returns (address);
    function parentNode() external view returns (bytes32);
    function defaultContenthash() external view returns (bytes memory);
    function platformAddress() external view returns (address);
    function parentText(string calldata key) external view returns (string memory);
    function isRegistered(address token) external view returns (bool);

    /// @notice Fixes a registered token's cause focus: the catalogue categories and regions its
    ///         ballots draw from. Factory only, once; both masks must be non-zero (all bits set
    ///         means "any").
    function setFocus(address token, uint64 categoryMask, uint16 regionMask) external;

    /// @notice Cause focus of a token (zero masks if never set).
    function focusOf(address token) external view returns (uint64 categoryMask, uint16 regionMask);
    function getProfile(address token) external view returns (Profile memory);
    function labelOf(address token) external view returns (string memory);
    function labelhashOf(address token) external view returns (bytes32);
    function nodeOf(address token) external view returns (bytes32);
    function controllerOf(address token) external view returns (address);
    function editorOf(address token) external view returns (address);
    function logoRefOf(address token) external view returns (bytes32);
    function registeredAtOf(address token) external view returns (uint48);
    function isSuppressed(address token) external view returns (bool);
    function text(address token, string calldata key) external view returns (string memory);
    function tokenByLabelhash(bytes32 labelhash) external view returns (address);
    function tokenByNode(bytes32 node) external view returns (address);
    function reservationOf(bytes32 labelhash) external view returns (Reservation memory);
    function MAX_CONTENTHASH_LENGTH() external view returns (uint256);
}

src/interfaces/IVotingScheme.sol

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

/// @title IBallotGovernor
/// @notice Callback a voting scheme makes into the governor that owns a poll, so the governor can
///         authorize the voter and return their weight. Called with the voter as `voter` while the
///         voter's transaction is executing, so schemes whose ballots are bound to the transaction
///         sender (encrypted inputs) work.
interface IBallotGovernor {
    /// @notice Authorizes `voter` to cast a ballot in `(token, scope)` and returns their weight in
    ///         whole tokens. Must revert if the voter may not vote. Only callable by the scheme.
    /// @param ballotRef Opaque reference of the ballot being cast (for the governor's event).
    function authorizeBallot(address token, uint256 scope, address voter, bytes32 ballotRef)
        external
        returns (uint64 weight);
}

/// @title IVotingScheme
/// @notice Pluggable ballot box used by the governors. A poll is keyed by the governor, the token
///         and a governor-chosen `scope` (an epoch index or a proposal id). The governor decides
///         who may vote and with what weight (through `IBallotGovernor.authorizeBallot`); the
///         scheme decides how choices are hidden and how final per-option counts are produced and
///         verified.
/// @dev Option indices are `0 .. optionCount-1`. Weights are in whole tokens so that totals fit in
///      64 bits. A scheme may hide the choice (e.g. FHE) and reveal only aggregates. Voters call
///      `castBallot` directly so that ballots can be bound to the transaction sender.
interface IVotingScheme {
    event PollOpened(
        address indexed governor, address indexed token, uint256 indexed scope, uint8 optionCount
    );
    event BallotCast(
        address indexed governor,
        address indexed token,
        uint256 indexed scope,
        address voter,
        uint64 weight,
        bytes32 ballotRef
    );
    event TallyRequested(address indexed governor, address indexed token, uint256 indexed scope);
    event TallySubmitted(
        address indexed governor, address indexed token, uint256 indexed scope, uint64[] counts
    );
    event GovernorSet(address indexed governor, bool allowed);

    error NotGovernor(address caller);
    error PollNotOpen(address governor, address token, uint256 scope);
    error PollAlreadyOpen(address governor, address token, uint256 scope);
    error PollClosed(address governor, address token, uint256 scope);
    error PollNotClosed(address governor, address token, uint256 scope);
    error TallyAlreadyFinal(address governor, address token, uint256 scope);
    error InvalidOptionCount(uint8 optionCount);
    error AlreadyVoted(address voter);
    error ZeroWeight();
    error InvalidBallot();
    error InvalidTallyProof();

    /// @notice Opens a poll. Governor only.
    function open(address token, uint256 scope, uint8 optionCount) external;

    /// @notice Casts the caller's ballot in `governor`'s poll `(token, scope)`. The scheme calls
    ///         `IBallotGovernor(governor).authorizeBallot` to authorize the caller and learn their
    ///         weight (which may lazily open the poll), then records the ballot. One ballot per
    ///         voter per poll.
    /// @return ballotRef Opaque reference, also passed to the governor.
    function castBallot(address governor, address token, uint256 scope, bytes calldata ballot)
        external
        returns (bytes32 ballotRef);

    /// @notice Closes the poll and asks for the aggregate to be revealed. Governor only. A scheme
    ///         may make the tally final right here when there is nothing to reveal (a poll
    ///         without ballots), emitting `TallySubmitted` itself.
    function requestTally(address token, uint256 scope) external;

    /// @notice Publishes the verified per-option counts of a closed poll. Permissionless; the
    ///         scheme verifies `proof` (e.g. KMS signatures over the decrypted aggregates).
    function submitTally(
        address governor,
        address token,
        uint256 scope,
        bytes calldata cleartexts,
        bytes calldata proof
    ) external;

    /// @notice Final counts of a poll, if available.
    function tallyOf(address governor, address token, uint256 scope)
        external
        view
        returns (bool isFinal, uint64[] memory counts);

    /// @notice Whether `voter` already cast a ballot in the poll.
    function hasVoted(address governor, address token, uint256 scope, address voter)
        external
        view
        returns (bool);

    /// @notice Number of ballots recorded in the poll.
    function ballotCount(address governor, address token, uint256 scope)
        external
        view
        returns (uint256);

    /// @notice Whether the poll is open for ballots.
    function isOpen(address governor, address token, uint256 scope) external view returns (bool);

    /// @notice Whether the poll was closed (tally requested).
    function isClosed(address governor, address token, uint256 scope) external view returns (bool);

    /// @notice Number of options of the poll (zero if never opened).
    function optionCountOf(address governor, address token, uint256 scope)
        external
        view
        returns (uint8);

    /// @notice Whether `governor` may open polls and request tallies.
    function isGovernor(address governor) external view returns (bool);

    /// @notice Largest option count a poll may have.
    function MAX_OPTIONS() external view returns (uint8);
}

/// @title IMinVotersGovernor
/// @notice Optional view of a governor: the fewest ballots its outcome polls need.
interface IMinVotersGovernor {
    function minVoters() external view returns (uint32);
}

// Winner index an outcome poll reports when no option qualifies.
uint8 constant NO_WINNER = type(uint8).max;

/// @title IOutcomeVotingScheme
/// @notice A voting scheme that can reveal only the outcome of a poll instead of its per-option
///         counts. Per-option counts of a small poll give individual choices away (one voter, or
///         a subset sum over the public weights); an outcome poll reveals a single option index.
/// @dev `requestOutcome` closes the poll instead of `requestTally`; such a poll never publishes
///      counts (`tallyOf` stays not final) and `submitTally` is refused for it.
///      The winner is the option with the strictly greatest tally, the lowest index on ties,
///      provided that tally is nonzero and at least `minWeight`; otherwise `NO_WINNER`.
interface IOutcomeVotingScheme is IVotingScheme {
    event OutcomeRequested(
        address indexed governor, address indexed token, uint256 indexed scope, uint64 minWeight
    );
    event OutcomeSubmitted(
        address indexed governor, address indexed token, uint256 indexed scope, uint8 winner
    );

    /// @notice The poll was closed for its outcome, so counts are never published.
    error OutcomeOnlyPoll(address governor, address token, uint256 scope);
    /// @notice The poll was not closed for its outcome.
    error NotOutcomePoll(address governor, address token, uint256 scope);

    /// @notice Closes the poll and asks for only its winner to be revealed. Governor only.
    /// @param minWeight Smallest winning tally; a lower best tally yields `NO_WINNER`.
    function requestOutcome(address token, uint256 scope, uint64 minWeight) external;

    /// @notice `requestOutcome` that also yields `NO_WINNER` unless at least `minBallots`
    ///         ballots chose a valid option. A scheme that hides the choice counts this under
    ///         encryption, so ballots for a missing option cannot pad a poll to its minimum. A
    ///         scheme may also leave out ballots below a minimum weight.
    function requestOutcome(address token, uint256 scope, uint64 minWeight, uint32 minBallots)
        external;

    /// @notice Publishes the verified winner of a poll closed with `requestOutcome`.
    ///         Permissionless; the scheme verifies `proof`.
    function submitOutcome(
        address governor,
        address token,
        uint256 scope,
        bytes calldata cleartexts,
        bytes calldata proof
    ) external;

    /// @notice Final winner of an outcome poll, if available (`NO_WINNER` when none qualified).
    function outcomeOf(address governor, address token, uint256 scope)
        external
        view
        returns (bool isFinal, uint8 winner);
}

src/libraries/HoldWeightLib.sol

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

/// @dev Vote checkpoint accessors of `ERC20TimestampVotes` (live tokens are `VaradaToken`s).
interface ICheckpointVotes {
    function numCheckpoints(address account) external view returns (uint32);
    function checkpoints(address account, uint32 pos)
        external
        view
        returns (uint48 key, uint208 value);
}

/// @title HoldWeightLib
/// @notice Hold weight shared by the governors: the lowest vote checkpoint an account had over a
///         window `[holdFrom, snapshot]`, in whole tokens.
/// @dev Every checkpoint inside the window is read, newest first; there is no cap. A cap would
///      let a holder hide a dip behind enough later checkpoints, and zeroing or rejecting a
///      capped scan would let anyone cancel a holder's vote, since a transfer to an account
///      writes a checkpoint (tokens self-delegate on receipt).
///
///      Extra checkpoints therefore only make a holder's scan longer: about 4.4k gas each, while
///      each one costs its sender a transfer at a distinct second (one per block at most). So
///      that no number of them can push a ballot past the block gas limit, anyone can run a
///      scan ahead in chunks (`advance`); its progress is cached per window. A window that ends
///      in the past never changes (new checkpoints are keyed at the current time), so the cache
///      stays valid.
library HoldWeightLib {
    /// @dev Cached progress of a window scan: the lowest value read so far, how many checkpoints
    ///      are still unread (the next one read is `next - 1`), and the scan state.
    struct Scan {
        uint208 low;
        uint32 next;
        bool started;
        bool done;
    }

    /// @dev `advance` on a window whose snapshot is not yet in the past.
    error HoldWindowOpen(uint256 snapshot);

    /// @dev Lowest vote checkpoint of `account` over `[holdFrom, snapshot]` in whole tokens,
    ///      capped to 64 bits; zero while `snapshot` is not in the past, or when the account had
    ///      no votes at `holdFrom`. A `holdFrom` at or after `snapshot` reads `snapshot` alone.
    ///      Resumes from the progress cached by `advance`, then reads the rest.
    function lowest(
        mapping(bytes32 => Scan) storage scans,
        address token,
        address account,
        uint256 holdFrom,
        uint256 snapshot
    ) internal view returns (uint64) {
        // forge-lint: disable-next-line(block-timestamp)
        if (snapshot >= block.timestamp) return 0;
        (, Scan memory s) =
            _resume(scans, token, account, holdFrom, snapshot, type(uint256).max);
        uint256 whole = uint256(s.low) / 1e18;
        // Capped just below, so the cast cannot truncate.
        // forge-lint: disable-next-line(unsafe-typecast)
        return whole > type(uint64).max ? type(uint64).max : uint64(whole);
    }

    /// @dev Reads at most `maxReads` more checkpoints of the window and caches the progress.
    ///      Returns whether the scan is complete.
    function advance(
        mapping(bytes32 => Scan) storage scans,
        address token,
        address account,
        uint256 holdFrom,
        uint256 snapshot,
        uint256 maxReads
    ) internal returns (bool) {
        // forge-lint: disable-next-line(block-timestamp)
        if (snapshot >= block.timestamp) revert HoldWindowOpen(snapshot);
        (bytes32 key, Scan memory s) =
            _resume(scans, token, account, holdFrom, snapshot, maxReads);
        scans[key] = s;
        return s.done;
    }

    /// @dev The cached scan of the window, continued by at most `maxReads` reads. One call site
    ///      for the scan, so it is compiled once.
    function _resume(
        mapping(bytes32 => Scan) storage scans,
        address token,
        address account,
        uint256 holdFrom,
        uint256 snapshot,
        uint256 maxReads
    ) private view returns (bytes32 key, Scan memory s) {
        key = keccak256(abi.encode(token, account, holdFrom, snapshot));
        s = scans[key];
        _scan(s, token, account, holdFrom, snapshot, maxReads);
    }

    /// @dev Continues `s` by at most `maxReads` checkpoint reads, newest first, down to and
    ///      including the checkpoint in effect at `holdFrom`.
    function _scan(
        Scan memory s,
        address token,
        address account,
        uint256 holdFrom,
        uint256 snapshot,
        uint256 maxReads
    ) private view {
        if (s.done) return;
        ICheckpointVotes cv = ICheckpointVotes(token);
        uint256 i;
        uint256 low;
        if (s.started) {
            i = s.next;
            low = s.low;
        } else {
            // Index one past the last checkpoint with `key <= snapshot`.
            uint256 hi = cv.numCheckpoints(account);
            while (i < hi) {
                uint256 mid = (i + hi) / 2;
                (uint48 k,) = cv.checkpoints(account, uint32(mid));
                if (k > snapshot) hi = mid;
                else i = mid + 1;
            }
            low = type(uint208).max;
        }
        bool done;
        for (uint256 reads; reads < maxReads; ++reads) {
            // No checkpoint at or before `holdFrom`: no votes at the window's start.
            if (i == 0) {
                low = 0;
                done = true;
                break;
            }
            --i;
            (uint48 key, uint208 value) = cv.checkpoints(account, uint32(i));
            if (value < low) low = value;
            if (low == 0 || key <= holdFrom) {
                done = true;
                break;
            }
        }
        // `low` is a checkpoint value or the uint208 maximum, and `i` a checkpoint index.
        // forge-lint: disable-next-line(unsafe-typecast)
        s.low = uint208(low);
        // forge-lint: disable-next-line(unsafe-typecast)
        s.next = uint32(i);
        s.started = true;
        s.done = done;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@uniswap/v4-core/=lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "v4-core/=lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/src/",
    "solmate/=lib/v4-core/lib/solmate/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "@fhevm/solidity/=node_modules/@fhevm/solidity/",
    "encrypted-types/=node_modules/encrypted-types/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.