Skip to content
Verified contractExactUNLICENSED

Governance

Address0x65a8afdaa5a464490a5c216797eb592bbff3e917
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 10,000 runs
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,352,803
Creation transaction
0xd26a64c60c…955f6216a4

contracts/Governance.sol

// SPDX-License-Identifier: UNLICENSED
// =====================================================================
//  EquityMint.org / DataCloud OS  —  Official Sovereign Issuance Suite
//  Module: Governance.sol
//  (c) 2025 US Fintech LLC, a New York limited liability company.
//  ALL RIGHTS RESERVED.  PROPRIETARY & CONFIDENTIAL.
// ---------------------------------------------------------------------
//  NOTICE OF PROPRIETARY RIGHTS
//  This source file, its compiled bytecode, ABI, deployment artifacts,
//  documentation, and every derivative thereof (the "Software") are
//  the proprietary intellectual property of US Fintech LLC ("Licensor").
//  No license, express or implied, by estoppel or otherwise, to any
//  patent, copyright, trademark, trade secret, or other intellectual
//  property right of Licensor is granted by this file or its publication
//  on any chain, repository, registry, or service. Possession, viewing,
//  indexing, mirroring, decompilation, or re-publication does NOT confer
//  any right of use.
//
//  AUTHORIZED USE ONLY
//  Deployments are authorized SOLELY through the official EquityMint
//  DataCloud OS Sovereign Deployment Engine and are cryptographically
//  registered in the EquityMint On-Chain Registry.
//
//  GOVERNING LAW & FORUM
//  This notice and any dispute arising out of or relating to the
//  Software are governed by the laws of the State of New York, U.S.A.,
//  without regard to conflict-of-law principles. Exclusive jurisdiction
//  and venue lie in the state and federal courts located in New York
//  County, New York.
//
//  AUTHENTICITY & CONTACT
//  Official sources: https://EquityMint.org   |   [email protected]
//  Infringement / DMCA notices: [email protected]
//  Author of architecture: Ken Silverman (ElasticTreasury HUB & SPOKE,
//  PeerTreasury, Controller / ControllerTree models).
// =====================================================================
// Copyright 2025 US Fintech LLC, a New York company.
//
// OFFICIAL US FINTECH LLC COMPONENT
// EquityMint Governance - Shareholder voting for tokens issued via the
// EquityMint Sovereign Issuance Suite.
//
// @author Ken Silverman
// @dev    Governance is a project-Controller-registered SmartContract peer,
//         self-registering (like PRT / DM / BTM / ReleaseManager) via a
//         DIRECT Controller.init() call in its constructor. v43107: the
//         ExecutivePeerTreasury inheritance was REMOVED — Governance never
//         holds funds by design (money-attached "votes" are subscriptions,
//         not votes, and live in CapitalCallManager), and dropping the
//         treasury base frees bytecode room for future Governance features
//         (e.g., an admin-settable permissioned vote fee routed to a
//         TokenAdmin-specified ExecutivePeerTreasury). The constructor still
//         accepts (controller, feeManager, issueToken) — the standard peer
//         signature — so the Factory bytecode-injection and the UI remain
//         unchanged, and `feeManager` stays queryable for future fee flows.
//         Because Governance is deployed LAST in ControllerFactory Phase 7,
//         its constructor-tail sync of the excluded-core-contract cache sees
//         every phase-7 peer already registered — including itself.
pragma solidity 0.8.35;

import "../interfaces/IController.sol";
import "../interfaces/IFeeManager.sol";
import "./CloneInitializable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

/* ========== CUSTOM ERRORS ========== */

error NotTokenAdmin();
error InvalidController();
error VoterIsCoreContract();
error ProposerIsCoreContract();
error InsufficientProposerBalance();
error InsufficientVoterBalance();
error ElectionAlreadyExists();
error ElectionNotFound();
error ElectionNotActive();
error ElectionNotClosed();
error AlreadyVoted();
error InvalidOptionCount();
error InvalidOptionIndex();
error EmptyOptionText();
error OptionTextTooLong();
error EmptyTitle();
error TitleTooLong();
error InvalidVoteDuration();
error InvalidPreviewDuration();
error InvalidMaxActiveElections();
error InvalidPercent();
error TooManyOpenElections();
error UnsupportedDecimals();
error ZeroTokenAddress();
error ApprovalQueueFull();
error ElectionNotAwaitingApproval();
error InvalidMaxPendingApprovalElections();
error CannotDuplicateBeforeClose();
error FeeStablecoinNotSet();     // v43108: a non-zero GovernancePropose/Vote fee is configured but the IssueToken reported no stablecoin
error FeeTransferFailed();       // v43108: stablecoin pull from the payer / push to a fee entity returned false

/// @dev Minimal token surface Governance reads. IssueToken satisfies this via
///      standard ERC20 + IIssueToken.
interface IGovernanceToken {
    function balanceOf(address account) external view returns (uint256);
    function totalSupply() external view returns (uint256);
    function decimals() external view returns (uint8);
}

/// @dev v43108: minimal stablecoin surface for the GovernancePropose / GovernanceVote fees.
interface IGovStable {
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
}

/**
 * @title  Governance
 * @notice On-chain proposal + voting for holders of a project's IssueToken.
 *
 * TERMINOLOGY — "propose" vs "activate"
 *   proposeElection() is the public entry point. It writes the election
 *   struct (proposer identity, title, options, submittedAtTimestamp) into
 *   storage but does NOT necessarily set the election in motion. Whether
 *   the election starts its lifecycle immediately is decided by the global
 *   approval gate:
 *     - requireAdminApprovalToPropose == false (default): proposeElection
 *       directly calls the internal helper _activateElection() and the
 *       election immediately enters Pending → Active → Closed.
 *     - requireAdminApprovalToPropose == true: proposeElection instead
 *       parks the proposal in the ADMIN-APPROVAL QUEUE (see the "APPROVAL
 *       GATE" section below). A later approveElection() by a TokenAdmin is
 *       what calls _activateElection() and puts the election in motion.
 *   _activateElection() is the SINGLE place that flips isActivated=true
 *   (bit _F_IS_ACTIVATED on Election.flags), freezes the frozen-globals,
 *   and enrolls the election in the lifecycle queues. approveElection()
 *   is the SINGLE place that flips isApproved=true (bit _F_IS_APPROVED).
 *   The direct path (no admin review) leaves isApproved=false forever.
 *
 * LIFECYCLE
 *   Every activated election flows through three phases:
 *
 *      Pending  -(activeFromTimestamp reached)→  Active  -(closesAtTimestamp reached)→  Closed
 *
 *   Both timestamps are FROZEN at ACTIVATION time. The election also
 *   freezes the two duration globals (voteDurationInDays,
 *   previewDurationInDays) and the two quorum-percent globals
 *   (minTokenTallyPercentToWin, minTokenPercentVoted) into its own struct
 *   at ACTIVATION time. The eligible-supply snapshot
 *   (totalTokensVotableAtClose) is deliberately NOT frozen at activation —
 *   it is captured at CLOSE time so quorum thresholds measure the
 *   shareholder-supply that was in force when voting concluded, not one
 *   that could be many weeks stale. See the CLOSE-TIME VOTABLE-SUPPLY
 *   SNAPSHOT section below for the full rationale.
 *
 * ORDERING INVARIANTS
 *   Lifecycle arrays (_allElectionKeys, _pendingKeys, _activeKeys,
 *   _closedKeys) are populated in strict ACTIVATION-TIMESTAMP order — the
 *   push happens inside _activateElection, so entries appear in the order
 *   they were set in motion, NOT the order they were submitted. (For the
 *   direct path these coincide; for the approval-gated path a proposal
 *   submitted early but approved late arrives late in the arrays.) That
 *   order NEVER changes — nothing in this contract re-orders history.
 *
 *   Two side-index arrays (_awaitingApprovalKeys and
 *   _electionsByProposer[proposer]) use SWAP-AND-POP removal on
 *   reject / approve, and are therefore NOT guaranteed to preserve
 *   submission order after the first removal. Every summary returned by
 *   the view layer carries submittedAtTimestamp so clients that want a
 *   stable "submitted first" order can sort client-side. This is the
 *   same trade-off used by _awaitingApprovalKeys.
 *
 *   The election key itself is keccak256(block.number, proposer), pairing
 *   proposal block with proposer address as an unforgeable identifier.
 *
 * REFRESH MODEL
 *   refreshElections() — cheap. Walks the FRONT of pending + active until it
 *   finds an entry that still belongs, then STOPS. Auto-invoked at the top of
 *   every proposeElection() and castVote(). Public, callable by anyone.
 *
 *   The internal _refresh(true) path sweeps the ENTIRE pending + active
 *   queues in a single pass, promoting/closing every eligible entry
 *   regardless of its position. NOT exposed as a standalone external —
 *   the two TokenAdmin setters that mutate a DURATION global
 *   (setVoteDurationInDays, setPreviewDurationInDays) call _refresh(true)
 *   themselves — because after such a change the derived timestamps
 *   (activeFromTimestamp = activated + frozen preview; closesAtTimestamp
 *   = activated + frozen preview + frozen vote) of already-in-flight
 *   elections may no longer be monotone in the order they were pushed, so
 *   the cheap front-break could miss middle stragglers until the full
 *   sweep runs. Threshold setters (min-token, min-percent) and the
 *   approval-gate toggle are frozen per-election or only affect future
 *   proposals, so they do NOT trigger a full sweep.
 *
 *   Internally both entry points funnel to _refresh(bool full): false runs
 *   the cheap front-walk, true runs the O(N) sweep with tail rebuild.
 *
 *   The cheap refresh is called on every hot path (vote + propose); the full
 *   sweep is used only where required (duration setters, or on-demand by any
 *   user).
 *
 * CAPACITY CAP
 *   maxActiveElections (TokenAdmin-settable, default 100) caps the combined
 *   live pending + active count. proposeElection() reverts with
 *   TooManyOpenElections when adding would exceed the cap. This is what keeps
 *   active/pending views un-paginated.
 *
 * ELIGIBILITY
 *   Voters and proposers must NOT be Controller-registered SmartContract
 *   entities (the "core-contract list"). Governance mirrors DM's cache
 *   idiom: the initial sync runs in the constructor; syncExcludedCoreContracts
 *   is permissionless. TokenAdmin bypasses the propose minimum-balance gate
 *   (see proposeElection) but still cannot be an excluded core contract.
 *
 * APPROVAL GATE (requireAdminApprovalToPropose)
 *   Global TokenAdmin-settable boolean, default FALSE. When TRUE, every
 *   proposeElection() call routes into the ADMIN-APPROVAL QUEUE instead of
 *   creating the election directly. The queue is a separate bounded array
 *   (cap = maxPendingApprovalElections, default DEFAULT_MAX_PENDING_APPROVAL_ELECTIONS
 *   = 100) so admins can retrieve every entry via
 *   getAwaitingApprovalElectionKeys() (hydrate with getElectionSummaries())
 *   without pagination.
 *
 *   Admin actions on a queued entry:
 *     - approveElection(key)  – dequeues + calls _activateElection(), which
 *                                is the same lifecycle path a direct-mode
 *                                proposal would have taken. The frozen
 *                                globals are captured at APPROVAL time so
 *                                the election's terms reflect the state of
 *                                the world when its clock actually starts.
 *                                (The eligible-supply snapshot is still
 *                                deferred to CLOSE — see below.)
 *     - rejectElection(key)   – dequeues from the approval queue and sets
 *                                _F_IS_REJECTED on Election.flags. The slot
 *                                is INTENTIONALLY retained (title, proposer,
 *                                options, submittedAtTimestamp) as a
 *                                permanent audit record; clients hide
 *                                rejected rows by filtering summary.flags
 *                                bit 0. Resubmission works because the key
 *                                derivation includes block.number.
 *
 *   Toggling the global does NOT retroactively re-route in-flight entries:
 *   already-queued proposals still need explicit approve/reject; already-
 *   activated (Pending/Active/Closed) elections are unaffected. Auth checks
 *   (excluded-core-contract + minTokenRequiredToProposeVote / TokenAdmin
 *   bypass) run at SUBMISSION only — admin discretion is the extra layer,
 *   not a replacement for the base gates.
 *
 * STATE BOOLEANS (per election, in the Election struct)
 *   isApproved    – false by default. Flipped true ONLY by approveElection()
 *                    (i.e. when a TokenAdmin has EXPLICITLY approved this
 *                    proposal). Direct-path proposals — the case where
 *                    requireAdminApprovalToPropose was false at submission
 *                    — never see an admin approval and therefore keep
 *                    isApproved = false for their entire lifetime, even
 *                    after they run to close. Read as: "did a human admin
 *                    say yes to this?"
 *   isActivated   – false by default. Flipped true by _activateElection()
 *                    on BOTH branches (direct-path from proposeElection,
 *                    and gated-path from approveElection). Means "the
 *                    election has entered the Pending → Active → Closed
 *                    lifecycle" — its activatedTimestamp /
 *                    activeFromTimestamp / closesAtTimestamp are non-zero
 *                    and it lives in _pendingKeys / _activeKeys /
 *                    _closedKeys somewhere. Rejected-and-deleted proposals
 *                    of course have exists == false too.
 *   awaitingApproval – true iff the entry currently lives in _awaitingApprovalKeys.
 *                      Mutually exclusive with isActivated.
 *
 *   Truth table:
 *
 *     Path                           isApproved   isActivated   awaitingApproval
 *     -----------------------------  ----------   -----------   ----------------
 *     Direct (gate OFF at submit)      false        true            false
 *     Gated, waiting                   false        false           true
 *     Gated, admin-approved            true         true            false
 *     Gated, admin-rejected            (n/a — storage deleted)
 *
 *   So the two booleans differ in the direct path (isApproved false,
 *   isActivated true). Keeping them separate lets downstream views (the
 *   ElectionSummary returned by getElectionSummaries) show "admin
 *   explicitly said yes" independently of "election started running", and
 *   captures the distinction the user may care about: was there a human
 *   review step?
 *
 * DUPLICATION (revote support)
 *   Sometimes an election closes but its result is unusable — e.g. quorum
 *   wasn't met because the eligible-supply baseline (frozen at close, see
 *   below) had inflated since activation. Rather than letting the admin
 *   spin up a completely fresh proposal that loses the chain of provenance,
 *   the contract exposes duplicateElection(sourceKey), TokenAdmin-only,
 *   which:
 *     - Reads the source's title + option-texts.
 *     - Registers a fresh election with those same fields via the same
 *       _registerNewElection path proposeElection uses (so the approval
 *       gate is respected — a duplicated election obeys the current
 *       requireAdminApprovalToPropose setting just like any other).
 *     - Sets newElection.duplicatedFromKey = sourceKey.
 *     - Increments sourceElection.numDuplicates by 1.
 *     - Appends the new key to a global _duplicateElectionKeys array so
 *       auditors can enumerate every revote that has ever happened on
 *       the contract (getDuplicateElectionKeys() view).
 *
 *   Constraints:
 *     - The source must exist AND be closed (closedAtTimestamp != 0).
 *       Duplicating an awaiting-approval, pending, or active election is
 *       rejected with CannotDuplicateBeforeClose — the intended use case
 *       is "the previous run finished, let's try again", not "let's split
 *       an active vote in two".
 *     - Duplicates chain: duplicating a duplicate is allowed, and each
 *       new duplicate points back at its IMMEDIATE parent (not the root).
 *       Full provenance is followable by walking duplicatedFromKey until
 *       it hits bytes32(0).
 *     - The immediate parent's numDuplicates is what gets incremented —
 *       transitive duplicates are NOT counted against the root.
 *
 * CLOSE-TIME VOTABLE-SUPPLY SNAPSHOT (totalTokensVotableAtClose)
 *   The frozen eligible-supply used by the two quorum thresholds is
 *   snapshotted in _closeElection(), NOT in _activateElection(). Rationale:
 *     - No code path DURING voting reads this field. Voter auth uses the
 *       live balanceOf() at castVote() time, not the snapshot.
 *     - Deferring to close guarantees the quorum baseline matches the
 *       shareholder supply that was actually in play at the end of the
 *       vote, rather than one that could be many weeks stale for elections
 *       with long preview + voting windows.
 *     - _isValidWinner() runs at close-time (and on any post-close view via
 *       ElectionSummary.isValid), both of which see the frozen snapshot.
 *       Callers wanting an expired-but-not-yet-refreshed preview should
 *       send a plain refreshElections() tx (anyone can call it — no auth)
 *       and then read the summary; no dedicated preview code path exists.
 *   Governance-risk note: because minting/burning between activation and
 *   close changes the quorum baseline, TokenAdmins with mint power on the
 *   IssueToken can influence quorum outcomes by adjusting supply near
 *   close. The excluded-core-contract cache is subtracted from totalSupply
 *   before scaling, so tokens held by other Controller-registered peers do
 *   not enter the baseline.
 *
 * WINNER
 *   The election winner is the OPTION whose tokensTally is strictly highest.
 *   On close, _closeElection() copies that option's string into
 *   Election.winningOptionText so future readers do not walk the options
 *   array to identify it. Ties and no-vote outcomes are flagged (`tie`,
 *   `noVotes`) and leave winningOptionText empty.
 *
 * RESULT VALIDITY
 *   Each election freezes TWO quorum-percent inputs at ACTIVATION time —
 *   minTokenPercentVotedAtActivation, minTokenTallyPercentToWinAtActivation —
 *   AND ONE eligible-supply snapshot at CLOSE time —
 *   totalTokensVotableAtClose (see the CLOSE-TIME VOTABLE-SUPPLY SNAPSHOT
 *   section for why the snapshot is deferred).
 *
 *   isElectionResultValid() applies TWO orthogonal thresholds on close,
 *   both computed on the fly:
 *
 *     participation quorum:
 *        totalTokensVoted * 100
 *          >= totalTokensVotableAtClose * minTokenPercentVotedAtActivation
 *
 *     winning-option quorum:
 *        winningTokensTally * 100
 *          >= totalTokensVotableAtClose * minTokenTallyPercentToWinAtActivation
 *
 *   BOTH must hold, AND the outcome must be a single-winner (not tied and
 *   not empty), for isElectionResultValid to be true. When either frozen
 *   percent is 0 (the built-in default), that particular threshold auto-
 *   passes. Ties and no-vote closes are always invalid.
 *
 * IMPLEMENTATION FLAG (post-close TODO tracker)
 *   Each election also carries an admin-set boolean `isImplemented`, defaulting
 *   to false. Only TokenAdmin can toggle it, and only after the election has
 *   formally closed. It has no on-chain effect: it's exposed via
 *   ElectionSummary.isImplemented and clients filter closed pages on it to
 *   render "TODO" (unimplemented) vs "DONE" (implemented) lists. The
 *   previous filtered views were removed to save bytecode — client-side
 *   filtering over a paginated `getClosedElectionKeys` + `getElectionSummaries`
 *   result is straightforward and keeps the contract lean.
 */
// PROXY BUILD: EIP-1167 clone variant — deployed once per chain as an inert MODEL;
// projects receive a clone configured via initialize(). OZ ReentrancyGuard is
// clone-safe as-is (zero initial state behaves as NOT_ENTERED).
contract Governance is ReentrancyGuard, CloneInitializable {

    /// @notice Bytecode-verification tag.
    ///  v43108: FeeManager fee types GovernancePropose (proposeElection / duplicateElection,
    ///          once per proposal) and GovernanceVote (castVote, once per voter per election),
    ///          absolute-only, paid in the project stablecoin and pushed straight to the chained
    ///          fee entities (Governance still HOLDS no funds). *WithPermit variants bundle the
    ///          EIP-2612 signature; the original signatures work with a prior approve, or free
    ///          when the fee is 0 / the label is absent on the FeeManager.
    ///  v43107: ExecutivePeerTreasury inheritance removed (see @dev in the file header).
    uint16 public constant CONTRACT_VERSION = 43108;

    /* ========== FORMER ExecutivePeerTreasury SURFACE (kept, inlined) ========== */
    // Names preserved so every internal reference and the public ABI getters
    // (peerTreasuryController / feeManager / issueTokenAddress) are unchanged.

    /// @notice Project Controller used for entity gating.
    // PROXY BUILD: were `immutable` — now storage, set once in initialize().
    address public peerTreasuryController;

    /// @notice Project FeeManager — quotes the GovernancePropose / GovernanceVote
    ///         fees (v43108). A FeeManager that pre-dates either label, or a zero
    ///         amount, means "no fee".
    address public feeManager;

    /// @notice Project IssueToken (balance source).
    address public issueTokenAddress;

    /// @notice Pre-computed keccak256 hash of "TokenAdmin" (was inherited
    ///         from TreasuryConstants).
    bytes32 public constant KECCAK_TOKEN_ADMIN = keccak256(bytes("TokenAdmin"));

    /// @notice v43108 FeeManager label hashes (fee types 22 / 23). Both absolute-only:
    ///         quoted with totalVal = 0 so percent slots always evaluate to 0.
    bytes32 public constant KECCAK_FEE_GOV_PROPOSE = keccak256("GovernancePropose");
    bytes32 public constant KECCAK_FEE_GOV_VOTE    = keccak256("GovernanceVote");

    /* ========== CONSTANTS ========== */

    /// @notice Internal precision: X, Y, and per-option tokensTally are all
    ///         expressed in 18-decimal fixed-point.
    uint256 public constant PRECISION = 1e18;

    uint256 public constant MIN_OPTIONS = 2;
    uint256 public constant MAX_OPTIONS = 32;
    uint256 public constant MAX_OPTION_TEXT_LENGTH = 256;
    uint256 public constant MAX_TITLE_LENGTH = 256;

    /// @notice Absolute ceilings enforced by the TokenAdmin setters.
    uint256 public constant MAX_VOTE_DURATION_DAYS_CEILING    = 1460;   // ~4 years
    uint256 public constant MAX_PREVIEW_DURATION_DAYS_CEILING = 365;    // 1 year
    /// @notice Absolute ceiling on maxActiveElections. Guards refresh loops
    ///         from pathological admin misconfiguration.
    uint256 public constant MAX_ACTIVE_ELECTIONS_CEILING      = 10_000;

    /// @notice Constructor-baked defaults — chosen so the contract is fully
    ///         usable out-of-the-box with zero admin action.
    uint256 public constant DEFAULT_VOTE_DURATION_DAYS         = 30;      // one month active
    uint256 public constant DEFAULT_PREVIEW_DURATION_DAYS      = 30;      // one month preview
    uint256 public constant DEFAULT_MAX_ACTIVE_ELECTIONS       = 100;
    uint256 public constant DEFAULT_MIN_TOKENS_TO_PROPOSE      = 1000e18; // 1000 whole tokens
    uint256 public constant DEFAULT_MIN_TOKENS_TO_VOTE         = 1e18;    // 1 whole token
    uint256 public constant DEFAULT_MIN_TOKEN_TALLY_PCT_TO_WIN = 0;       // winning-option quorum off
    uint256 public constant DEFAULT_MIN_TOKEN_PCT_VOTED        = 10;      // 10% participation quorum by default

    /// @notice Default cap on the admin-approval queue length. Chosen small
    ///         enough that getAwaitingApprovalElectionKeys() can return
    ///         every entry in one call without pagination.
    uint256 public constant DEFAULT_MAX_PENDING_APPROVAL_ELECTIONS = 100;

    /// @notice Absolute ceiling on maxPendingApprovalElections. Same
    ///         rationale as MAX_ACTIVE_ELECTIONS_CEILING — guards the
    ///         setter from pathological admin misconfiguration that would
    ///         make the O(N) queue view unusable.
    uint256 public constant MAX_PENDING_APPROVAL_ELECTIONS_CEILING = 10_000;

    /* ========== IMMUTABLES ========== */

    /// @notice IssueToken.decimals() cached at deployment.
    // PROXY BUILD: was `immutable` — now storage, set once in initialize().
    uint8 public tokenDecimalsCached;

    /// @notice Multiplier applied to native-decimals balanceOf() readings to
    ///         reach 18-decimal precision (10 ** (18 - decimals)).
    /// @dev PROXY BUILD: was `immutable` — now storage, set once in initialize().
    uint256 public dec18Scale;

    /* ========== GLOBAL PARAMS (TokenAdmin-only) ========== */

    /// @notice Duration in days a proposal spends in the Active phase.
    ///         Applies to proposals created AFTER this value is set. Each
    ///         election freezes its own copy in voteDurationInDaysAtActivation.
    uint256 public voteDurationInDays;

    /// @notice Preview duration Z (days). Elections spend this long in the
    ///         Pending phase after proposal — screenable but non-votable —
    ///         before entering Active. Frozen per-election.
    uint256 public previewDurationInDays;

    /// @notice Combined cap on live Pending + Active. Reverts new proposals
    ///         above the cap; keeps active/pending views un-paginated.
    uint256 public maxActiveElections;

    /// @notice X — minimum 18-dec-normalized balance to propose. TokenAdmins
    ///         BYPASS this check (see proposeElection).
    uint256 public minTokenRequiredToProposeVote;

    /// @notice Y — minimum 18-dec-normalized balance to vote.
    uint256 public minTokensRequiredToVote;

    /// @notice Quorum threshold on the winning option (percent 0-100).
    ///         Frozen per-election in minTokenTallyPercentToWinAtActivation.
    ///         See contract-level RESULT VALIDITY section for the formula.
    uint256 public minTokenTallyPercentToWin;

    /// @notice Participation quorum (percent 0-100). Total tokens cast in
    ///         the election must be at least this percent of the frozen
    ///         eligible supply for the close to be marked valid. Frozen
    ///         per-election in minTokenPercentVotedAtActivation. Constructor
    ///         default is DEFAULT_MIN_TOKEN_PCT_VOTED (10%); TokenAdmin can
    ///         set to 0 to disable the participation floor entirely.
    uint256 public minTokenPercentVoted;

    /// @notice Global admin-approval switch. Default FALSE — proposeElection
    ///         goes DIRECT into the lifecycle. When TRUE, proposeElection
    ///         parks the proposal in the admin-approval queue and requires
    ///         a TokenAdmin approveElection() call before the election
    ///         actually enters Pending phase. See the APPROVAL GATE section
    ///         of the contract-level NatSpec.
    bool public requireAdminApprovalToPropose;

    /// @notice Cap on the admin-approval queue length. Enforced at
    ///         SUBMISSION time (ApprovalQueueFull) so the O(N) queue viewer
    ///         and admin UX both stay bounded. Constructor default is
    ///         DEFAULT_MAX_PENDING_APPROVAL_ELECTIONS; TokenAdmin can adjust.
    uint256 public maxPendingApprovalElections;

    /* ========== EXCLUDED CORE-CONTRACT CACHE ========== */

    mapping(address => bool) public isExcludedCoreContract;
    address[] private _excludedList;

    /* ========== ELECTION STORAGE ========== */

    /**
     * @dev Bit positions inside Election.flags (uint8). The 7 lifecycle
     *      booleans that used to be separate `bool` fields are packed
     *      into a single byte to save bytecode (fewer per-field
     *      mask-and-set sequences) and gas (one SSTORE per state
     *      transition instead of N).
     *
     *      Bit 0 (_F_IS_REJECTED) is set EXCLUSIVELY by rejectElection()
     *      and NEVER cleared. Rejected elections retain their storage slot
     *      (title, proposer, options, submittedAtTimestamp) as a permanent
     *      audit trail; their key still appears in _allElectionKeys and
     *      _electionsByProposer, so clients should filter on this bit when
     *      rendering lists (or hide rejected rows entirely, admin's choice).
     *
     *      Sentinel note: the "was this key ever proposed?" check does NOT
     *      use flags — it uses `e.proposer == address(0)`, which is written
     *      once in _registerNewElection and never cleared. This lets
     *      _F_IS_REJECTED default to 0 (matching the semantic "not
     *      rejected") without needing a redundant exists bit.
     *
     *      All 7 bits are RE-USED at the same positions in
     *      ElectionSummary.flags so getElectionSummaries can bulk-copy
     *      them with one mask; see the summary block below.
     *      Bit 7 (_F_IS_VALID) is summary-only (derived at hydrate time).
     */
    uint8 internal constant _F_IS_REJECTED       = 0x01; // bit 0 — set once by rejectElection, never cleared
    uint8 internal constant _F_AWAITING_APPROVAL = 0x02; // bit 1
    uint8 internal constant _F_IS_APPROVED       = 0x04; // bit 2
    uint8 internal constant _F_IS_ACTIVATED      = 0x08; // bit 3
    uint8 internal constant _F_IS_IMPLEMENTED    = 0x10; // bit 4
    uint8 internal constant _F_NO_VOTES          = 0x20; // bit 5
    uint8 internal constant _F_TIE               = 0x40; // bit 6
    uint8 internal constant _F_IS_VALID          = 0x80; // bit 7 — summary-only, derived

    /// @dev Mask for the 7 lifecycle bits (0..6) shared between
    ///      Election.flags and ElectionSummary.flags — used in
    ///      getElectionSummaries to bulk-copy them in a single AND.
    ///      Bit 7 (_F_IS_VALID) is OR'd in AFTER the mask.
    uint8 internal constant _F_SHARED_MASK =
        _F_IS_REJECTED       | _F_AWAITING_APPROVAL | _F_IS_APPROVED |
        _F_IS_ACTIVATED      | _F_IS_IMPLEMENTED    | _F_NO_VOTES    |
        _F_TIE;

    struct ElectionOption {
        string  text;         // caller-supplied option label
        uint256 tokensTally;  // sum of 18-dec-normalized tokens voted for this option
        uint256 voterCount;   // unique voters that chose this option
    }

    /**
     * @dev Election storage layout. The 7 lifecycle booleans previously
     *      here as separate `bool` fields — `isRejected`, `awaitingApproval`,
     *      `isApproved`, `isActivated`, `isImplemented`, `noVotes`, `tie`
     *      — are packed into `flags`. See the _F_* constants above for bit
     *      assignments and semantics.
     *
     *      Semantics:
     *        isRejected       — set EXCLUSIVELY by rejectElection() and
     *                            NEVER cleared. The rejected slot retains
     *                            its title/proposer/options/submitted
     *                            timestamp as a permanent audit trail; the
     *                            key remains in _allElectionKeys and
     *                            _electionsByProposer. Clients render or
     *                            filter rejected rows client-side by
     *                            testing summary.flags & 0x01.
     *        awaitingApproval — true while parked in _awaitingApprovalKeys.
     *                            Set on proposal (approval-gated path);
     *                            cleared in approveElection() before
     *                            _activateElection() runs. While true,
     *                            activatedTimestamp / activeFromTimestamp /
     *                            closesAtTimestamp / frozen-globals are 0.
     *        isApproved       — set EXCLUSIVELY in approveElection(). Direct-
     *                            path proposals (approval not required at
     *                            submission time) leave this FALSE for life.
     *                            Read as: "was there a human review step?"
     *        isActivated      — set EXCLUSIVELY in _activateElection() (for
     *                            BOTH direct and approval-gated paths).
     *                            Read as: "has this entered the lifecycle?"
     *        isImplemented    — TokenAdmin-toggleable post-close TODO tracker.
     *                            No on-chain effect; exposed via the summary
     *                            for client-side "TODO vs DONE" filtering.
     *        noVotes / tie    — set in _closeElection() based on tally shape.
     */
    struct Election {
        string  title;                     // proposer-supplied identifier
        address proposer;
        uint256 startBlock;                // block.number at SUBMISSION (proposeElection); part of the election key derivation
        uint256 activatedTimestamp;        // block.timestamp when _activateElection ran (== submittedAtTimestamp for direct path; strictly later for approval-gated path)
        uint256 activeFromTimestamp;       // activatedTimestamp + previewDurationInDaysAtActivation*1 days
        uint256 closesAtTimestamp;         // activeFromTimestamp + voteDurationInDaysAtActivation*1 days
        uint256 closedAtTimestamp;         // when Closed was actually applied (0 until closed)

        // Frozen globals — see contract-level NatSpec.
        uint256 voteDurationInDaysAtActivation;
        uint256 previewDurationInDaysAtActivation;
        uint256 minTokenTallyPercentToWinAtActivation;
        uint256 minTokenPercentVotedAtActivation;      // participation quorum, frozen
        /// 18-dec eligible-supply snapshot. Populated in _closeElection()
        /// (NOT at activation) — see the CLOSE-TIME VOTABLE-SUPPLY SNAPSHOT
        /// section of the contract-level NatSpec. Zero until close.
        uint256 totalTokensVotableAtClose;

        uint256 totalNumberVoted;          // sum across options
        uint256 totalTokensVoted;          // sum across options (18-dec)
        ElectionOption[] options;

        // Winner cache — populated by _closeElection().
        uint256 winningOptionIndex;
        string  winningOptionText;
        uint256 winningTokensTally;

        /// block.timestamp at which proposeElection() was called. For
        /// direct-mode elections this equals activatedTimestamp; for
        /// approval-gated elections this is strictly earlier than
        /// activatedTimestamp and lets the admin queue view show
        /// "waiting since X" without recomputing.
        uint256 submittedAtTimestamp;

        /// If this election was created by duplicateElection() from an
        /// existing (closed) source, this stores the source's key. Zero
        /// otherwise. See the DUPLICATION section of the contract-level
        /// NatSpec — used to trace revote chains when an original election
        /// closed with insufficient quorum and had to be re-run.
        bytes32 duplicatedFromKey;

        /// How many times THIS election has been used as the source of a
        /// duplicateElection() call. Incremented in _registerNewElection
        /// on the source. Read as: "how many revote-attempts spawned from
        /// this election?" — 0 for elections that have never been duplicated.
        uint256 numDuplicates;

        /// Packed lifecycle booleans (see _F_* bit constants above).
        uint8 flags;
    }

    mapping(bytes32 => Election) private _elections;

    /// @notice Append-only, activation-timestamp order. Backs getAll* views.
    bytes32[] private _allElectionKeys;

    /// @notice Phase queues (activation-timestamp order). Pending + Active use
    ///         head pointers for O(1) dequeue-from-front on the hot path.
    ///         Full sweeps (via internal _refresh(true)) rebuild the tails.
    bytes32[] private _pendingKeys; uint256 private _pendingHead;
    bytes32[] private _activeKeys;  uint256 private _activeHead;
    bytes32[] private _closedKeys;

    /// @notice Admin-approval queue. Only populated while
    ///         requireAdminApprovalToPropose is true (or was true when the
    ///         entries were submitted). Approve / reject use swap-and-pop
    ///         removal, so order is NOT stable — callers relying on the
    ///         "submitted first" order should sort client-side on
    ///         submittedAtTimestamp. Bounded by maxPendingApprovalElections.
    bytes32[] private _awaitingApprovalKeys;

    /// @notice Per-proposer index. Populated on proposeElection() for BOTH
    ///         branches (direct + approval-gated). Entries are NEVER
    ///         removed — rejected proposals retain their slot (see
    ///         _F_IS_REJECTED and the Election NatSpec). Order is stable
    ///         (append-only), matches submission order 1:1, and clients
    ///         wanting to hide rejected rows filter on
    ///         `(summary.flags & 0x01) != 0`. Backs getElectionKeysByProposer().
    mapping(address => bytes32[]) private _electionsByProposer;

    /// @notice Chronological list of every child key created via
    ///         duplicateElection(). Append-only — a duplicated election is
    ///         itself just a regular election that happens to point at a
    ///         parent via its Election.duplicatedFromKey field, so nothing
    ///         removes entries from this array. Auditors get
    ///         getDuplicateElectionKeys() / getDuplicateElectionCount() /
    ///         getDuplicatesOf(sourceKey) for querying. See the DUPLICATION
    ///         section of the contract-level NatSpec.
    bytes32[] private _duplicateElectionKeys;

    /// @notice Voter bookkeeping (audit trail + double-vote guard).
    mapping(bytes32 => mapping(address => bool)) public hasVoted;
    mapping(bytes32 => mapping(address => uint256)) public votedOptionIndexOf;
    mapping(bytes32 => mapping(address => uint256)) public votedTokensOf;

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

    // NOTE: The 9 per-setter "*Updated(value, setBy)" audit events were
    // removed to reclaim bytecode. Rationale:
    //   1. The current value of every global is queryable via its public
    //      getter, so "what is X now?" needs no event.
    //   2. Each election FREEZES its own copy of every relevant global into
    //      its Election struct at activation time (see the frozen-globals
    //      block). "What were the globals when election E ran?" is
    //      permanently recoverable from getElectionSummaries([E]) — the
    //      per-setter audit event was strictly redundant with that state.
    //   3. Block explorers already record raw setXxx transactions with
    //      full calldata, so off-chain audit trails ("who called setYyy(Z)
    //      at block N?") are trivially reconstructible without custom
    //      events.
    //
    // The events surviving below are the ones whose data is NOT otherwise
    // preserved anywhere on-chain: reject/approve/duplicate/implement
    // record msg.sender + electionKey (not stored in the Election struct),
    // and VoteCast is retained because off-chain indexers rely on it for
    // fast historical voter queries.

    event ExcludedCoreContractsSynced(uint256 count, address indexed by);
    event ElectionImplementationSet(bytes32 indexed electionKey, bool isImplemented, address indexed setBy);

    /// @notice Admin-action audit events. These record msg.sender + the
    ///         affected election key, which is NOT preserved anywhere else
    ///         on-chain. Kept even though bytecode is tight because
    ///         "who did what, when" is unrecoverable from state alone.
    event ElectionApproved(bytes32 indexed electionKey, address indexed approver);
    event ElectionRejected(bytes32 indexed electionKey, address indexed rejecter);
    event ElectionDuplicated(
        bytes32 indexed sourceKey,
        bytes32 indexed newKey,
        address indexed duplicator,
        uint256 timestamp
    );

    /// @notice Voter action. Retained because msg.sender's option-index and
    ///         tokens-cast IS also stored (votedOptionIndexOf / votedTokensOf),
    ///         but indexers rely on the event for cheap history queries.
    event VoteCast(
        bytes32 indexed electionKey,
        address indexed voter,
        uint256 optionIndex,
        uint256 tokensCastScaledTo18
    );

    /// @notice v43108: a GovernancePropose / GovernanceVote fee was pulled from `payer`
    ///         and pushed to the FeeManager's chained entities (total across entities).
    event FeeCharged(bytes32 indexed feeLabelHash, address indexed payer, uint256 amount);

    // ------------------------------------------------------------------
    // Deliberately NOT emitted (all data is queryable from state — save
    // bytecode + gas):
    //   • ElectionProposed          — data in Election struct + _allElectionKeys
    //   • ElectionActivated         — timestamp in Election.activatedTimestamp
    //   • ElectionSubmittedForApproval — data in Election struct + _awaitingApprovalKeys
    //   • ElectionClosed            — data in Election struct + _closedKeys;
    //                                  isValid derivable from the summary
    //   • FullRefreshRan            — effects visible via key-view lengths
    //
    // Off-chain clients that used to subscribe to these events should poll
    // getPendingElectionKeys() / getActiveElectionKeys() /
    // getClosedElectionKeys() / getAwaitingApprovalElectionKeys() and diff
    // key arrays against their last seen snapshot; hydrate deltas via
    // getElectionSummaries().
    // ------------------------------------------------------------------

    /* ========== CONSTRUCTOR ========== */

    // ===== PROXY BUILD: MODEL CONSTRUCTOR =====
    // No arguments; permanently locks the model. Clones never execute this.
    constructor() {
        _disableInitializers();
    }

    // ===== PROXY BUILD: CLONE CONSTRUCTOR-EQUIVALENT (former constructor, verbatim) =====
    /**
     * @param _controller  Project Controller for entity gating.
     * @param _feeManager  Project FeeManager. Cached in the retained
     *                     `feeManager` immutable. Governance itself does not
     *                     currently invoke fee flows, but the address is kept
     *                     for (a) constructor-signature parity with every
     *                     other project peer (BTM / DM / PRT / ReleaseManager
     *                     / CapitalCallManager) so the Factory bytecode-injects
     *                     `result.feeManager` uniformly and the UI needs no
     *                     change, and (b) the planned vote-fee feature.
     * @param _issueToken  Project IssueToken (balance source).
     *
     * @dev v43107: ExecutivePeerTreasury inheritance removed — the former
     *      parent's work (controller/feeManager/issueToken caching + the
     *      Controller.init() self-registration) is inlined below. Governance
     *      holds no funds by design, so none of the peer-treasury flows are
     *      needed here.
     *
     * @dev All governance parameters (durations, minimums, quorum, cap) are
     *      baked in with sensible defaults so ControllerFactory Phase 7 can
     *      pass just (controller, feeManager, issueToken). Post-deployment,
     *      any of the globals can be updated by a Controller-registered
     *      TokenAdmin via the setter functions.
     *
     *      The initial excluded-core-contract sync runs at the tail of the
     *      constructor.  Since Governance is the LAST contract added by
     *      Phase 7, the Controller has already registered every phase-7 peer
     *      by the time this body runs — including this contract itself, whose
     *      registration was performed by the direct init() call above.
     */
    function initialize(
        address _controller,
        address _feeManager,
        address _issueToken
    ) external initializer {
        if (_controller == address(0)) revert InvalidController();
        if (_issueToken == address(0)) revert ZeroTokenAddress();

        peerTreasuryController = _controller;
        feeManager = _feeManager;
        issueTokenAddress = _issueToken;

        // Self-register as a SmartContract entity on the project Controller
        // (formerly performed inside ExecutivePeerTreasury's constructor).
        IController(_controller).init(address(this), "Governance");

        uint8 dec = IGovernanceToken(_issueToken).decimals();
        if (dec > 18) revert UnsupportedDecimals();
        tokenDecimalsCached = dec;
        dec18Scale = 10 ** (uint256(18) - uint256(dec));

        voteDurationInDays            = DEFAULT_VOTE_DURATION_DAYS;
        previewDurationInDays         = DEFAULT_PREVIEW_DURATION_DAYS;
        maxActiveElections            = DEFAULT_MAX_ACTIVE_ELECTIONS;
        minTokenRequiredToProposeVote = DEFAULT_MIN_TOKENS_TO_PROPOSE;
        minTokensRequiredToVote       = DEFAULT_MIN_TOKENS_TO_VOTE;
        minTokenTallyPercentToWin     = DEFAULT_MIN_TOKEN_TALLY_PCT_TO_WIN;
        minTokenPercentVoted          = DEFAULT_MIN_TOKEN_PCT_VOTED;
        maxPendingApprovalElections   = DEFAULT_MAX_PENDING_APPROVAL_ELECTIONS;
        // requireAdminApprovalToPropose defaults to false — no explicit init needed.

        _syncExcludedCoreContractsInternal();
    }

    /* ========== AUTH HELPERS ========== */

    function _isTokenAdmin(address who) internal view returns (bool) {
        return IController(peerTreasuryController).isOfficialEntityFast(KECCAK_TOKEN_ADMIN, who);
    }

    function _requireTokenAdmin() internal view {
        if (!_isTokenAdmin(msg.sender)) revert NotTokenAdmin();
    }

    /* ========== v43108 FEES (GovernancePropose / GovernanceVote) ========== */

    /// @notice Project stablecoin the GovernancePropose / GovernanceVote fees are paid in.
    ///         Read LIVE from IssueToken.stableCoinAddress() — nothing is cached here, so
    ///         Governance can never drift from the IssueToken (no setter, no syncer); the UI
    ///         approves / permits exactly what this returns. address(0) when the IssueToken
    ///         reports none — then any non-zero fee reverts FeeStablecoinNotSet.
    function stableCoinAddress() public view returns (address stable) {
        (bool ok, bytes memory data) = issueTokenAddress.staticcall(abi.encodeWithSignature("stableCoinAddress()"));
        if (ok && data.length == 32) stable = abi.decode(data, (address));
    }

    /// @notice Current fee for `feeLabelHash` (KECCAK_FEE_GOV_PROPOSE / KECCAK_FEE_GOV_VOTE)
    ///         in stablecoin atomics; 0 = none / label absent on this FeeManager. UI pre-flight.
    function quoteFee(bytes32 feeLabelHash) public view returns (uint256 total) {
        (, total) = _quoteFee(feeLabelHash);
    }

    /// @dev Absolute-only quote (totalVal = 0). Missing label / no FeeManager → (empty, 0).
    function _quoteFee(bytes32 label)
        private view
        returns (IFeeManager.CalculatedEntityAmount[] memory fees, uint256 total)
    {
        address fm = feeManager;
        if (fm == address(0)) return (fees, 0);
        try IFeeManager(fm).calculateChainedAmounts(0, 10000, label)
            returns (IFeeManager.CalculatedEntityAmount[] memory f, uint256 t)
        {
            return (f, t);
        } catch {
            return (fees, 0);
        }
    }

    /// @dev Pull the quoted fee from msg.sender (optional EIP-2612 permit executed
    ///      atomically) and push every share straight to its fee entity — Governance
    ///      never retains a balance. No-op when the fee is 0.
    function _chargeFee(bytes32 label, uint256 permitDeadline, uint8 v, bytes32 r, bytes32 s) private {
        (IFeeManager.CalculatedEntityAmount[] memory fees, uint256 total) = _quoteFee(label);
        if (total == 0) return;
        address stable = stableCoinAddress();
        if (stable == address(0)) revert FeeStablecoinNotSet();
        if (permitDeadline != 0) {
            IGovStable(stable).permit(msg.sender, address(this), total, permitDeadline, v, r, s);
        }
        if (!IGovStable(stable).transferFrom(msg.sender, address(this), total)) revert FeeTransferFailed();
        for (uint256 i = 0; i < fees.length; i++) {
            if (fees[i].amount == 0 || fees[i].entityAddress == address(0)) continue;
            if (!IGovStable(stable).transfer(fees[i].entityAddress, fees[i].amount)) revert FeeTransferFailed();
        }
        emit FeeCharged(label, msg.sender, total);
    }

    /* ========== SYNC OF EXCLUDED CORE-CONTRACT LIST ========== */

    /// @notice Re-populate the cached excluded core-contract list from the
    ///         project Controller. Callable by ANY address.
    function syncExcludedCoreContracts() external {
        _syncExcludedCoreContractsInternal();
    }

    function _syncExcludedCoreContractsInternal() internal {
        uint256 oldLen = _excludedList.length;
        for (uint256 i = 0; i < oldLen; i++) {
            isExcludedCoreContract[_excludedList[i]] = false;
        }
        delete _excludedList;

        // v43107: active-only (the loop filtered on .active anyway; false is
        // O(active) on new-model Controllers).
        IController.OfficialEntityStruct[] memory scList =
            IController(peerTreasuryController).getAllOfficialEntities("SmartContract", false);

        uint256 added = 0;
        for (uint256 i = 0; i < scList.length; i++) {
            if (!scList[i].active) continue;
            address a = scList[i].pubAddress;
            if (a == address(0)) continue;
            if (isExcludedCoreContract[a]) continue; // dedup
            isExcludedCoreContract[a] = true;
            _excludedList.push(a);
            added++;
        }

        emit ExcludedCoreContractsSynced(added, msg.sender);
    }

    /* ========== ADMIN SETTERS (TokenAdmin-only, GLOBAL) ========== */
    /// @dev The two setters that mutate a DURATION global
    ///      (setVoteDurationInDays, setPreviewDurationInDays) end with a
    ///      _refresh(true) so that any elections already-in-flight resettle
    ///      into the correct phase — see _refresh(bool full) for why the
    ///      fast walk cannot be trusted after a duration change. All other
    ///      setters either (a) don't affect existing elections at all
    ///      (thresholds are frozen per-election at activation) or (b) only
    ///      gate FUTURE calls (caps, approval-gate toggle), and so require
    ///      no refresh.

    // NOTE: Admin setters below no longer emit *Updated events. See the
    // NOTE block at the top of the EVENTS section for the rationale
    // (state-readable + per-election frozen copies + explorer calldata).

    function setVoteDurationInDays(uint256 newDays) external {
        _requireTokenAdmin();
        if (newDays == 0 || newDays > MAX_VOTE_DURATION_DAYS_CEILING) revert InvalidVoteDuration();
        voteDurationInDays = newDays;
        _refresh(true); // full sweep — see _refresh(bool full) for rationale
    }

    function setPreviewDurationInDays(uint256 newDays) external {
        _requireTokenAdmin();
        if (newDays > MAX_PREVIEW_DURATION_DAYS_CEILING) revert InvalidPreviewDuration();
        previewDurationInDays = newDays;
        _refresh(true); // full sweep — see _refresh(bool full) for rationale
    }

    function setMaxActiveElections(uint256 newMax) external {
        _requireTokenAdmin();
        if (newMax == 0 || newMax > MAX_ACTIVE_ELECTIONS_CEILING) revert InvalidMaxActiveElections();
        maxActiveElections = newMax;
        // No _refresh(true) — this cap only gates FUTURE proposals; it does
        // not change the derived timestamps of already-open elections and
        // therefore preserves the ordering invariant used by _refresh(false).
    }

    function setMinTokenRequiredToProposeVote(uint256 newValue) external {
        _requireTokenAdmin();
        minTokenRequiredToProposeVote = newValue;
    }

    function setMinTokensRequiredToVote(uint256 newValue) external {
        _requireTokenAdmin();
        minTokensRequiredToVote = newValue;
    }

    function setMinTokenTallyPercentToWin(uint256 newPct) external {
        _requireTokenAdmin();
        if (newPct > 100) revert InvalidPercent();
        minTokenTallyPercentToWin = newPct;
        // Not lifecycle-affecting for open elections (each froze its own
        // percent at activation time), so no _refresh(true) needed here.
    }

    function setMinTokenPercentVoted(uint256 newPct) external {
        _requireTokenAdmin();
        if (newPct > 100) revert InvalidPercent();
        minTokenPercentVoted = newPct;
        // Same rationale as setMinTokenTallyPercentToWin — frozen per-election.
    }

    /// @notice Toggle the global admin-approval gate. When true, new
    ///         proposeElection() calls route into _awaitingApprovalKeys
    ///         instead of the lifecycle. Toggling does NOT retroactively
    ///         change already-queued or already-created elections —
    ///         existing queue entries still require explicit approve/reject.
    function setRequireAdminApprovalToPropose(bool value) external {
        _requireTokenAdmin();
        requireAdminApprovalToPropose = value;
        // Not lifecycle-affecting (no _refresh(true)) — the flag only
        // branches FUTURE proposals; already-created elections keep their
        // queue.
    }

    /// @notice Adjust the cap on the admin-approval queue length. Shrinking
    ///         below the current queue length is allowed — no existing
    ///         entries are evicted, but new submissions revert with
    ///         ApprovalQueueFull until the queue drains below the new cap.
    function setMaxPendingApprovalElections(uint256 newMax) external {
        _requireTokenAdmin();
        if (newMax == 0 || newMax > MAX_PENDING_APPROVAL_ELECTIONS_CEILING) {
            revert InvalidMaxPendingApprovalElections();
        }
        maxPendingApprovalElections = newMax;
    }

    /* ========== ADMIN SETTER (TokenAdmin-only, PER-ELECTION) ========== */

    /// @notice TokenAdmin-only: mark a formally-CLOSED election as
    ///         implemented / not implemented. Purely a bookkeeping flag with
    ///         no on-chain side-effects beyond powering the filtered closed-
    ///         viewer pair. Reverts if the election is not yet formally
    ///         closed (closedAtTimestamp == 0). Idempotent — writing the
    ///         same value twice is allowed but still emits the event.
    ///
    ///         A cheap _refresh() is invoked at the top so an expired-but-
    ///         not-yet-refreshed election gets its close applied before we
    ///         check the gate, keeping "I can see it in the closed list" and
    ///         "I can flag it" in sync.
    function setElectionImplemented(bytes32 electionKey, bool value) external {
        _requireTokenAdmin();
        _refresh(false);
        Election storage e = _elections[electionKey];
        // Sentinel check omitted — a garbage key has closedAtTimestamp == 0
        // and reverts with ElectionNotClosed. Admin-only path.
        if (e.closedAtTimestamp == 0) revert ElectionNotClosed();
        if (value) e.flags |= _F_IS_IMPLEMENTED;
        else       e.flags &= ~_F_IS_IMPLEMENTED;
        emit ElectionImplementationSet(electionKey, value, msg.sender);
    }

    /* ========== LIFECYCLE REFRESH ========== */

    /// @notice Fast refresh. Walks the FRONT of pending + active until it
    ///         hits an entry still in-bucket, then stops. Auto-invoked at
    ///         the start of every proposeElection() / duplicateElection() /
    ///         castVote() / approveElection().
    ///
    ///         A separate `fullRefresh()` external does NOT exist — the two
    ///         admin setters that ever break the ordering invariant
    ///         (setVoteDurationInDays, setPreviewDurationInDays) call
    ///         `_refresh(true)` themselves. There is no state the fast
    ///         path can leave uncorrected that a subsequent
    ///         propose/vote/approve wouldn't itself resolve on its next
    ///         refresh call, so exposing a manual full-sweep trigger to
    ///         users is unnecessary.
    function refreshElections() external { _refresh(false); }

    /**
     * @dev Combined refresh. Passing `full=false` runs the fast head-of-
     *      queue early-exit walk used by the hot path (propose / vote /
     *      duplicate / approve). Passing `full=true` runs the O(N) rebuild
     *      that admin duration-setters must call.
     *
     *      Why `full=true` is required after duration-setter changes:
     *        Array push order is ACTIVATION-timestamp order. But the fast
     *        walk compares `activeFromTimestamp` (=
     *        activatedTimestamp + previewDurationInDaysAtActivation * 1 days)
     *        for Pending→Active, and `closesAtTimestamp` (=
     *        activeFromTimestamp + voteDurationInDaysAtActivation * 1 days)
     *        for Active→Closed. Each entry freezes its OWN preview /
     *        vote duration at activation. So if admin changes those
     *        globals between two activations, a later-activated entry can
     *        have an EARLIER `activeFromTimestamp` (or `closesAtTimestamp`)
     *        than one in front of it — the array ordering by those
     *        derived timestamps breaks. The fast walk's early-exit `break`
     *        would then miss the middle stragglers. The full sweep resolves
     *        this by visiting every entry, not just the front.
     */
    function _refresh(bool full) internal {
        uint256 nowTs = block.timestamp;

        // ============ Pass 1: Pending → Active ============
        uint256 pLen = _pendingKeys.length;
        if (!full) {
            // Fast walk — early exit. Correct as long as the derived
            // activeFromTimestamp order matches array order, which holds
            // as long as no duration-setter has been called since the last
            // full sweep (_refresh(true) triggered by setVoteDurationInDays
            // / setPreviewDurationInDays).
            while (_pendingHead < pLen) {
                bytes32 k = _pendingKeys[_pendingHead];
                Election storage e = _elections[k];
                if (e.activeFromTimestamp > nowTs) break;
                _pendingHead++;
                _activeKeys.push(k);
            }
        } else {
            // Full sweep — visit every entry from head to end, promote /
            // close eligible ones, rebuild the tail with survivors so the
            // fast walk works again afterwards.
            uint256 stillPCount = 0;
            for (uint256 i = _pendingHead; i < pLen; i++) {
                Election storage e = _elections[_pendingKeys[i]];
                if (nowTs < e.activeFromTimestamp) stillPCount++;
            }
            bytes32[] memory stillPending = new bytes32[](stillPCount);
            uint256 pj = 0;
            for (uint256 i = _pendingHead; i < pLen; i++) {
                bytes32 k = _pendingKeys[i];
                Election storage e = _elections[k];
                if (nowTs >= e.closesAtTimestamp) {
                    // Would-be-active-then-closed within the same instant.
                    _closeElection(k, nowTs);
                } else if (nowTs >= e.activeFromTimestamp) {
                    _activeKeys.push(k);
                } else {
                    stillPending[pj++] = k;
                }
            }
            delete _pendingKeys;
            _pendingHead = 0;
            for (uint256 i = 0; i < stillPending.length; i++) {
                _pendingKeys.push(stillPending[i]);
            }
        }

        // ============ Pass 2: Active → Closed ============
        uint256 aLen = _activeKeys.length;
        if (!full) {
            while (_activeHead < aLen) {
                bytes32 k = _activeKeys[_activeHead];
                Election storage e = _elections[k];
                if (e.closesAtTimestamp > nowTs) break;
                _activeHead++;
                _closeElection(k, nowTs);
            }
        } else {
            uint256 stillACount = 0;
            for (uint256 i = _activeHead; i < aLen; i++) {
                Election storage e = _elections[_activeKeys[i]];
                if (e.closedAtTimestamp != 0) continue;
                if (nowTs < e.closesAtTimestamp) stillACount++;
            }
            bytes32[] memory stillActive = new bytes32[](stillACount);
            uint256 aj = 0;
            for (uint256 i = _activeHead; i < aLen; i++) {
                bytes32 k = _activeKeys[i];
                Election storage e = _elections[k];
                if (e.closedAtTimestamp != 0) continue;
                if (nowTs >= e.closesAtTimestamp) {
                    _closeElection(k, nowTs);
                } else {
                    stillActive[aj++] = k;
                }
            }
            delete _activeKeys;
            _activeHead = 0;
            for (uint256 i = 0; i < stillActive.length; i++) {
                _activeKeys.push(stillActive[i]);
            }
        }
    }

    /// @dev Compute winner, snapshot the winning string, and append to
    ///      _closedKeys. The winning option is the one whose tokensTally is
    ///      strictly highest. Ties and no-vote outcomes are flagged and
    ///      leave winningOptionText empty.
    function _closeElection(bytes32 k, uint256 nowTs) private {
        Election storage e = _elections[k];
        e.closedAtTimestamp = nowTs;

        // Eligible-supply snapshot. Taken HERE (at close) rather than at
        // activation so quorum thresholds measure the shareholder supply
        // that was in force at the moment voting concluded. See the
        // CLOSE-TIME VOTABLE-SUPPLY SNAPSHOT section of the contract NatSpec.
        e.totalTokensVotableAtClose = _snapshotVotableSupply();

        uint256 highest    = 0;
        uint256 winnerIdx  = 0;
        uint256 tiedAtTop  = 0;
        uint256 optCount   = e.options.length;

        for (uint256 i = 0; i < optCount; i++) {
            uint256 t = e.options[i].tokensTally;
            if (t > highest) {
                highest = t;
                winnerIdx = i;
                tiedAtTop = 1;
            } else if (t == highest && t > 0) {
                tiedAtTop++;
            }
        }

        // Set noVotes / tie via bitmask on flags. Default at close is that
        // both are 0 (uninitialized) so we only need to SET the true cases —
        // no explicit "&= ~_F_TIE" is needed because we've never set it.
        if (e.totalTokensVoted == 0) {
            e.flags |= _F_NO_VOTES;
            e.winningOptionIndex = 0;
            e.winningTokensTally = 0;
            e.winningOptionText  = "";
        } else if (tiedAtTop > 1) {
            e.flags |= _F_TIE;
            e.winningOptionIndex = winnerIdx; // first-encountered max
            e.winningTokensTally = highest;
            e.winningOptionText  = "";
        } else {
            e.winningOptionIndex = winnerIdx;
            e.winningTokensTally = highest;
            e.winningOptionText  = e.options[winnerIdx].text;
        }

        _closedKeys.push(k);
        // Deliberately no event emit — all data queryable via
        // getElectionSummaries([k]) (see EVENTS block for rationale).
    }

    /// @dev Full validity check for a CLOSED election. Applies both
    ///      frozen quorums against the close-time eligible-supply snapshot
    ///      (totalTokensVotableAtClose — see contract NatSpec). Ties and
    ///      empty-vote closes are unconditionally invalid.
    function _isValidWinner(Election storage e) internal view returns (bool) {
        if ((e.flags & (_F_NO_VOTES | _F_TIE)) != 0) return false;

        uint256 votable = e.totalTokensVotableAtClose;

        // Participation quorum:  totalTokensVoted * 100 >= votable * pctVoted
        uint256 pctVoted = e.minTokenPercentVotedAtActivation;
        if (pctVoted != 0) {
            if (e.totalTokensVoted * 100 < votable * pctVoted) return false;
        }

        // Winning-option quorum:  winningTokensTally * 100 >= votable * pctWin
        uint256 pctWin = e.minTokenTallyPercentToWinAtActivation;
        if (pctWin != 0) {
            if (e.winningTokensTally * 100 < votable * pctWin) return false;
        }

        return true;
    }

    /* ========== ELIGIBLE-SUPPLY SNAPSHOT ========== */

    /// @dev Live snapshot of the eligible shareholder supply, scaled to
    ///      18-decimal precision. Excluded core contracts (from the current
    ///      cache) are subtracted from totalSupply so quorum percentages
    ///      measure "shareholder-held" tokens rather than circulating
    ///      supply that includes contract-held allocations. Called from
    ///      _closeElection() (to freeze the snapshot on-chain).
    function _snapshotVotableSupply() internal view returns (uint256) {
        uint256 total = IGovernanceToken(issueTokenAddress).totalSupply();
        uint256 excluded = 0;
        uint256 n = _excludedList.length;
        for (uint256 i = 0; i < n; i++) {
            excluded += IGovernanceToken(issueTokenAddress).balanceOf(_excludedList[i]);
        }
        if (excluded > total) excluded = total; // defensive
        return (total - excluded) * dec18Scale;
    }

    /* ========== PROPOSE + ADMIN APPROVAL ========== */

    /**
     * @notice Propose a new election. See the APPROVAL GATE + STATE
     *         BOOLEANS + DUPLICATION sections of the contract-level NatSpec
     *         for the full flow.
     *
     *         AUTH: msg.sender must NOT be a Controller-registered
     *         SmartContract, AND EITHER hold >= minTokenRequiredToProposeVote,
     *         OR be a Controller-registered TokenAdmin (TokenAdmins may open
     *         votes without holding any tokens themselves).
     */
    function proposeElection(string calldata title, string[] calldata options)
        external
        nonReentrant
        returns (bytes32 electionKey)
    {
        _chargeFee(KECCAK_FEE_GOV_PROPOSE, 0, 0, bytes32(0), bytes32(0));
        return _registerNewElection(msg.sender, title, options, bytes32(0));
    }

    /// @notice v43108: proposeElection with the GovernancePropose fee's EIP-2612 permit
    ///         bundled (one signature, one tx). permitDeadline 0 = rely on a prior approve.
    function proposeElectionWithPermit(
        string calldata title,
        string[] calldata options,
        uint256 permitDeadline,
        uint8 permitV,
        bytes32 permitR,
        bytes32 permitS
    ) external nonReentrant returns (bytes32 electionKey) {
        _chargeFee(KECCAK_FEE_GOV_PROPOSE, permitDeadline, permitV, permitR, permitS);
        return _registerNewElection(msg.sender, title, options, bytes32(0));
    }

    /**
     * @notice TokenAdmin-only: clone the title + option-texts of a CLOSED
     *         source election into a fresh election, wired up as a
     *         duplicate for provenance tracking. See DUPLICATION in the
     *         contract-level NatSpec.
     *
     *         The new election obeys the current requireAdminApprovalToPropose
     *         setting — if the gate is on when duplicateElection runs, the
     *         clone lands in the approval queue and must be admin-approved
     *         before it can start voting. (The admin who called
     *         duplicateElection can then call approveElection immediately
     *         in the same tx if desired.)
     */
    function duplicateElection(bytes32 sourceKey)
        external
        nonReentrant
        returns (bytes32 newKey)
    {
        _requireTokenAdmin();
        // v43108: a duplicate is a new proposal — same GovernancePropose fee (prior approve).
        _chargeFee(KECCAK_FEE_GOV_PROPOSE, 0, 0, bytes32(0), bytes32(0));
        Election storage src = _elections[sourceKey];
        // Sentinel check omitted — a garbage sourceKey has closedAtTimestamp == 0
        // and reverts with CannotDuplicateBeforeClose. Same holds for rejected
        // proposals (which never reach closed state). Admin-only path,
        // indirect error name on typos is acceptable.
        if (src.closedAtTimestamp == 0) revert CannotDuplicateBeforeClose();

        string memory titleCopy = src.title;
        uint256 optCount = src.options.length;
        string[] memory optsCopy = new string[](optCount);
        for (uint256 i = 0; i < optCount; i++) {
            optsCopy[i] = src.options[i].text;
        }

        newKey = _registerNewElection(msg.sender, titleCopy, optsCopy, sourceKey);
        emit ElectionDuplicated(sourceKey, newKey, msg.sender, block.timestamp);
    }

    /**
     * @dev Shared "write a new election slot" helper. Called by
     *      proposeElection (fresh proposal, duplicatedFromKey == 0) and
     *      duplicateElection (revote clone, duplicatedFromKey == source).
     *      Runs refresh, auth, validation, cap-check; writes the initial
     *      struct fields; populates the proposer + duplicate indices; then
     *      routes to either the approval queue or _activateElection.
     *
     *      calldata args in proposeElection are implicitly copied to memory
     *      here (Solidity 0.8 handles the calldata→memory conversion on
     *      internal-call boundaries).
     */
    function _registerNewElection(
        address proposer,
        string memory title,
        string[] memory options,
        bytes32 duplicatedFromKey
    ) private returns (bytes32 electionKey) {
        _refresh(false);

        if (isExcludedCoreContract[proposer]) revert ProposerIsCoreContract();
        // TokenAdmins bypass the minimum-holdings check. duplicateElection
        // is TokenAdmin-only at its external entry, so the min-tokens check
        // is a no-op for that path.
        if (!_isTokenAdmin(proposer)) {
            uint256 proposerBalance18 =
                IGovernanceToken(issueTokenAddress).balanceOf(proposer) * dec18Scale;
            if (proposerBalance18 < minTokenRequiredToProposeVote) revert InsufficientProposerBalance();
        }

        uint256 tLen = bytes(title).length;
        if (tLen == 0) revert EmptyTitle();
        if (tLen > MAX_TITLE_LENGTH) revert TitleTooLong();

        uint256 n = options.length;
        if (n < MIN_OPTIONS || n > MAX_OPTIONS) revert InvalidOptionCount();
        for (uint256 i = 0; i < n; i++) {
            uint256 oLen = bytes(options[i]).length;
            if (oLen == 0) revert EmptyOptionText();
            if (oLen > MAX_OPTION_TEXT_LENGTH) revert OptionTextTooLong();
        }

        // Cap check runs BEFORE any storage writes so a full-queue revert
        // doesn't waste SSTOREs on options / title.
        bool routeToApprovalQueue = requireAdminApprovalToPropose;
        if (routeToApprovalQueue) {
            if (_awaitingApprovalKeys.length >= maxPendingApprovalElections) revert ApprovalQueueFull();
        } else {
            uint256 openCount =
                (_pendingKeys.length - _pendingHead) + (_activeKeys.length - _activeHead);
            if (openCount >= maxActiveElections) revert TooManyOpenElections();
        }

        electionKey = keccak256(abi.encode(block.number, proposer));
        Election storage e = _elections[electionKey];
        // Sentinel: proposer is written exactly once (here) and never
        // cleared. Rejected slots RETAIN their proposer, which means a
        // proposer cannot re-collide the same key with a rejected slot —
        // resubmission works because block.number moves forward and the
        // key derivation includes block.number.
        if (e.proposer != address(0)) revert ElectionAlreadyExists();

        uint256 nowTs = block.timestamp;
        // Fresh slot: flags starts at 0 (mapping default). No _F_IS_REJECTED
        // bit to set here — that's the whole point of the flip.
        e.title = title;
        e.proposer = proposer;
        e.startBlock = block.number;
        e.submittedAtTimestamp = nowTs;
        e.duplicatedFromKey = duplicatedFromKey;   // 0 for fresh proposals
        for (uint256 i = 0; i < n; i++) {
            e.options.push(ElectionOption({ text: options[i], tokensTally: 0, voterCount: 0 }));
        }

        _electionsByProposer[proposer].push(electionKey);

        // Duplicate bookkeeping — after the new slot is written so a
        // mid-tx read of the source picks up the incremented counter.
        if (duplicatedFromKey != bytes32(0)) {
            _duplicateElectionKeys.push(electionKey);
            _elections[duplicatedFromKey].numDuplicates += 1;
        }

        if (routeToApprovalQueue) {
            // Fresh slot, so `flags` is 0 here — direct assignment beats
            // a read-modify-write OR by one opcode.
            e.flags = _F_AWAITING_APPROVAL;
            _awaitingApprovalKeys.push(electionKey);
            // No event — enqueue is queryable via
            // getAwaitingApprovalElectionKeys() + getElectionSummaries().
        } else {
            _activateElection(electionKey);
        }
    }

    /**
     * @notice TokenAdmin-only: promote a queued proposal into the Pending →
     *         Active → Closed lifecycle. Frozen globals are captured HERE
     *         (approval time), not at submission, so the election's terms
     *         match the state of the world when its clock actually starts.
     *         (The eligible-supply snapshot is still deferred to CLOSE —
     *         see CLOSE-TIME VOTABLE-SUPPLY SNAPSHOT in the contract NatSpec.)
     *
     *         _refresh() runs first so a natural close of an already-active
     *         election may free lifecycle capacity in the same tx.
     */
    function approveElection(bytes32 electionKey) external nonReentrant {
        _requireTokenAdmin();
        _refresh(false);

        Election storage e = _elections[electionKey];
        uint8 f = e.flags;
        // Sentinel check omitted — a garbage key has flags == 0, so the
        // AWAITING_APPROVAL check below reverts with ElectionNotAwaitingApproval.
        // Admin-only path, so a slightly indirect error name on typos is
        // acceptable.
        if ((f & _F_AWAITING_APPROVAL) == 0)  revert ElectionNotAwaitingApproval();

        // Lifecycle capacity gate — separate from the approval-queue cap.
        uint256 openCount =
            (_pendingKeys.length - _pendingHead) + (_activeKeys.length - _activeHead);
        if (openCount >= maxActiveElections) revert TooManyOpenElections();

        // Clear AWAITING_APPROVAL + set IS_APPROVED in a single SSTORE.
        // isApproved is flipped BEFORE _activateElection so a same-tx read
        // (e.g. by an admin dashboard listening for the ElectionApproved
        // event and immediately calling getElectionSummaries) picks it up.
        // See the STATE BOOLEANS section of the contract-level NatSpec.
        e.flags = (f & ~_F_AWAITING_APPROVAL) | _F_IS_APPROVED;

        _removeFromApprovalQueue(electionKey);
        _activateElection(electionKey);

        emit ElectionApproved(electionKey, msg.sender);
    }

    /**
     * @notice TokenAdmin-only: mark a queued proposal as REJECTED. Sets
     *         _F_IS_REJECTED, clears _F_AWAITING_APPROVAL, and drops the key
     *         from the approval queue (via _removeFromApprovalQueue) so the
     *         admin's TODO shrinks.
     *
     *         The Election storage slot is INTENTIONALLY preserved — its
     *         title/proposer/options/submittedAtTimestamp remain readable
     *         through getElectionSummaries and are counted in every
     *         historical list view (_allElectionKeys, _electionsByProposer,
     *         etc.). Clients are expected to filter on
     *         `(summary.flags & 0x01) != 0` when rejected rows are unwanted.
     *
     *         Because the storage slot is NOT deleted, the sentinel that
     *         guards "already exists" checks in _registerNewElection is
     *         `e.proposer != address(0)` (proposer is set once and never
     *         cleared). Resubmission from a later block works because the
     *         election key includes block.number.
     */
    function rejectElection(bytes32 electionKey) external {
        _requireTokenAdmin();
        Election storage e = _elections[electionKey];
        uint8 f = e.flags;
        // Sentinel check omitted — see approveElection for the same
        // rationale (garbage key → flags == 0 → AWAITING_APPROVAL check
        // reverts with ElectionNotAwaitingApproval).
        if ((f & _F_AWAITING_APPROVAL) == 0) revert ElectionNotAwaitingApproval();

        // Clear AWAITING_APPROVAL + set IS_REJECTED in one SSTORE.
        e.flags = (f & ~_F_AWAITING_APPROVAL) | _F_IS_REJECTED;

        _removeFromApprovalQueue(electionKey);

        emit ElectionRejected(electionKey, msg.sender);
    }

    /// @dev Swap-and-pop removal from _awaitingApprovalKeys. Order in the
    ///      queue is NOT preserved — clients that care about "submitted
    ///      first" order should sort on submittedAtTimestamp themselves.
    function _removeFromApprovalQueue(bytes32 key) private {
        uint256 len = _awaitingApprovalKeys.length;
        for (uint256 i = 0; i < len; i++) {
            if (_awaitingApprovalKeys[i] == key) {
                uint256 lastIdx = len - 1;
                if (i != lastIdx) {
                    _awaitingApprovalKeys[i] = _awaitingApprovalKeys[lastIdx];
                }
                _awaitingApprovalKeys.pop();
                return;
            }
        }
        // If we reach here, the awaitingApproval flag was set but the key
        // wasn't in the queue — invariant violation. Defensive no-op rather
        // than revert so callers can still recover manually via reject.
    }

    /**
     * @dev Set the election in motion — freezes the four frozen-globals,
     *      computes derived timestamps, flips isActivated=true, and pushes
     *      to _allElectionKeys + _pendingKeys. THE SINGLE place isActivated
     *      is ever set true; if you find any other call site flipping it,
     *      that's a bug. isApproved is NOT touched here — see approveElection.
     *      Called from:
     *        - _registerNewElection() (direct path, when the approval gate
     *          is off; used by both proposeElection and duplicateElection).
     *        - approveElection() (approval-gated path, at admin approval time,
     *          AFTER approveElection has flipped isApproved=true).
     *
     *      NOT called on: awaiting-approval slots (before approve) or
     *      rejected slots (which are deleted outright).
     *
     *      Preconditions (caller-enforced):
     *        - e.proposer != address(0) (proposer identity, title, options,
     *          submittedAtTimestamp already written by _registerNewElection).
     *        - (e.flags & _F_AWAITING_APPROVAL) == 0.
     *        - (e.flags & _F_IS_REJECTED) == 0 — trivially true from the
     *          existing call sites (proposeElection direct path skips
     *          rejected; approveElection can't fire on a rejected slot
     *          because its awaitingApproval bit was cleared at reject).
     *        - Lifecycle capacity has already been checked by the caller.
     *
     *      NOTE: totalTokensVotableAtClose is NOT frozen here — that
     *      snapshot is taken in _closeElection(). See CLOSE-TIME
     *      VOTABLE-SUPPLY SNAPSHOT in the contract-level NatSpec.
     */
    function _activateElection(bytes32 electionKey) private {
        Election storage e = _elections[electionKey];
        uint256 nowTs = block.timestamp;

        // activatedTimestamp == when the LIFECYCLE begins. For the direct
        // path this equals e.submittedAtTimestamp; for the approval-gated
        // path it's strictly later.
        e.activatedTimestamp = nowTs;

        e.voteDurationInDaysAtActivation        = voteDurationInDays;
        e.previewDurationInDaysAtActivation     = previewDurationInDays;
        e.minTokenTallyPercentToWinAtActivation = minTokenTallyPercentToWin;
        e.minTokenPercentVotedAtActivation      = minTokenPercentVoted;
        // totalTokensVotableAtClose intentionally NOT set here.

        e.activeFromTimestamp = nowTs + (previewDurationInDays * 1 days);
        e.closesAtTimestamp   = e.activeFromTimestamp + (voteDurationInDays * 1 days);

        // Flip the "in motion" flag. isApproved is NOT set here — the
        // direct path (no admin review) must leave isApproved = false to
        // preserve the "was there a human review?" semantic. isApproved
        // is set exclusively in approveElection().
        e.flags |= _F_IS_ACTIVATED;

        _allElectionKeys.push(electionKey);
        _pendingKeys.push(electionKey);
        // No event — all data queryable via getElectionSummaries([electionKey]).
    }

    /* ========== VOTE ========== */

    function castVote(bytes32 electionKey, uint256 optionIndex) external nonReentrant {
        _castVote(electionKey, optionIndex, 0, 0, bytes32(0), bytes32(0));
    }

    /// @notice v43108: castVote with the GovernanceVote fee's EIP-2612 permit bundled
    ///         (one signature, one tx). permitDeadline 0 = rely on a prior approve.
    function castVoteWithPermit(
        bytes32 electionKey,
        uint256 optionIndex,
        uint256 permitDeadline,
        uint8 permitV,
        bytes32 permitR,
        bytes32 permitS
    ) external nonReentrant {
        _castVote(electionKey, optionIndex, permitDeadline, permitV, permitR, permitS);
    }

    /// @dev Shared vote body. The GovernanceVote fee is charged AFTER every eligibility
    ///      check and the double-vote guard (so a rejected vote costs nothing) and BEFORE
    ///      the tally writes; hasVoted makes it once per voter per election by construction.
    function _castVote(
        bytes32 electionKey,
        uint256 optionIndex,
        uint256 permitDeadline,
        uint8 permitV,
        bytes32 permitR,
        bytes32 permitS
    ) private {
        _refresh(false);

        Election storage e = _elections[electionKey];
        if (e.proposer == address(0)) revert ElectionNotFound();
        uint8 f = e.flags;
        // Rejected proposals never entered the lifecycle (no activated
        // timestamps) — the activeFromTimestamp / closesAtTimestamp checks
        // below would revert them with ElectionNotActive anyway, but the
        // explicit early revert here surfaces a clearer client-side error.
        if ((f & _F_IS_REJECTED) != 0)       revert ElectionNotActive();
        if ((f & _F_AWAITING_APPROVAL) != 0) revert ElectionNotActive();

        uint256 nowTs = block.timestamp;
        if (e.closedAtTimestamp != 0) revert ElectionNotActive();
        if (nowTs < e.activeFromTimestamp || nowTs >= e.closesAtTimestamp) revert ElectionNotActive();

        if (optionIndex >= e.options.length) revert InvalidOptionIndex();

        if (isExcludedCoreContract[msg.sender]) revert VoterIsCoreContract();

        uint256 voterBalance18 =
            IGovernanceToken(issueTokenAddress).balanceOf(msg.sender) * dec18Scale;
        if (voterBalance18 < minTokensRequiredToVote) revert InsufficientVoterBalance();

        if (hasVoted[electionKey][msg.sender]) revert AlreadyVoted();

        _chargeFee(KECCAK_FEE_GOV_VOTE, permitDeadline, permitV, permitR, permitS);

        hasVoted[electionKey][msg.sender] = true;
        votedOptionIndexOf[electionKey][msg.sender] = optionIndex;
        votedTokensOf[electionKey][msg.sender] = voterBalance18;

        ElectionOption storage opt = e.options[optionIndex];
        opt.tokensTally += voterBalance18;
        opt.voterCount  += 1;

        e.totalNumberVoted += 1;
        e.totalTokensVoted += voterBalance18;

        emit VoteCast(electionKey, msg.sender, optionIndex, voterBalance18);
    }

    /* ========== VIEWS — SINGLE ELECTION ========== */

    // NOTE: Phase (Pending / Active / Closed / AwaitingApproval) is now
    // derived CLIENT-SIDE from an ElectionSummary — no on-chain phase
    // view is exposed. The 7 lifecycle booleans on the summary live in
    // ElectionSummary.flags (uint8). The bit assignments are:
    //     0x02 _F_AWAITING_APPROVAL
    //     0x04 _F_IS_APPROVED
    //     0x08 _F_IS_ACTIVATED
    //     0x10 _F_IS_IMPLEMENTED
    //     0x20 _F_NO_VOTES
    //     0x40 _F_TIE
    //     0x80 _F_IS_VALID     (derived at hydrate time)
    //
    // Derivation rule (mirror this in every client):
    //   if (s.flags & 0x02)                                → AwaitingApproval
    //   else if (s.closedAtTimestamp != 0)                 → Closed
    //   else {
    //       activeFrom = s.activatedTimestamp
    //                  + s.previewDurationInDaysAtActivation * 86400
    //       closesAt   = activeFrom
    //                  + s.voteDurationInDaysAtActivation * 86400
    //       if (now >= closesAt)                           → Closed (stale, unrefreshed)
    //       else if (now < activeFrom)                     → Pending
    //       else                                           → Active
    //   }
    // A client that wants the stale-Closed entries formally moved into
    // _closedKeys should send a refreshElections() tx first.

    // NOTE: The public `computeElectionKey(uint256 blockNum, address proposer)
    //       external pure returns (bytes32)` helper was removed to save
    //       bytecode. The derivation is trivially reproducible by any
    //       client via `keccak256(abi.encode(uint256(blockNum), address(proposer)))`
    //       — the JS modal already does this locally when reporting the
    //       receipt after proposeElection.

    /// @notice The full options array for the given election. Callers that
    ///         only want a single option can index into the returned array
    ///         client-side — the on-chain single-option getter was removed
    ///         to save bytecode.
    function getElectionOptions(bytes32 electionKey)
        external
        view
        returns (ElectionOption[] memory)
    {
        Election storage e = _elections[electionKey];
        if (e.proposer == address(0)) revert ElectionNotFound();
        return e.options;
    }

    // NOTE: getElectionWinner() and _previewWinner() were removed for
    // bytecode. Post-close winner data is exposed via getElectionSummaries
    // (winningOptionIndex / winningOptionText / winningTokensTally / tie /
    // noVotes / isValid). Callers wanting an expired-but-not-yet-refreshed
    // preview should send a plain refreshElections() tx (anyone can call
    // it — no auth) and then read the summary, which is cheaper on-chain
    // than maintaining a dedicated preview code path.

    /* ========== VIEWS — SUMMARIES (two-call pattern) ========== */

    /**
     * @notice Wire-format summary of one election.
     *
     *         DERIVED / REDUNDANT fields (phase, activeFromTimestamp,
     *         closesAtTimestamp) are intentionally NOT included — clients
     *         compute them from the raw fields below. See the phase-derivation
     *         block-comment above getElectionSummaries for the formulas.
     *
     *         The 7 lifecycle booleans (isRejected, awaitingApproval,
     *         isApproved, isActivated, isImplemented, noVotes, tie) plus the
     *         derived `isValid` are PACKED into a single uint8 `flags` byte,
     *         re-using the same bit positions as Election.flags (bits 0..6),
     *         plus bit 7 for the derived `isValid`. Clients decode via the
     *         _F_* bit values — see the constants block near the top of the
     *         contract.
     *
     *           bit 0 (0x01) — isRejected  (permanent — see Election NatSpec)
     *           bit 1 (0x02) — awaitingApproval
     *           bit 2 (0x04) — isApproved
     *           bit 3 (0x08) — isActivated
     *           bit 4 (0x10) — isImplemented
     *           bit 5 (0x20) — noVotes
     *           bit 6 (0x40) — tie
     *           bit 7 (0x80) — isValid   (derived at hydrate time)
     */
    struct ElectionSummary {
        bytes32 key;
        string  title;
        address proposer;
        uint256 activatedTimestamp;
        uint256 closedAtTimestamp;
        uint256 voteDurationInDaysAtActivation;
        uint256 previewDurationInDaysAtActivation;
        uint256 minTokenTallyPercentToWinAtActivation;
        uint256 minTokenPercentVotedAtActivation;
        /// Zero until _closeElection(); see CLOSE-TIME VOTABLE-SUPPLY
        /// SNAPSHOT in the contract-level NatSpec.
        uint256 totalTokensVotableAtClose;
        uint256 totalNumberVoted;
        uint256 totalTokensVoted;
        uint256 optionCount;
        uint256 winningOptionIndex;
        string  winningOptionText;
        uint256 winningTokensTally;
        uint256 submittedAtTimestamp;
        bytes32 duplicatedFromKey;
        uint256 numDuplicates;
        /// Packed lifecycle booleans — see struct NatSpec above for bit map.
        uint8   flags;
    }

    // NOTE: The prior `_summarize(bytes32) → ElectionSummary` internal
    // helper has been INLINED into getElectionSummaries below (single
    // call site, saves one function frame). If any other view ever needs
    // hydration logic, extract it BACK to an internal helper rather than
    // duplicating this block.

    /* ==========================================================
     * VIEWS — TWO-CALL PATTERN
     * ----------------------------------------------------------
     * All list-returning views return bytes32[] (election keys).
     * ElectionSummary[] is exposed via exactly ONE external —
     * getElectionSummaries(bytes32[]) — so the compiler inlines
     * the big struct-array ABI encoder only once. Clients:
     *
     *   1) Call getXxxElectionKeys(...) to get keys.
     *   2) Call getElectionSummaries(keys) to hydrate summaries.
     *
     * There is NO batch cap enforced on-chain. Callers must
     * chunk keys.length ≤ ~100 themselves; too-big batches will
     * fail at the node's return-data or gas limit, which the UI
     * should handle by chunking.
     *
     * Filtering (e.g. by phase, isImplemented, stale-Closed) is
     * done CLIENT-SIDE on the returned ElectionSummary[].
     * ========================================================== */

    error EmptyKeyBatch();

    /// @dev Slice a stored bytes32[] into a memory bytes32[]. Semantics:
    ///        start >= arr.length     → empty result (no revert)
    ///        count == 0 or overflow  → clipped to (len - start)
    ///      Bytecode-lean: single tight loop, no struct copies.
    function _paginateKeys(bytes32[] storage arr, uint256 start, uint256 count)
        private
        view
        returns (bytes32[] memory out)
    {
        uint256 len = arr.length;
        if (start >= len) return new bytes32[](0);
        uint256 remaining = len - start;
        if (count == 0 || count > remaining) count = remaining;
        out = new bytes32[](count);
        for (uint256 i = 0; i < count; i++) {
            out[i] = arr[start + i];
        }
    }

    // ---------- KEY VIEWS ----------

    /// @notice Raw slice of the Pending queue (from _pendingHead to end).
    ///         May include stale entries whose activeFromTimestamp has
    ///         already elapsed but weren't yet head-advanced by _refresh.
    ///         Clients that care can call refreshElections() first, or
    ///         hydrate summaries and filter client-side by comparing
    ///         (activatedTimestamp + previewDurationInDaysAtActivation*day)
    ///         against block.timestamp.
    function getPendingElectionKeys() external view returns (bytes32[] memory) {
        return _paginateKeys(_pendingKeys, _pendingHead, 0);
    }

    /// @notice Raw slice of the Active queue (from _activeHead to end).
    ///         Same staleness caveat as getPendingElectionKeys.
    function getActiveElectionKeys() external view returns (bytes32[] memory) {
        return _paginateKeys(_activeKeys, _activeHead, 0);
    }

    /// @notice Full snapshot of the admin-approval queue. Un-paginated —
    ///         capped at maxPendingApprovalElections (default 100). Order
    ///         is NOT stable across approve/reject (swap-and-pop); if
    ///         clients want "submitted first" ordering they can hydrate
    ///         summaries and sort by submittedAtTimestamp client-side.
    function getAwaitingApprovalElectionKeys() external view returns (bytes32[] memory) {
        return _paginateKeys(_awaitingApprovalKeys, 0, 0);
    }

    /// @notice Paginated closed-election key listing (formally closed only).
    ///         For "closed AND !isImplemented" (a TODO list) or the
    ///         mirror-image "closed AND isImplemented" (a DONE list),
    ///         hydrate a page and filter on `(flags & 0x10) != 0` client-side.
    function getClosedElectionKeys(uint256 start, uint256 count)
        external
        view
        returns (bytes32[] memory)
    {
        return _paginateKeys(_closedKeys, start, count);
    }

    /// @notice Paginated all-time listing in activation-timestamp order.
    ///         Elections stuck in the approval queue are NOT included here;
    ///         see getAwaitingApprovalElectionKeys.
    function getAllElectionKeys(uint256 start, uint256 count)
        external
        view
        returns (bytes32[] memory)
    {
        return _paginateKeys(_allElectionKeys, start, count);
    }

    /// @notice Paginated per-proposer keys. Order is NOT guaranteed to be
    ///         submission-time after any reject (swap-and-pop); hydrate to
    ///         summaries and sort on submittedAtTimestamp if needed.
    function getElectionKeysByProposer(address proposer, uint256 start, uint256 count)
        external
        view
        returns (bytes32[] memory)
    {
        return _paginateKeys(_electionsByProposer[proposer], start, count);
    }

    /// @notice Paginated keys of every revote-clone ever created, in the
    ///         order they were duplicated. Each entry's `duplicatedFromKey`
    ///         (readable via the batch summary) links back to its source.
    function getDuplicateElectionKeys(uint256 start, uint256 count)
        external
        view
        returns (bytes32[] memory)
    {
        return _paginateKeys(_duplicateElectionKeys, start, count);
    }

    // ---------- BATCH SUMMARY VIEW ----------

    /// @notice Hydrate one or more election keys into full ElectionSummary
    ///         entries. THE ONLY external returning ElectionSummary[] —
    ///         all other list views return bytes32[] so the big struct-array
    ///         ABI encoder is inlined into bytecode exactly once.
    ///
    ///         No cap on keys.length is enforced on-chain; the caller is
    ///         responsible for chunking (~100 keys per call is safe;
    ///         beyond that, node return-data limits will bite). Passing an
    ///         empty array reverts with EmptyKeyBatch. Every key MUST
    ///         reference an existing election — non-existent keys revert
    ///         with ElectionNotFound.
    function getElectionSummaries(bytes32[] calldata keys)
        external
        view
        returns (ElectionSummary[] memory out)
    {
        uint256 n = keys.length;
        if (n == 0) revert EmptyKeyBatch();
        out = new ElectionSummary[](n);
        for (uint256 i = 0; i < n; i++) {
            bytes32 key = keys[i];
            Election storage e = _elections[key];
            // Read proposer once — used for both the sentinel check AND
            // the summary field.
            address prop = e.proposer;
            if (prop == address(0)) revert ElectionNotFound();
            uint8 f = e.flags;

            ElectionSummary memory s;
            s.key = key;
            s.title = e.title;
            s.proposer = prop;
            s.activatedTimestamp = e.activatedTimestamp;
            s.closedAtTimestamp = e.closedAtTimestamp;
            s.voteDurationInDaysAtActivation = e.voteDurationInDaysAtActivation;
            s.previewDurationInDaysAtActivation = e.previewDurationInDaysAtActivation;
            s.minTokenTallyPercentToWinAtActivation = e.minTokenTallyPercentToWinAtActivation;
            s.minTokenPercentVotedAtActivation = e.minTokenPercentVotedAtActivation;
            s.totalTokensVotableAtClose = e.totalTokensVotableAtClose;
            s.totalNumberVoted = e.totalNumberVoted;
            s.totalTokensVoted = e.totalTokensVoted;
            s.optionCount = e.options.length;
            s.winningOptionIndex = e.winningOptionIndex;
            s.winningOptionText = e.winningOptionText;
            s.winningTokensTally = e.winningTokensTally;
            s.submittedAtTimestamp = e.submittedAtTimestamp;
            s.duplicatedFromKey = e.duplicatedFromKey;
            s.numDuplicates = e.numDuplicates;

            // Packed flags: copy the 7 shared bits (0..6, includes isRejected
            // at bit 0) verbatim, then derive bit 7 (_F_IS_VALID) from
            // close-state + quorum check.
            uint8 sf = f & _F_SHARED_MASK;
            if (e.closedAtTimestamp != 0 && _isValidWinner(e)) sf |= _F_IS_VALID;
            s.flags = sf;

            out[i] = s;
        }
    }

    /// @notice The cached excluded-core-contract list. Callers wanting the
    ///         count can read arr.length client-side — no dedicated on-chain
    ///         counter (removed for bytecode).
    function getExcludedCoreContracts() external view returns (address[] memory) {
        return _excludedList;
    }

    /// @notice Convenience getter — reports whether `account` currently
    ///         satisfies the propose / vote gates. `canPropose` accounts for
    ///         the TokenAdmin bypass.
    function getShareholderVotingStatus(address account)
        external
        view
        returns (
            uint256 rawBalance,
            uint256 balance18,
            bool    isExcluded,
            bool    isTokenAdmin,
            bool    canPropose,
            bool    canVote
        )
    {
        rawBalance = IGovernanceToken(issueTokenAddress).balanceOf(account);
        balance18 = rawBalance * dec18Scale;
        isExcluded = isExcludedCoreContract[account];
        isTokenAdmin = _isTokenAdmin(account);
        canPropose = !isExcluded && (isTokenAdmin || balance18 >= minTokenRequiredToProposeVote);
        canVote    = !isExcluded && balance18 >= minTokensRequiredToVote;
    }
}

@openzeppelin/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

contracts/CloneInitializable.sol

// SPDX-License-Identifier: CLOSED LICENSE COPYRIGHT 2025
// =====================================================================
//  EquityMint.org / DataCloud OS  —  Official Sovereign Issuance Suite
//  Module: CloneInitializable.sol  (PROXY BUILD ONLY)
//  (c) 2025 US Fintech LLC. ALL RIGHTS RESERVED. See Recoverable.sol
//  header for the full proprietary-rights notice, which is incorporated
//  here by reference.
// =====================================================================
// Designed by Ken Silverman as part of the EIP-1167 clone ("proxy")
// variant of the Sovereign Issuance Suite (DPMS/contractProxies).

pragma solidity 0.8.35;

/// @title CloneInitializable
/// @notice Minimal one-shot initializer guard for the EIP-1167 clone build.
/// @dev HOW THE FLAG WORKS ACROSS THE TWO STORAGE CONTEXTS:
///      - The MODEL (implementation) runs its constructor once at model deploy;
///        the constructor calls _disableInitializers(), writing state=2 into the
///        MODEL's own storage. The model is permanently uninitializable — an
///        inert code donor that is never configured and never used directly.
///      - A CLONE never executes any constructor and starts with EMPTY storage
///        (state=0), so its one initialize() call succeeds exactly once and
///        flips the flag to 1 in the CLONE's own storage.
///      The factory creates the clone and calls initialize() in the SAME
///      transaction, so no uninitialized clone is ever observable on-chain.
abstract contract CloneInitializable {

    /// @dev 0 = uninitialized (fresh clone), 1 = initialized (live clone),
    ///      2 = locked (the model/implementation itself).
    uint8 private _initState;

    error AlreadyInitialized();

    modifier initializer() {
        if (_initState != 0) revert AlreadyInitialized();
        _initState = 1;
        _;
    }

    /// @dev Call ONLY from the implementation's (model's) empty constructor.
    function _disableInitializers() internal {
        _initState = 2;
    }

    error InitDelegateFailed();

    /// @dev INITIALIZER-SIDECAR TRAMPOLINE (EIP-170 relief).
    ///      Oversized models keep only a stub initialize() (guarded by the
    ///      `initializer` modifier, which runs BEFORE this call — one-shot is
    ///      enforced in the stub, in the clone's storage) and forward msg.data
    ///      verbatim to their <Parent>Initializer sidecar, which carries the
    ///      former constructor body. Because the sidecar function has the SAME
    ///      signature, the forwarded selector dispatches directly to it.
    ///
    ///      Context math: clone --DELEGATECALL--> model --DELEGATECALL--> sidecar.
    ///      A nested delegatecall PRESERVES the outer context, so the sidecar
    ///      body executes against the CLONE's storage with address(this) = clone
    ///      and msg.sender = the factory — byte-identical semantics to the body
    ///      living in the model itself.
    function _delegateInit(address sidecar) internal {
        (bool ok, bytes memory ret) = sidecar.delegatecall(msg.data);
        if (!ok) {
            if (ret.length > 0) {
                assembly ("memory-safe") { revert(add(ret, 0x20), mload(ret)) }
            }
            revert InitDelegateFailed();
        }
    }

    /// @notice True once this instance has been initialized (or locked).
    function isInitialized() external view returns (bool) {
        return _initState != 0;
    }
}

interfaces/IController.sol

// SPDX-License-Identifier: UNLICENSED
// ============================================================
//  EquityMint.org — Official Sovereign Issuance Contract
//  © Copyright 2025 US Fintech LLC
//  All Rights Reserved.
// ------------------------------------------------------------
//  This contract is part of the EquityMint.org RWA platform,
//  built on the DataCloud OS issuance engine. This file and all
//  related logic are proprietary intellectual property of
//  US Fintech LLC. EquityMint.com and all other domains are not
//  authorized sources of this technology.
//
//  Licensing & Authorized Use:
//  - Deployments are permitted ONLY through the official
//    EquityMint DataCloud OS Sovereign Deployment Engine.
//  - Each issuer receives a sovereign copy with identical
//    canonical comments and legal metadata.
//  - White-labeling is prohibited unless explicitly authorized
//    by written agreement with US Fintech LLC.
//  - Any deployment, modification, or derivative work that does
//    NOT include this header is an unauthorized use.
//  - Any such unauthorized deployment or derivation will be
//    subject to enforcement and legal remedies, including civil
//    litigation for copyright infringement, against the deployer
//    and all associated entities.
//
//  Restrictions:
//  - Unauthorized redistribution, modification, resale,
//    rebranding, or misrepresentation is strictly prohibited.
//  - Cloned/forked versions outside the official EquityMint
//    deployment process are not recognized and may violate
//    copyright and licensing terms.
//  - Use of this system for securities offerings requires full
//    legal compliance with applicable exemptions (Reg D 506(b),
//    506(c), Reg S, and Rule 144). Issuers bear all legal
//    responsibility for their own compliance program.
//
//  Authenticity:
//  - Official deployments are cryptographically registered in
//    the EquityMint On-Chain Registry.
//  - Only deployments listed in the registry are recognized as
//    authentic sovereign issuances.
//
//  Contact:
//  - https://EquityMint.org
//  - [email protected]
// ============================================================
//
// Copyright 2025 US Fintech LLC ALL RIGHTS RESERVED.
// Permission to use, copy, modify, or distribute this software is strictly prohibited
// without prior written consent from copyright holder. Violators will be prosecuted to the fullest extent of the law.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE,
// ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// @author Ken Silverman
// Architecture: ElasticTreasury (HUB and SPOKE), PeerTreasury, Controller, and ControllerTree.
// This deployment is for US Fintech, LLC NY.
// Permission to change metadata stored on blockchain explorers and elsewhere granted to:
// US Fintech, LLC NY only.
pragma solidity 0.8.35;

interface IController {
    struct OfficialEntityStruct {
        string fullNameOfEntityOrLabel;
        string nationalIdOfEntity;
        address pubAddress;
        uint256 blockNumber;
        uint256 blockTimestamp;
        bool active;
        uint256 value;  // Associated value (0-1,000,000 for absolute, or basis points for %, type(uint256).max = no value)
    }

    // v43107: returned by getAllOfficialDeactivatedEntities — the current
    // (inactive) snapshot plus the full on-chain deactivation-timestamp history.
    struct DeactivatedEntityStruct {
        OfficialEntityStruct entity;
        uint256[] deactivationTimestamps;
    }

    struct ChainedEntityStruct {
        address entityAddress;
        address parent;
        uint8[] feeTypes;      // Array of fee type bytes [0, 1, 2, 3, 4, ...]
        uint256[] feeAmounts;  // Parallel array: amounts (absolute or basis points)
        uint8[] feeFlags;      // Parallel array: bit0=isPercent, bit1=isTaker
        bool active;
        bool locked;     // Temporary lock by ancestors - can be unlocked
        bool permanentlyLocked;  // Permanent lock by Super after 6 months - IRREVERSIBLE
        uint256 blockNumber;
        uint256 blockTimestamp;
        string entityName;  // Human-readable name
        string entityID;    // Additional identifier (tax ID, registration #, etc)
    }

    struct CalculatedEntityAmount {
        address entityAddress;
        uint256 amount;  // Calculated amount for the requested feeType
    }

    // Internal storage structure for chained entity groups
    struct ChainedEntityGroup {
        mapping(address => ChainedEntityStruct) entitiesByAddress;
        mapping(address => address[]) childrenByParent;
        address[] rootNodes;
    }

    // Entity with fees for addChainedEntity to avoid stack too deep
    struct EntityFeesWithNames {
        address entityAddress;
        address parent;
        uint8[] feeTypes;      // Array of fee type bytes [0, 1, 2, 3, 4, ...]
        uint256[] feeAmounts;  // Parallel array of amounts (same index as feeTypes)
        uint8[] feeFlags;      // Parallel array of flags: bit0=isPercent(0/1), bit1=isTaker(0/1)
        bool locked;
        string entityName;
        string entityID;
    }

    // Official Entity Functions
    function addOfficialEntity(string memory, address, string memory, string memory) external returns (bool);
    function addOfficialEntityWithValue(string memory, address, string memory, string memory, uint256) external returns (bool);
    function removeOfficialEntity(string memory, address) external returns (bool);
    function isOfficialEntity(string memory, address) external view returns (bool);
    function isOfficialEntityFast(bytes32, address) external view returns (bool);
    /// @dev v43108: LATEST ACTIVE entity of the (pre-hashed) type by EXACT label match;
    ///      address(0) = no active match (not a revert — see Controller docblock).
    function getOfficialEntityAddressFast(bytes32 adminTypeHash, string calldata label) external view returns (address);
    function isOfficialEntityPlusNotEntityFast(bytes32, address, bytes32, address, bool) external view returns (bool);
    function isOfficialDoubleEntityFast(bytes32, address, bytes32, address, bool) external view returns (bool);
    function isOfficialTripleEntityFast(bytes32, address, bytes32, address, bytes32, address, bool) external view returns (bool);
    function isOfficialQuadrupleEntityFast(bytes32, address,  bytes32, address, bytes32, address, bytes32, address, bool) external view returns (bool);
    function getOfficialEntity(string calldata, address) external view returns (OfficialEntityStruct memory);
    function getAllOfficialEntities(string calldata, bool) external view returns (OfficialEntityStruct[] memory);
    function init(address, string calldata) external;
    function openInit() external returns (bool);
    function closeInit() external returns (bool);
    function getEntityCount(bytes32) external view returns (uint256);

    // v43107: active/deactivated split — new-model Controllers only
    // (feature-detect with try/catch on older deployments).
    function getEntityCount(bytes32, bool) external view returns (uint256);
    function getDeactivatedEntityCount(bytes32) external view returns (uint256);
    function getAllOfficialDeactivatedEntities(string calldata, uint256, uint256) external view returns (DeactivatedEntityStruct[] memory);
    function migrateActiveEntities(string[] calldata, OfficialEntityStruct[] calldata) external;
    function migrateInactiveEntities(string[] calldata, DeactivatedEntityStruct[] calldata) external;
    function sealMigration() external;
    function migrationSealed() external view returns (bool);
    
    // Platform Controller Functions
    function PLATFORM_CONTROLLER() external view returns (address);
    function isPlatform() external view returns (bool);
    function isPlatformTreasuryAdmin(address) external view returns (bool);
    function isPlatformAdmin(address, bytes32) external view returns (bool);

    /// @notice True if the project has permanently locked out platform mutation
    ///         (SmartContract registry, init window).  Exposed as the auto-getter
    ///         for the `platformAccessPermanentlyRevoked` storage variable.
    ///
    ///         Project sovereignty signal:  callers that gate platform-admin paths
    ///         on this flag (e.g. IssueTokenDistributionManager's subscriber
    ///         add/remove) should DENY the platform path when this is true, so a
    ///         revoked project's platform admin loses NOT just registry-mutation
    ///         access (enforced inside Controller) but also any downstream
    ///         sovereignty-relevant ops the platform might otherwise still reach.
    ///
    ///         Controller itself does NOT globally gate `isPlatformAdmin` on this
    ///         flag — revocation is enforced per call site by convention.  Each
    ///         downstream contract decides whether revocation should sever a
    ///         given platform-admin path.
    function platformAccessPermanentlyRevoked() external view returns (bool);

    // Constants
    function BASIS_POINTS_DIVISOR() external view returns (uint256);
}

interfaces/IFeeManager.sol

// SPDX-License-Identifier: UNLICENSED
// =====================================================================
//  EquityMint.org / DataCloud OS  —  Official Sovereign Issuance Suite
//  Module: IFeeManager.sol
//  (c) 2025 US Fintech LLC, a New York limited liability company.
//  ALL RIGHTS RESERVED.  PROPRIETARY & CONFIDENTIAL.
// ---------------------------------------------------------------------
//  NOTICE OF PROPRIETARY RIGHTS
//  This source file, its compiled bytecode, ABI, deployment artifacts,
//  documentation, and every derivative thereof (the "Software") are
//  the proprietary intellectual property of US Fintech LLC
//  ("Licensor"). No license, express or implied, by estoppel or
//  otherwise, to any patent, copyright, trademark, trade secret, or
//  other intellectual property right of Licensor is granted by this
//  file or its publication on any chain, repository, registry, or
//  service. Possession, viewing, indexing, mirroring, decompilation,
//  or re-publication does NOT confer any right of use.
//
//  PROHIBITED CONDUCT (non-exhaustive)
//  Without prior, signed, written authorization from US Fintech LLC,
//  it is strictly prohibited to:
//   (a) copy, fork, mirror, redistribute, sublicense, sell, lease, or
//       otherwise transfer the Software or any portion thereof;
//   (b) modify, translate, port, adapt, or create derivative works;
//   (c) deploy, redeploy, instantiate, proxy, clone, CREATE/CREATE2,
//       relay, or upgrade the Software on any blockchain, side-chain,
//       L2, testnet, or private network;
//   (d) reverse engineer, disassemble, decompile, or extract bytecode
//       except to the limited extent expressly permitted by law that
//       cannot be contractually waived;
//   (e) remove, obscure, alter, or omit this header, the SPDX line,
//       any copyright/trademark notice, or any on-chain metadata
//       (including, without limitation, the contract's reported
//       source, name, or compiler metadata) from any copy or fork;
//   (f) white-label, rebrand, re-attribute, or hold out the Software
//       (or any derivative) as the work of any party other than
//       US Fintech LLC; or
//   (g) use the Software to facilitate any offering, sale, or
//       distribution of securities or financial products in violation
//       of applicable law.
//
//  AUTHORIZED USE ONLY
//  Deployments are authorized SOLELY through the official EquityMint
//  DataCloud OS Sovereign Deployment Engine and are cryptographically
//  registered in the EquityMint On-Chain Registry. Only registry-
//  listed deployments are recognized as authentic. Any deployment
//  lacking this header -- or whose header has been altered -- is, on
//  its face, unauthorized and infringing.
//
//  TRADEMARKS
//  "EquityMint", "EquityMint.org", "DataCloud OS",
//  "Sovereign Issuance", and associated logos are trademarks of
//  US Fintech LLC. Use of these marks without written consent is
//  prohibited and may constitute trademark infringement, false
//  designation of origin, and unfair competition under the Lanham
//  Act, 15 U.S.C. sec. 1114, 1125(a).
//
//  ENFORCEMENT & REMEDIES
//  Unauthorized use is willful infringement. Licensor will pursue all
//  available remedies, which may include, without limitation:
//   - Civil copyright infringement under 17 U.S.C. sec. 501 et seq.,
//     including statutory damages up to $150,000 per work for willful
//     infringement under 17 U.S.C. sec. 504(c)(2), plus costs and
//     attorneys' fees under 17 U.S.C. sec. 505;
//   - Anti-circumvention and integrity-of-CMI claims under the DMCA,
//     17 U.S.C. sec. 1201-1203 (circumvention) and sec. 1202 (removal
//     or alteration of copyright management information);
//   - Trademark, false designation of origin, and unfair competition
//     under 15 U.S.C. sec. 1114, 1125(a) and applicable state law;
//   - Trade-secret misappropriation under the Defend Trade Secrets
//     Act, 18 U.S.C. sec. 1836, and the New York Uniform Trade
//     Secrets framework;
//   - Computer Fraud and Abuse Act claims, 18 U.S.C. sec. 1030, where
//     unauthorized access or deployment is involved;
//   - Injunctive relief, impoundment, accounting, and disgorgement of
//     profits.
//  Where conduct is criminal, Licensor reserves the right to refer
//  the matter to U.S. and foreign authorities for prosecution.
//
//  GOVERNING LAW & FORUM
//  This notice and any dispute arising out of or relating to the
//  Software are governed by the laws of the State of New York, U.S.A.,
//  without regard to conflict-of-law principles. Exclusive jurisdiction
//  and venue lie in the state and federal courts located in New York
//  County, New York. The parties waive any objection to such venue
//  and any right to a jury trial to the fullest extent permitted by
//  law. The U.N. Convention on Contracts for the International Sale
//  of Goods does not apply.
//
//  SECURITIES-LAW DISCLAIMER
//  The Software is a software tool. It is not investment, legal, tax,
//  or accounting advice and is not an offer or solicitation. Any use
//  for the offer or sale of securities (including under Reg D 506(b),
//  506(c), Reg S, Rule 144, or any non-U.S. exemption) is the sole
//  responsibility of the issuer, who must maintain its own compliance
//  program. Licensor disclaims any role as issuer, underwriter,
//  broker-dealer, investment adviser, or fiduciary.
//
//  NO WARRANTY
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND
//  NON-INFRINGEMENT. IN NO EVENT SHALL US FINTECH LLC OR ITS
//  AFFILIATES, OFFICERS, MEMBERS, OR AGENTS BE LIABLE FOR ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//  ARISING FROM OR RELATED TO THE SOFTWARE OR ITS USE, EVEN IF
//  ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
//
//  AUTHENTICITY & CONTACT
//  Official sources: https://EquityMint.org   |   [email protected]
//  Infringement / DMCA notices: [email protected]
//  Author of architecture: Ken Silverman (ElasticTreasury HUB & SPOKE,
//  PeerTreasury, Controller / ControllerTree models).
//  Permission to set/modify on-chain explorer metadata for official
//  deployments is granted to US Fintech LLC, NY only.
//
//  INTERPRETATION & MERGER
//  This Notice is supplemental to, and not in limitation of, any
//  other notice, restriction, or terms appearing elsewhere in this
//  file or incorporated by reference (including, without limitation,
//  the EquityMint.org and DataCloudOS.com Terms of Use). Where any
//  provision herein and any other provision affecting the Software
//  differ, the provision that is more restrictive of use, or that
//  affords Licensor greater protection or remedies, shall control.
//  No provision shall be construed against Licensor as drafter, and
//  no failure or delay by Licensor in enforcing any provision shall
//  operate as a waiver of any right hereunder. If any provision is
//  held invalid or unenforceable in any jurisdiction, the remaining
//  provisions shall remain in full force and effect.
// =====================================================================
// Copyright 2025 US Fintech LLC, a New York company.
pragma solidity 0.8.35;

/// @title IFeeManager Interface
/// @author Ken Silverman
/// @notice Interface for managing hierarchical fee structures (chained entities)
interface IFeeManager {
    
    // Structures
    struct ChainedEntityStruct {
        address entityAddress;
        address parent;
        uint256[] feeValues;        // DYNAMIC array
        uint8[] feeFlags;           // DYNAMIC array - CHANGED TO uint8
        bool active;
        bool locked;
        bool permanentlyLocked;
        uint256 blockNumber;
        uint256 blockTimestamp;
        string entityName;
        string entityID;
    }

    struct CalculatedEntityAmount {
        address entityAddress;
        uint256 amount;
    }

    struct EntityFeesWithNames {
        address entityAddress;
        address parent;
        uint256[] feeValues;        // DYNAMIC array
        uint8[] feeFlags;           // DYNAMIC array - CHANGED TO uint8
        bool permanentlyLocked;     // Per-root IRREVERSIBLE lock (set via permLockRoot). Blocks all unlocks.
        bool locked;                // Temporary lock (can be unlocked by parent/admin)
        string entityName;
        string entityID;
    }

    // Core fee management functions (simplified - uses default chain type)
    function addChainedEntity(EntityFeesWithNames memory entity) external returns (bool);
    function removeChainedEntity(address entity, bool includeSelf) external returns (bool);
    function setChainedEntityLock(address entity, bool shouldLock) external returns (bool);
    
    // Core fee management functions (advanced - custom chain type)
    function addChainedEntity(bytes32 chainType, EntityFeesWithNames memory entity) external returns (bool);
    function removeChainedEntity(bytes32 chainHash, address entity, bool includeSelf) external returns (bool);
    function setChainedEntityLock(string calldata chainType, address entity, bool shouldLock) external returns (bool);
    
    // Lock/unlock (tiered sovereignty: Platform TokenAdmin for constructor entities, Project Admin for non-constructor)
    function lockChild(string calldata chainType, address child, bool isLock) external returns (bool);
    function lockAllMyChildren(string calldata chainType, address subtreeRoot, bool includeSubtreeRoot, bool isLock) external returns (uint256);
    
    // Payout override (tiered: Platform TokenAdmin for constructor roots, Project Admin for project-added roots)
    function changeRoot(string calldata chainType, address root, address newPayout) external returns (bool);
    
    // Per-root permanent lock (tiered: IRREVERSIBLE, no time restriction)
    function permLockRoot(string calldata chainType, address root) external returns (uint256 lockedCount);
    
    // Global locks (Project Admin = Super/TreasuryAdmin/TokenAdmin via onlyProjectAdmin, after freezeDelay)
    function permLockAllRootChainedEntities(string calldata chainType, bool includeSelf, bool isFreezeLock) external returns (uint256 lockedCount);
    function lockNewRootEntityAdds(bool shouldLock) external returns (bool);

    // Per-root subtree freeze (Project Admin, after freezeDelay, reversible).
    // When set, blocks all mutations in that subtree for every caller (including platform).
    // Default chain type only — flat map, no bytes32 outer key.
    function freezeRootPath(address root, bool isFreeze) external returns (bool);
    function rootFamilyLocked(address root) external view returns (bool);
    
    // Query functions
    function isChainedEntity(string calldata chainType, address entity) external view returns (bool);
    
    function isChainedEntityFast(bytes32 hashedChainType, address entity) external view returns (bool);
    
    function getChainedEntity(string calldata chainType, address entity) external view returns (ChainedEntityStruct memory);
    
    function getActiveChainedEntities(string calldata chainType) external view returns (ChainedEntityStruct[] memory);
    
    // Fee calculation with hash (GAS-OPTIMIZED: ~200-300 gas savings vs string version)
    // Saves gas by avoiding ABI encoding overhead (96 bytes for string vs 32 bytes for hash)
    function calculateChainedAmounts(
        uint256 totalVal,
        uint256 maxPct,
        bytes32 feeTypeHash
    ) external view returns (
        CalculatedEntityAmount[] memory calculatedAmounts,
        uint256 totalAmount
    );
    
    // Fee calculation (advanced - custom chain type with uint8 feeType)
    function calculateChainedAmounts(
        bytes32 chainType,
        uint256 totalVal,
        uint256 maxPct,
        uint8 feeType
    ) external view returns (
        CalculatedEntityAmount[] memory calculatedAmounts,
        uint256 totalAmount
    );
    
    function distributeFees(
        CalculatedEntityAmount[] calldata calculatedFees,
        address payer,
        address paymentToken
    ) external returns (uint256 totalDistributed);
    
    function triggerNotify() external;
    
    // Fee type management
    function addFeeType(string calldata label) external;  // Auto-assigns next fee type
    function getAllFeeTypeLabels() external view returns (string[] memory);  // Batch getter for all labels
    function feeTypeLabels(uint8 index) external view returns (string memory);  // Query by array index 0-49!
    function feeTypeLabelToType(string calldata label) external view returns (uint8);  // Reverse mapping: label → type
    function getTypeForLabel(string calldata label) external view returns (uint8);  // Get type by label (reverts if undefined)
    function currentMaxFeeType() external view returns (uint8);  // Returns current max fee type (dynamic, starts at 7, max 50)
    function ABSOLUTE_MAX_FEE_TYPES() external view returns (uint8);  // Returns 50
    // v43108: canonical-6-dec → official-stable-atomics output multiplier (10**(decimals-6)).
    // 0 (pre-v43108 instance) must be treated as 1 by callers. See FeeManager.stableScale.
    function stableScale() external view returns (uint256);
    function syncStableCoin(string calldata itLabel) external;  // TRUSTLESS re-sync after stable rotation: anyone may call — label must be "IssueToken_<symbol>" (strict prefix guard) and resolve on the clone's own controller; coin read from that IT's live stableCoinAddress()
    
    // ProjectRevenueTreasury notification registration
    function setProjectRevenueTreasury(address treasury) external;  // One-time registration of treasury for fee notifications
    
    // Constants
    function BASIS_POINTS_DIVISOR() external view returns (uint256);
    function ACTION_ADD() external view returns (uint8);
    function ACTION_UPDATE() external view returns (uint8);
    function ACTION_REMOVE() external view returns (uint8);
    function ACTION_LOCK() external view returns (uint8);
    function ACTION_UNLOCK() external view returns (uint8);
    function ACTION_REACTIVATE() external view returns (uint8);
}

Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs",
    "useLiteralContent": true
  },
  "optimizer": {
    "runs": 10000,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.