Skip to content
Verified contractExactUNLICENSED

IssueTokenTimeLock

Address0x6d577bc90ba24286534df9517b63b2ca182e710b
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,339,593
Creation transaction
0xdf87a59bf3…677966a0d6

contracts/IssueTokenTimeLock.sol

// SPDX-License-Identifier: UNLICENSED
// =====================================================================
//  EquityMint.org / DataCloud OS  —  Official Sovereign Issuance Suite
//  Module: IssueTokenTimeLock.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.
//
// Permission to use, copy, modify, or distribute this software is strictly prohibited
// without prior written consent from US Fintech LLC.
//
// 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 US FINTECH LLC 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.
//
// OFFICIAL US FINTECH LLC COMPONENT
// EquityMint Sovereign Model Token Contract System Component
// The Foremost De-Facto Architectural Standard for Real-World Asset (RWA),
// Fund and ETF-Like Tokenization and Monetization.
//
// Issue Token Time Lock - Flexible vesting and lockup manager supporting cliff periods, linear vesting,
// and fully customizable release schedules. Provides executive compensation structures, investor lockups,
// and earn-out mechanisms with granular control over token release timing. Integrates with IssueToken
// for secure, court-verifiable vesting arrangements.
//
// Chief Architect and CEO: Ken Silverman, US Fintech LLC
// Designed by Ken Silverman as part of the EquityMint vesting infrastructure.
// @author Ken Silverman
//
// ⚖️  AUTHORIZED USE RESTRICTIONS:
// Only projects deploying these contracts via the EquityMint platform at equitymint.org
// which contain this preamble and Fee structures generated through EquityMint.org have
// permission to use these contracts or any derivative works thereto. Any such deployment
// must contain these words. This contract is part of a greater system. They are owned
// and licensed exclusively in writing and through US Fintech, LLC.
//
// Any breach of these terms will be investigated and pursued through all available civil
// and criminal remedies to the fullest extent permitted by applicable law. Enforcement is
// discretionary. The failure to enforce any provision shall not constitute a waiver of the
// right to enforce at any time. All projects and platform users interacting with this system
// are subject to additional terms and conditions as may be published or updated from time to
// time at https://equitymint.org and/or https://DataCloudOS.com.
pragma solidity 0.8.35;

import "../interfaces/IController.sol";
import "./TreasuryConstants.sol";
import "./CloneInitializable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";

/* ========== INTERFACES FOR DEX DETECTION AND ORACLES ========== */

interface AggregatorV3Interface {
    function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

interface IUniswapV2Pair {
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
}

interface IUniswapV3Pool {
    function token0() external view returns (address);
    function token1() external view returns (address);
    function slot0() external view returns (
        uint160 sqrtPriceX96,
        int24 tick,
        uint16 observationIndex,
        uint16 observationCardinality,
        uint16 observationCardinalityNext,
        uint8 feeProtocol,
        bool unlocked
    );
    function liquidity() external view returns (uint128);
}

interface IERC20Metadata {
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function decimals() external view returns (uint8);
}

interface IERC20 {
    function balanceOf(address account) external view returns (uint256);
}

interface IIssueToken {
    function timeLockManager() external view returns (address);
}

interface IRegisteredSafeFactory {
    function isSafeWalletRegistered(address safeAddress) external view returns (bool);
}

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

// Authorization Errors
error NotTreasuryAdmin();
error NotAuthorized();
error MaxHoldersExceeded();
error OnlyIssueToken();
error TokenAddressAlreadySet();
error TokenNotRegisteredAsSmartContract();

// Constructor Errors
error InvalidController();
error MaxLockDurationExceeded();

// Allocation Errors
error InvalidUserAddress();
error InvalidAmount();
error ArrayLengthMismatch();
error InvalidAllocationIndex();

// Price Lock Errors
error BelowMinimumPrice();
error TransferToBlockedExchange();

/**
 * @title IssueTokenTimeLock
 * @notice Manages allocation-based timelocks with time and optional minimum price enforcement
 * @dev Each purchase creates a separate timelock entry. Users hold tokens but cannot transfer locked amounts.
 *      Optional price lock feature prevents DEX sales below threshold with separate expiry.
 * @author Ken Silverman
 */
// PROXY BUILD: EIP-1167 clone variant — deployed once per chain as an inert MODEL;
// projects receive a clone configured via initialize().
contract IssueTokenTimeLock is TreasuryConstants, CloneInitializable {

    uint16 public constant CONTRACT_VERSION = 43109; // v43109: cold-path sidecar (IssueTokenTimeLockSidecar) hosts initialize + all admin setters; + migrateAllocations (ERC-3643 recovery). 43107: min Price inheritance support

    /// @notice Structure to track a single timelock allocation
    struct TimeLockAllocation {
        uint256 amount;              // Amount of tokens locked
        uint256 unlockTime;          // Timestamp when time lock expires (0 = no lock)
        uint256 minPriceUSD;         // Minimum price in USD (18 decimals, 0 = no price lock)
        uint256 minPriceExpiry;      // Timestamp when price lock expires (0 = never expires if minPriceUSD > 0)
        bool released;               // True if allocation has been fully released
    }

    /// @notice Controller address for permission checks
    // PROXY BUILD: was `immutable` — now storage, set once in initialize().
    address public controller;

    /// @notice IssueToken that uses this TimeLock (set once during deployment)
    address public issueToken;

    /// @notice Stablecoin used by IssueToken for fee payments and min-price denomination
    /// @dev Set once during deployment via setLifetimeTokenAddress, updatable via setStableCoinAddress
    address public stableCoinAddress;

    /// @notice Chainlink price feed for stablecoin/USD (for price conversions)
    /// @dev 8-decimal feed (standard Chainlink format)
    address public stableCoinUsdFeed;

    /// @notice Mapping of token address => Chainlink USD price feed (8 decimals)
    /// @dev Used to convert arbitrary pool quote tokens into stablecoin-denominated prices
    mapping(address => address) public tokenUsdFeeds;

    /// @notice RegisteredSafeFactory for multi-sig safe registration (optional, 0x0 if not set)
    /// @dev Used to distinguish legitimate Gnosis Safes from wrapper contracts in wrapper attack prevention
    ///      If set, transfers to unregistered contracts are blocked (unless EOA, official SmartContract, or feeExempt)
    ///      If 0x0, wrapper blocking is disabled (all contract receivers allowed)
    address public registeredSafeFactory;

    /// @notice Global timelock switch - can disable all locks temporarily
    // PROXY BUILD: `= true` default moved to initialize() (inline initializers never run for clones).
    bool public timeLockActive;

    /// @notice Lock duration for addTimeLock() (0 = no lock)
    uint256 public timeLockDuration = 0;

    /// @notice Default minimum price for new allocations (18 decimals, 0 = disabled)
    uint256 public defaultMinPriceUSD = 0;

    /// @notice Default minimum price lock duration in seconds (0 = no expiry, permanent)
    uint256 public defaultMinPriceDuration = 0;

    /// @notice Mapping from user address to their timelock allocations
    mapping(address => TimeLockAllocation[]) public userTimeLocks;

    /// @notice Blocked exchange addresses (CEX addresses)
    mapping(address => bool) public blockedExchanges;

    /// @notice List of blocked exchange addresses
    address[] public blockedExchangeList;

    /// @notice Request transfer nonce tracking (prevent signature replay)
    mapping(address => mapping(uint256 => bool)) public usedRequestTransferNonces;

    // NEW: Fee exemption and DEX control for transfer fees
    /// @notice Fee-exempt addresses (CEX hot wallets, treasury multisigs)
    mapping(address => bool) public isFeeExempt;

    /// @notice List of fee-exempt addresses
    address[] public feeExemptList;

    /// @notice Exempt DEX sells from transfer fees (default: false, fees collected on DEX and P2P)
    bool public exemptDexSells = false;

    /// @notice Exempt DEX buys from transfer fees (default: false, fees collected on DEX and P2P)
    bool public exemptDexBuys = false;

    /// @notice Block direct DEX buys to force permit flow through website (default: false = permissive mode)
    /// @dev Naming: "ToForcePermitFlow" clarifies this is for fee collection + UX, not security (gating = security)
    ///      true = Force website usage with clear message
    ///      false = Permissive mode (allow if buyer pre-approved USDC)
    bool public blockDirectDexBuysToForcePermitFlow = false;

    /// @notice GLOBAL permanent transfer lock (default: false = transfers allowed)
    /// @dev When true: ALL holders locked (cannot sell/transfer to non-SmartContracts)
    ///      SmartContract recipients (SalesManager, DEX routers, etc.) ALWAYS bypass this lock
    ///      Use case: Permanent "never sell" mode for specific token distributions
    bool public globalPermTransferLock = false;

    /// @notice Block direct DEX sells to force permit flow through website (default: false = permissive mode)
    /// @dev Naming: "ToForcePermitFlow" clarifies this is for fee collection + UX, not security (gating = security)
    ///      true = Force website usage with clear message
    ///      false = Permissive mode (allow if seller pre-approved USDC)
    bool public blockDirectDexSellsToForcePermitFlow = false;

    /// @notice Custom URL for DEX trading (shown in error messages, empty = use default)
    /// @dev If empty, defaults to "https://equitymint.org/dex" in error messages
    string public dexTradeUrl;

    /// @notice Maximum number of unique token holders (0 = unlimited)
    /// @dev When setting maxHolders > 0, automatically reduced by 6 to reserve slots for:
    ///      Token Contract, Sales Contract, Restricted Sales Contract, Project Revenue Treasury,
    ///      Liquidity Provider, and Liquidity Pool.
    /// ⚠️ WARNING: DO NOT USE CENTRALIZED EXCHANGES (CEX) when maxHolders > 0!
    ///      CEX transactions originate from exchange wallets, and failed transfers due to holder
    ///      limits will SILENTLY FAIL without user notification. The exchange will not broadcast
    ///      the error, leaving users confused. Only use DEX or direct wallet transfers.
    uint256 public maxHolders = 0;

    /// @notice Mapping of SmartContract addresses for O(1) lookup
    /// @dev Populated via syncSmartContractCache(), permanent cache (SCs rarely change)
    mapping(address => bool) public isSmartContractCached;

    /// @notice Flag to track if SmartContract cache has been synced
    /// @dev Set to true after first sync, prevents redundant syncs
    bool public isSmartContractCacheSynced;

    /// @notice Array of active user holders (balance > 0, excluding SmartContracts)
    /// @dev Dynamically updated on each transfer, uses swap-and-pop for efficient removal
    ///      Length of this array IS the count (no separate counter needed)
    address[] private activeHoldersList;

    /// @notice Mapping of holder address to index in activeHoldersList
    /// @dev Index is stored as (actualIndex + 1), so 0 means not in list
    mapping(address => uint256) private activeHolderIndex;

    /// @notice Fee decision struct for centralized transfer policy
    struct FeeDecision {
        bool shouldCollectFees;      // True if fees should be collected
        bool collectFromRecipient;   // True if collecting from recipient (DEX buy permissive mode)
        bool shouldBlock;            // True if transaction should be blocked entirely
        string blockMessage;         // Custom error message if blocked (complete, ready to use)
        string feeApprovalMessage;   // Custom error message if USDC approval missing (complete, ready to use)
    }

    // Keccak hashes inherited from TreasuryConstants:
    // KECCAK_TOKEN_ADMIN, KECCAK_TREASURY_ADMIN, KECCAK_SMART_CONTRACT, KECCAK_PLATFORM_TREASURER

    /// @notice Events
    event TimeLockAdded(address indexed user, uint256 amount, uint256 unlockTime, uint256 minPriceUSD, uint256 minPriceExpiry, uint256 allocationIndex);
    event TimeLockActiveChanged(bool active);
    event TransferBlocked(address indexed user, address indexed recipient, uint256 attemptedAmount, uint256 lockedAmount, string reason);
    event TimeLockDurationChanged(uint256 newDuration);
    event MinPriceDefaultsChanged(uint256 minPriceUSD, uint256 minPriceDuration);
    event BlockedExchangeAdded(address indexed exchange);
    event BlockedExchangeRemoved(address indexed exchange);
    event TimeLockInherited(address indexed from, address indexed to, uint256 amount, uint256 minPriceUSD, uint256 minPriceExpiry);
    // NEW: Fee exemption and DEX control events
    event FeeExemptionChanged(address indexed account, bool exempt, address indexed changedBy);
    event ExemptDexSellsChanged(bool exempt, address indexed changedBy);
    event ExemptDexBuysChanged(bool exempt, address indexed changedBy);
    event BlockDirectDexBuysToForcePermitFlowChanged(bool blocked, address indexed changedBy);
    event BlockDirectDexSellsToForcePermitFlowChanged(bool blocked, address indexed changedBy);
    event DexTradeUrlChanged(string newUrl, address indexed changedBy);
    event MaxHoldersChanged(uint256 newMaxHolders, address indexed changedBy);
    event GlobalPermTransferLockChanged(bool locked, address indexed changedBy);
    event SmartContractCacheSynced(uint256 count);
    event ActiveHolderCountChanged(uint256 newCount, address indexed affectedAddress, bool increased);
    event StableCoinAddressChanged(address indexed oldAddress, address indexed newAddress, address indexed changedBy);
    event StableCoinUsdFeedChanged(address indexed newFeed, address indexed changedBy);
    event TokenUsdFeedSet(address indexed token, address indexed feed, address indexed changedBy);

    modifier onlyTokenAdmin() {
        if (!IController(controller).isOfficialEntityFast(KECCAK_TOKEN_ADMIN, msg.sender)) revert NotTokenAdmin();
        _;
    }

    modifier onlyTreasuryAdmin() {
        if (!IController(controller).isOfficialEntityFast(KECCAK_TREASURY_ADMIN, msg.sender)) revert NotTreasuryAdmin();
        _;
    }

    modifier onlyAuthorized() {
        if (!IController(controller).isOfficialDoubleEntityFast(
                KECCAK_TOKEN_ADMIN, msg.sender,
                KECCAK_SMART_CONTRACT, msg.sender,
                false  // OR logic: TokenAdmin OR SmartContract
            )) {
            revert NotAuthorized();
        }
        _;
    }

    // NEW: PLATFORM_TREASURER modifier for fee policy control
    modifier onlyPlatformTreasurer() {
        if (!IController(controller).isPlatformAdmin(msg.sender, KECCAK_TREASURY_ADMIN)) revert NotAuthorized();
        _;
    }

    modifier onlyIssueToken() {
        if (msg.sender != issueToken) revert OnlyIssueToken();
        _;
    }

    // ===== PROXY BUILD: COLD-PATH SIDECAR TRAMPOLINE (v43109) =====
    // Same pattern as IssueTokenNavPoolManager / RestrictedSaleManager / IssueToken:
    // IssueTokenTimeLockSidecar (end of this file) is deployed by THIS model's constructor
    // (constructor code is not subject to EIP-170), its address is an immutable, and NO
    // factory / PPAM / UI change is required. The sidecar mirrors this contract's storage
    // layout verbatim and carries the bodies of initialize() and every cold admin setter.
    // The HOT paths — getLockedAmount / getTimeLockedAmount / getTransferFeeDecision /
    // handleTransferInheritanceAndUpdateHolderCount / validateRequestTransferSignature /
    // addTimeLockedAllocation — and ALL views stay here. Stubs keep the SAME signatures
    // (compiled ABI unchanged) and forward msg.data via nested delegatecall: clone
    // storage, msg.sender, address(this) and event addresses are preserved; return data
    // and custom errors bubble verbatim. Role checks run INSIDE the sidecar bodies.
    address private immutable SIDECAR;

    /// @dev Forward the ENTIRE calldata to the sidecar and bubble its return / revert data.
    function _fwd() private {
        address s = SIDECAR;
        assembly ("memory-safe") {
            let p := mload(0x40)
            calldatacopy(p, 0, calldatasize())
            let ok := delegatecall(gas(), s, p, calldatasize(), 0, 0)
            returndatacopy(p, 0, returndatasize())
            switch ok
            case 0 { revert(p, returndatasize()) }
            default { return(p, returndatasize()) }
        }
    }

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

    /// @notice Clone constructor-equivalent — body in IssueTokenTimeLockSidecar.initialize().
    /// @dev One-shot is enforced by `initializer` HERE (clone storage) before forwarding.
    ///      Params: (_controller, _initialLockDurationMonths, _minPriceUSD, _minPriceLockMonths, _maxHolders)
    ///      — unchanged; full NatSpec on the sidecar.
    function initialize(address, uint256, uint256, uint256, uint256) external initializer {
        _fwd();
    }

    /* ========== SMART CONTRACT TRACKING ========== */

    /**
     * @notice Sync SmartContract addresses from Controller into local cache
     * @dev Can be called by anyone, auto-called on first maxHolders check
     *      Uses mapping for O(1) lookup during transfers (gas efficient)
     *      Can be called multiple times to pick up newly deployed SmartContracts
     *      Cache is additive (new SCs are added, old ones remain cached)
     */
    function syncSmartContractCache() public {
        // v43107: active-only (O(active) on new-model Controllers). The loop
        // below always filtered on .active anyway, so behavior is unchanged;
        // the additive cache retains SCs that later deactivate.
        IController.OfficialEntityStruct[] memory smartContracts =
            IController(controller).getAllOfficialEntities("SmartContract", false);

        uint256 count = 0;
        for (uint256 i = 0; i < smartContracts.length; i++) {
            address scAddress = smartContracts[i].pubAddress;
            if (scAddress != address(0) && smartContracts[i].active) {
                isSmartContractCached[scAddress] = true;
                count++;
            }
        }

        isSmartContractCacheSynced = true;
        emit SmartContractCacheSynced(count);
    }

    /**
     * @notice Check if address is a SmartContract (O(1) cached lookup)
     * @param addr Address to check
     * @return True if address is a cached SmartContract entity
     * @dev Pure cache lookup, no fallback needed (cache is permanent)
     */
    function _isSmartContractEntity(address addr) internal view returns (bool) {
        return isSmartContractCached[addr];
    }

    /* ========== ACTIVE HOLDER LIST MANAGEMENT ========== */

    /**
     * @notice Add holder to active list (internal helper)
     * @param holder Address to add
     * @dev Only adds if not already in list (checked via activeHolderIndex mapping)
     *      Gas cost: ~25k (one-time per new holder)
     */
    function _addToActiveList(address holder) private {
        if (activeHolderIndex[holder] == 0) { // Not in list (0 means not present)
            activeHoldersList.push(holder);
            activeHolderIndex[holder] = activeHoldersList.length; // Store index + 1 (so 0 can mean "not in list")
        }
    }

    /**
     * @notice Remove holder from active list (internal helper)
     * @param holder Address to remove
     * @dev Uses swap-and-pop for O(1) removal
     *      Gas cost: ~5-10k (efficient removal)
     *      Order is not preserved (last element swapped to removed position)
     */
    function _removeFromActiveList(address holder) private {
        uint256 indexPlusOne = activeHolderIndex[holder];
        if (indexPlusOne == 0) return; // Not in list

        uint256 index = indexPlusOne - 1; // Convert to actual index
        uint256 lastIndex = activeHoldersList.length - 1;

        // Swap-and-pop: move last element to deleted position
        if (index != lastIndex) {
            address lastHolder = activeHoldersList[lastIndex];
            activeHoldersList[index] = lastHolder;
            activeHolderIndex[lastHolder] = index + 1; // Update moved holder's index
        }

        activeHoldersList.pop();
        delete activeHolderIndex[holder];
    }

    /* ========== LIFETIME TOKEN BINDING ========== */

    /*
     * Set the IssueToken address (can only be called ONCE, during deployment)
     *   _issueToken — Address of the IssueToken using this TimeLock
     * @param tokenSymbol Token symbol (for DEX URL construction)
     * @param _stableCoinAddress Address of stablecoin used for fee payments and min-price denomination
     * @dev Called by IssueToken constructor immediately after TimeLock deployment
     *      Once set, issueToken can never be changed (permanent 1:1 binding)
     *      stableCoinAddress can be updated later via setStableCoinAddress()
     *
     * SECURITY:
     * - Only works if _issueToken is registered as SmartContract in Controller
     * - Prevents front-running: attacker can't lock TimeLock to wrong token
     * - TimeLock and IssueToken share the SAME Controller (deployed near-simultaneously)
     * - ONLY the deployer has admin access to register SC entities in the Controller
     * - IssueToken is the ONLY SmartContract entity that can satisfy the check at deployment time
     * - One-time lock: after first successful call, forever bound
     *
     * WORKFLOW GUARANTEE:
     * - Contracts are deployed near-atomically by authorized deployer
     * - All platform contracts share single Controller for official SC entity registry
     * - No external/untrusted SC can be registered without deployer admin privileges
     *
     * GAS OPTIMIZATION:
     * - Eliminates 2nd external call in onlyIssueToken modifier (~2,100 gas saved)
     * - Reduces validation from 4,300 gas to 100 gas per transfer
     * - Break-even after 7 transfers, massive savings long-term
     *
     * @param _issueToken The IssueToken contract address
     * @param tokenSymbol Token symbol for URL construction
     * @param _stableCoinAddress Stablecoin address (for min-price denomination)
     */
    // v43109 — SIDECAR STUB (body + NatSpec in IssueTokenTimeLockSidecar).
    function setLifetimeTokenAddress(address, string calldata, address) external { _fwd(); }

    /// @notice Update stablecoin address (bound IssueToken only). v43109 sidecar stub.
    function setStableCoinAddress(address) external { _fwd(); }

    /// @notice Set Chainlink stablecoin/USD feed (TokenAdmin). v43109 sidecar stub.
    function setStableCoinUsdFeed(address) external { _fwd(); }

    /// @notice Set Chainlink USD feeds per token (TokenAdmin). v43109 sidecar stub.
    function setTokenUsdFeeds(address[] calldata, address[] calldata) external { _fwd(); }

    /**
     * @notice Add a timelock allocation using default settings
     * @param user Address receiving the locked allocation
     * @param amount Amount of tokens to lock
     * @dev Uses timeLockDuration and default min price settings
     */
    function addTimeLockedAllocation(address user, uint256 amount) external onlyAuthorized {
        if (user == address(0)) revert InvalidUserAddress();
        if (amount == 0) revert InvalidAmount();

        uint256 unlockTime = timeLockDuration > 0
            ? block.timestamp + timeLockDuration
            : 0;

        uint256 minPriceExpiry = defaultMinPriceDuration > 0
            ? block.timestamp + defaultMinPriceDuration
            : 0;

        // Create new allocation
        userTimeLocks[user].push(TimeLockAllocation({
            amount: amount,
            unlockTime: unlockTime,
            minPriceUSD: defaultMinPriceUSD,
            minPriceExpiry: minPriceExpiry,
            released: false
        }));

        emit TimeLockAdded(user, amount, unlockTime, defaultMinPriceUSD, minPriceExpiry, userTimeLocks[user].length - 1);
    }

    /*
     * Add a timelock allocation with custom unlock time (backward compatible - no price lock)
     *   user — Address receiving the locked allocation
     * @param amount Amount of tokens to lock
     * @param unlockTime Timestamp when time lock expires (0 = no time lock)
     * @dev Backward compatible 3-parameter version - defaults to no price lock
     */
    // v43109 — SIDECAR STUBS (bodies + NatSpec in IssueTokenTimeLockSidecar; TokenAdmin ∨ SmartContract).
    function addTimeLockCustom(address, uint256, uint256) external { _fwd(); }
    function addTimeLockCustom(address, uint256, uint256, uint256, uint256) external { _fwd(); }
    function addTimeLockBatch(address[] calldata, uint256[] calldata, uint256[] calldata, uint256[] calldata, uint256[] calldata) external { _fwd(); }

    /// @notice v43109 — ERC-3643 recovery support: move every unreleased allocation of `from` onto `to`.
    ///         Body in the sidecar; SmartContract-gated (the DistributionManager calls it inside
    ///         recoverHolder BEFORE IssueToken.forcedTransfer, so inheritance sees no sender locks).
    function migrateAllocations(address, address) external { _fwd(); }
    /* v43109 — release (no successor) for the BURN / RESCISSION sinks. Body in IssueTokenTimeLockSidecar. */
    function releaseAllocations(address) external { _fwd(); }

    /**
     * @notice Get total locked amount for a token owner (with recipient for price checking)
     * @param tokenOwner Address to check (the token holder)
     * @param recipient Transfer recipient (for DEX price checks, use address(0) for balance queries)
     * @return Total amount currently locked
     * @dev msg.sender is used to identify the IssueToken address for DEX price detection
     */
    function getLockedAmount(address tokenOwner, address recipient) external view returns (uint256) {
        // check both conditions first to allow a fast bypass when both these globals are false.
        if (globalPermTransferLock || timeLockActive) {
            if (IController(controller).isOfficialEntityPlusNotEntityFast(KECCAK_SMART_CONTRACT, recipient, KECCAK_LIQUIDITY_POOL, recipient, true)) {
                return 0; // SmartContract bypass (SalesManager, DEX routers, etc.)
            }
        } else {
            return 0;
        }
        // 🔒 GLOBAL PERMANENT LOCK: Check first (bypassed by SmartContract recipients)
        if (globalPermTransferLock) {
            // SmartContract recipients ALWAYS bypass global lock
            // Lock entire balance for non-SmartContract recipients
            return IERC20(issueToken).balanceOf(tokenOwner);  // or max_value to save gas?
        }
        if (!timeLockActive) {
            return 0;
        }
        return _calculateLockedAmount(tokenOwner, recipient);
    }

    /**
     * @notice Internal function to calculate locked amount with price checking
     * @param tokenOwner Address to check (the token holder)
     * @param recipient Transfer recipient (address(0) for non-transfer queries)
     * @return Total amount currently locked
     */
    function _calculateLockedAmount(address tokenOwner, address recipient) internal view returns (uint256) {
        TimeLockAllocation[] storage allocations = userTimeLocks[tokenOwner];

        if (allocations.length == 0) {
            return 0;
        }

        uint256 totalLocked = 0;
        uint256 currentTime = block.timestamp;

        // CEX BLOCKING DISABLED - See explanation below
        // bool isBlockedExchange = blockedExchanges[recipient];

        // Try to detect if recipient is a DEX pool and get price IN STABLECOIN UNITS
        bool isDEXTransfer = false;
        uint256 tokenPriceStableCoin18 = 0;

        if (recipient != address(0)) {
            (isDEXTransfer, tokenPriceStableCoin18) = _tryGetDEXPrice(recipient);
        }

        for (uint256 i = 0; i < allocations.length; i++) {
            if (allocations[i].released) {
                continue;
            }

            // Check time-based lock first
            if (allocations[i].unlockTime > currentTime) {
                totalLocked += allocations[i].amount;
                continue;
            }

            // Time lock expired or not set, check price lock
            if (allocations[i].minPriceUSD > 0) {
                // Check if price lock has expired
                bool priceLockActive = (allocations[i].minPriceExpiry == 0) ||
                                       (allocations[i].minPriceExpiry > currentTime);

                if (priceLockActive) {
                    // CEX BLOCKING DISABLED (CRITICAL UX FLAW):
                    // Problem: User transfers to CEX deposit address -> succeeds (leaves wallet)
                    //          CEX internal sweep to hot wallet -> fails (blocked by contract)
                    //          Result: Tokens stuck in limbo, not in user wallet, not credited to CEX
                    //          Creates support nightmares and potential loss
                    // Approach abandoned in favor of DEX-only price enforcement
                    /*
                    if (isBlockedExchange) {
                        totalLocked += allocations[i].amount;
                        continue;
                    }
                    */

                    // Check DEX price if it's a DEX transfer
                    // FAIL-CLOSED: if isDEX but price=0 (oracle missing/stale), lock the tokens
                    if (isDEXTransfer) {
                        if (tokenPriceStableCoin18 == 0) {
                            // Oracle conversion failed - BLOCK transfer (fail-closed)
                            totalLocked += allocations[i].amount;
                            continue;
                        }
                        if (tokenPriceStableCoin18 < allocations[i].minPriceUSD) {
                            // Price too low, lock the tokens
                            totalLocked += allocations[i].amount;
                            continue;
                        }
                    }
                    // If not a DEX transfer, allow (user can still transfer to wallets)
                }
            }
        }

        return totalLocked;
    }

    /**
     * @notice Get amount locked ONLY by time constraints (ignores price locks)
     * @param tokenOwner Address to check
     * @return Amount locked by unexpired time locks
     * @dev Used by requestTransfer to bypass price locks for peer-to-peer transfers
     */
    function getTimeLockedAmount(address tokenOwner) external view returns (uint256) {
        if (!timeLockActive) {
            return 0;
        }

        TimeLockAllocation[] storage allocations = userTimeLocks[tokenOwner];
        uint256 totalLocked = 0;
        uint256 currentTime = block.timestamp;

        for (uint256 i = 0; i < allocations.length; i++) {
            if (!allocations[i].released && allocations[i].unlockTime > currentTime) {
                totalLocked += allocations[i].amount;
            }
        }

        return totalLocked;
    }

    /**
     * @notice Get time-locked amount and latest unlock time for a user
     * @param user Address to check
     * @return lockedAmount Total amount locked by unexpired time locks
     * @return unlockTime Latest (furthest in future) unlock time, 0 if no active time locks
     * @dev Used by RestrictedSaleManager to check if seller can list tokens
     *      Returns ONLY time lock info (ignores price locks)
     */
    function getTimeLock(address user) external view returns (uint256 lockedAmount, uint256 unlockTime) {
        if (!timeLockActive) {
            return (0, 0);
        }

        TimeLockAllocation[] storage allocations = userTimeLocks[user];
        uint256 totalLocked = 0;
        uint256 latestUnlockTime = 0;
        uint256 currentTime = block.timestamp;

        for (uint256 i = 0; i < allocations.length; i++) {
            if (!allocations[i].released && allocations[i].unlockTime > currentTime) {
                totalLocked += allocations[i].amount;
                if (allocations[i].unlockTime > latestUnlockTime) {
                    latestUnlockTime = allocations[i].unlockTime;
                }
            }
        }

        return (totalLocked, latestUnlockTime);
    }

    /* ========== LOCK INHERITANCE SYSTEM ========== */

    /**
     * @notice Handle lock inheritance on transfer AND update active holder count
     * @param from Transfer sender
     * @param to Transfer recipient
     * @param amount Amount transferred
     * @param fromBalanceBefore Sender's balance before transfer (for holder count tracking)
     * @param toBalanceBefore Recipient's balance before transfer (for holder count tracking)
     * @dev Combined function to save gas (one external call instead of two)
     *      Inheritance logic unchanged, just adds holder count tracking
     *
     * INHERITANCE RULES:
     * 1. Only inherits allocations with ACTIVE price locks (time expired + price lock active)
     * 2. Proportional inheritance: if sender transfers 30% of locked tokens, recipient gets 30% of each lock
     * 3. Preserves ALL lock parameters: minPriceUSD, minPriceExpiry, unlockTime (if not expired)
     * 4. Reduces sender's allocations by transferred amount
     * 5. Creates NEW allocations for recipient (doesn't modify existing)
     *
     * GAS OPTIMIZATION:
     * - Early exit if sender has no allocations
     * - Early exit if no price locks active
     * - Only processes allocations that need inheritance
     * - Combined with holder count tracking (saves ~2100 gas per transfer)
     *
     * SECURITY:
     * - Only callable by IssueToken contracts that use this TimeLock
     * - Can't be called directly by users
     * - Called AFTER transfer succeeds (can't block transfer)
     *
     * EXAMPLE:
     *   Alice has 1000 tokens locked: minPrice=$5, expiry=2027
     *   Alice sells 300 tokens to Bob on DEX at $6
     *   Result:
     *     - Alice: 700 tokens locked, minPrice=$5, expiry=2027
     *     - Bob: 300 tokens locked, minPrice=$5, expiry=2027 (INHERITED)
     *   Bob tries to sell at $3 → BLOCKED by inherited price lock ✅
     */
    function handleTransferInheritanceAndUpdateHolderCount(
        address from,
        address to,
        uint256 amount,
        uint256 fromBalanceBefore,
        uint256 toBalanceBefore
    ) external onlyIssueToken {
        // ========== AUTO-SYNC SMARTCONTRACT CACHE (ONE-TIME) ==========
        // Lazy-load on first transfer - ensures cache is populated before holder tracking
        if (!isSmartContractCacheSynced) {
            syncSmartContractCache();
        }

        // ========== HOLDER COUNT TRACKING ==========
        // Do this after sync (so we have accurate SC detection)

        uint256 fromBalanceAfter = fromBalanceBefore - amount;
        uint256 toBalanceAfter = toBalanceBefore + amount;

        // Check if addresses are SmartContracts (O(1) via cache)
        bool fromIsSC = _isSmartContractEntity(from);
        bool toIsSC = _isSmartContractEntity(to);

        // Update count and list for sender (if USER, not SC)
        if (!fromIsSC) {
            if (fromBalanceBefore > 0 && fromBalanceAfter == 0) {
                _removeFromActiveList(from); // Remove from active holders list
                emit ActiveHolderCountChanged(activeHoldersList.length, from, false);
            }
        }

        // Update count and list for recipient (if USER, not SC)
        if (!toIsSC) {
            if (toBalanceBefore == 0 && toBalanceAfter > 0) {
                _addToActiveList(to); // Add to active holders list
                emit ActiveHolderCountChanged(activeHoldersList.length, to, true);
            }
        }

        // ========== LOCK INHERITANCE (EXISTING LOGIC) ==========

        if (!timeLockActive) return; // Global lock disabled, no inheritance

        TimeLockAllocation[] storage senderAllocations = userTimeLocks[from];
        if (senderAllocations.length == 0) return; // Sender has no locks

        uint256 currentTime = block.timestamp;
        uint256 totalInheritableAmount = 0;

        // First pass: Calculate total amount subject to price locks
        for (uint256 i = 0; i < senderAllocations.length; i++) {
            TimeLockAllocation storage alloc = senderAllocations[i];

            if (alloc.released) continue;

            // Only inherit if:
            // 1. Time lock expired (or not set)
            // 2. Price lock is active
            bool timeLockExpired = alloc.unlockTime <= currentTime;
            bool priceLockActive = alloc.minPriceUSD > 0 &&
                                   (alloc.minPriceExpiry == 0 || alloc.minPriceExpiry > currentTime);

            if (timeLockExpired && priceLockActive) {
                totalInheritableAmount += alloc.amount;
            }
        }

        if (totalInheritableAmount == 0) return; // No inheritable locks

        // UNRESTRICTED-FIRST: Calculate how many tokens transfer WITHOUT restrictions
        uint256 senderBalance = fromBalanceBefore; // Use passed parameter instead of external call!
        uint256 unrestrictedAmount = senderBalance > totalInheritableAmount ?
                                     senderBalance - totalInheritableAmount : 0;

        // Only restricted tokens (above unrestricted amount) inherit locks
        uint256 restrictedTransferred = 0;
        if (amount > unrestrictedAmount) {
            restrictedTransferred = amount - unrestrictedAmount;
        }

        if (restrictedTransferred == 0) return; // Only unrestricted tokens transferred

        // Transfer restricted tokens: proportionally reduce sender's allocations
        uint256 remainingToTransfer = restrictedTransferred;

        for (uint256 i = 0; i < senderAllocations.length && remainingToTransfer > 0; i++) {
            TimeLockAllocation storage alloc = senderAllocations[i];

            if (alloc.released) continue;

            bool timeLockExpired = alloc.unlockTime <= currentTime;
            bool priceLockActive = alloc.minPriceUSD > 0 &&
                                   (alloc.minPriceExpiry == 0 || alloc.minPriceExpiry > currentTime);

            if (timeLockExpired && priceLockActive && alloc.amount > 0) {
                // Calculate proportional amount from this allocation
                uint256 allocTransfer = (alloc.amount * restrictedTransferred) / totalInheritableAmount;
                if (allocTransfer > remainingToTransfer) allocTransfer = remainingToTransfer;
                if (allocTransfer > alloc.amount) allocTransfer = alloc.amount;

                if (allocTransfer > 0) {
                    // Reduce sender's allocation
                    alloc.amount -= allocTransfer;
                    remainingToTransfer -= allocTransfer;

                    // Mark as released if fully consumed
                    if (alloc.amount == 0) {
                        alloc.released = true;
                    }

                    // Create recipient's inherited allocation
                    userTimeLocks[to].push(TimeLockAllocation({
                        amount: allocTransfer,
                        unlockTime: alloc.unlockTime, // Already expired, kept for records
                        minPriceUSD: alloc.minPriceUSD, // INHERIT
                        minPriceExpiry: alloc.minPriceExpiry, // INHERIT
                        released: false
                    }));

                    emit TimeLockInherited(from, to, allocTransfer, alloc.minPriceUSD, alloc.minPriceExpiry);
                }
            }
        }
    }

    /**
     * @notice Validate recipient-approved transfer request
     * @param sender Token sender
     * @param recipient Token recipient
     * @param amount Amount to transfer
     * @param signature Recipient's signature
     * @param nonce Unique nonce to prevent replay
     * @return bool True if signature valid and nonce unused
     * @dev Called by IssueToken.requestTransfer() - validates signature and marks nonce as used
     *
     * Signature message format (domain-separated to prevent cross-token replay):
     * keccak256(abi.encodePacked(issueToken, sender, recipient, amount, chainid, nonce))
     */
    function validateRequestTransferSignature(
        address sender,
        address recipient,
        uint256 amount,
        bytes calldata signature,
        uint256 nonce
    ) external returns (bool) {
        if (msg.sender != issueToken) revert OnlyIssueToken();
        // Check nonce hasn't been used
        if (usedRequestTransferNonces[sender][nonce]) {
            return false;
        }

        // Verify recipient signature (domain-separated by issueToken address)
        bytes32 messageHash = keccak256(abi.encodePacked(
            issueToken,
            sender,
            recipient,
            amount,
            block.chainid,
            nonce
        ));
        bytes32 ethSignedMessageHash = keccak256(abi.encodePacked(
            "\x19Ethereum Signed Message:\n32",
            messageHash
        ));

        address signer = ECDSA.recover(ethSignedMessageHash, signature);
        if (signer != recipient) {
            return false;
        }

        // Mark nonce as used
        usedRequestTransferNonces[sender][nonce] = true;

        return true;
    }

    /**
     * @notice Try to detect if address is a DEX pool and get price IN STABLECOIN UNITS
     * @dev Supports both Uniswap V2 and V3 style pools
     * @param potentialPool Address to check
     * @return isDEX True if it's a DEX pool
     * @return priceStableCoin Token price in stablecoin units (18 decimals), 0 if can't determine
     * @dev CRITICAL: Price is now denominated in stableCoinAddress units, NOT "USD"
     *      Uses Chainlink oracles to convert pool quote token into stablecoin units
     *
     * MIN-PRICE ENFORCEMENT POLICY & ORACLE CONFIGURATION:
     * =====================================================
     * DEFAULT (RECOMMENDED): Zero oracle configuration required
     * - Only pools paired with stableCoinAddress (typically USDC) are supported for min-price enforcement
     * - Official pool: MyToken/USDC → price read directly from reserves, NO oracles needed ✅
     * - Unauthorized pools: MyToken/WETH, MyToken/DAI, etc. → FAIL-CLOSED (transfer blocked) ✅
     * - This funnels all min-price-locked trading through YOUR official stablecoin pool
     *
     * ADVANCED (OPTIONAL): Multi-pool support with oracles
     * - To support min-price enforcement on non-stablecoin pools (MyToken/WETH, etc.):
     *   1. TokenAdmin calls setStableCoinUsdFeed(usdcFeedAddress) for stablecoin/USD conversion
     *   2. TokenAdmin calls setTokenUsdFeeds([WETH, DAI], [wethFeed, daiFeed]) for quote token conversion
     * - Example: MyToken/WETH pool at 0.002 WETH, minPrice=$5.00
     *   → Needs WETH/USD feed ($3000) and USDC/USD feed ($1.00)
     *   → Converts: 0.002 WETH × ($3000/$1.00) = $6.00 → compare vs $5.00 ✅
     *
     * FAIL-CLOSED BEHAVIOR:
     * - If pool quote token has no feed configured → returns price=0 → transfer BLOCKED
     * - If feed is stale (>1 hour old) → returns price=0 → transfer BLOCKED
     * - This protects against price manipulation and ensures only authorized pools are used
     */
    function _tryGetDEXPrice(address potentialPool) internal view returns (bool isDEX, uint256 priceStableCoin) {
        // Try Uniswap V3 first (has slot0 function)
        (bool isV3, uint256 priceV3) = _tryGetV3Price(potentialPool);
        if (isV3) {
            return (true, priceV3);
        }

        // Try Uniswap V2 style
        (bool isV2, uint256 priceV2) = _tryGetV2Price(potentialPool);
        if (isV2) {
            return (true, priceV2);
        }

        return (false, 0);
    }

    /**
     * @notice Get Chainlink price with staleness check
     * @param feedAddress Chainlink price feed address
     * @return priceUsd Price in USD (8 decimals, Chainlink standard), 0 if stale/invalid
     * @dev Returns 0 if: feed missing, stale (>1 hour), or negative
     */
    function _getChainlinkPrice(address feedAddress) internal view returns (uint256 priceUsd) {
        if (feedAddress == address(0)) return 0;

        try AggregatorV3Interface(feedAddress).latestRoundData() returns (
            uint80 roundId,
            int256 answer,
            uint256 /* startedAt */,
            uint256 updatedAt,
            uint80 answeredInRound
        ) {
            // Staleness check: must be updated within 1 hour
            if (block.timestamp - updatedAt > 3600) return 0;
            // Round check: must be complete
            if (answeredInRound < roundId) return 0;
            // Price must be positive
            if (answer <= 0) return 0;

            return uint256(answer); // 8 decimals
        } catch {
            return 0;
        }
    }

    /**
     * @notice Try to get price from Uniswap V2 style pool IN STABLECOIN UNITS
     * @param potentialPool Address to check
     * @return isDEX True if valid V2 pool
     * @return priceStableCoin Token price in stablecoin units (18 decimals), 0 if can't convert
     * @dev CONVERSION LOGIC:
     *      1. Compute pool spot price: quoteToken per issueToken (18 decimals)
     *      2. Get oracle prices: quoteToken/USD and stableCoin/USD (8 decimals each)
     *      3. Convert: priceStableCoin = poolPrice * (quoteUSD / stableUSD)
     *      4. FAIL-CLOSED: if oracle missing/stale, return 0 (enforcement will block if minPrice set)
     */
    function _tryGetV2Price(address potentialPool) internal view returns (bool isDEX, uint256 priceStableCoin) {
        try IUniswapV2Pair(potentialPool).token0() returns (address token0) {
            try IUniswapV2Pair(potentialPool).token1() returns (address token1) {
                // It's a valid pair contract
                isDEX = true;

                // Check which token is our issueToken
                if (token0 != issueToken && token1 != issueToken) {
                    return (isDEX, 0); // Not a pool for our token
                }

                // Get reserves
                try IUniswapV2Pair(potentialPool).getReserves() returns (
                    uint112 reserve0,
                    uint112 reserve1,
                    uint32
                ) {
                    if (reserve0 == 0 || reserve1 == 0) {
                        return (isDEX, 0); // No liquidity
                    }

                    // Determine which is the quote token (the counter-asset in the pool)
                    address quoteToken = (token0 == issueToken) ? token1 : token0;
                    uint256 issueTokenReserve = (token0 == issueToken) ? uint256(reserve0) : uint256(reserve1);
                    uint256 quoteTokenReserve = (token0 == issueToken) ? uint256(reserve1) : uint256(reserve0);

                    // Get decimals
                    uint8 quoteDecimals = 18;
                    try IERC20Metadata(quoteToken).decimals() returns (uint8 dec) {
                        quoteDecimals = dec;
                    } catch {}

                    // Calculate pool spot price: quoteToken per issueToken (normalized to 18 decimals)
                    // Adjust for quote token decimals
                    if (quoteDecimals < 18) {
                        quoteTokenReserve = quoteTokenReserve * (10 ** (18 - quoteDecimals));
                    } else if (quoteDecimals > 18) {
                        quoteTokenReserve = quoteTokenReserve / (10 ** (quoteDecimals - 18));
                    }

                    // poolPrice = (quoteReserve * 1e18) / issueTokenReserve
                    uint256 poolPriceQuote18 = (quoteTokenReserve * 1e18) / issueTokenReserve;

                    // ORACLE CONVERSION: quoteToken → stableCoin
                    // If quoteToken == stableCoinAddress, no conversion needed
                    if (quoteToken == stableCoinAddress) {
                        return (isDEX, poolPriceQuote18);
                    }

                    // Otherwise: convert via oracles
                    // priceStable = poolPriceQuote * (quoteUSD / stableUSD)
                    uint256 quoteUsd8 = _getChainlinkPrice(tokenUsdFeeds[quoteToken]);
                    uint256 stableUsd8 = _getChainlinkPrice(stableCoinUsdFeed);

                    // FAIL-CLOSED: if either oracle missing/stale, return 0
                    if (quoteUsd8 == 0 || stableUsd8 == 0) {
                        return (isDEX, 0); // Can't convert, enforcement will block if minPrice set
                    }

                    // Convert: poolPriceQuote18 (18 dec) * quoteUsd8 (8 dec) / stableUsd8 (8 dec) = 18 decimals
                    priceStableCoin = (poolPriceQuote18 * quoteUsd8) / stableUsd8;

                    return (isDEX, priceStableCoin);
                } catch {
                    return (isDEX, 0);
                }
            } catch {
                return (false, 0);
            }
        } catch {
            return (false, 0);
        }
    }

    /**
     * @notice Try to get price from Uniswap V3 style pool IN STABLECOIN UNITS
     * @dev V3 uses sqrtPriceX96 encoding: price = (sqrtPriceX96 / 2^96)^2
     * @param potentialPool Address to check
     * @return isDEX True if valid V3 pool
     * @return priceStableCoin Token price in stablecoin units (18 decimals), 0 if can't convert
     * @dev CONVERSION LOGIC: same as V2, but pool price derived from sqrtPriceX96
     */
    function _tryGetV3Price(address potentialPool) internal view returns (bool isDEX, uint256 priceStableCoin) {
        try IUniswapV3Pool(potentialPool).slot0() returns (
            uint160 sqrtPriceX96,
            int24,
            uint16,
            uint16,
            uint16,
            uint8,
            bool
        ) {
            // Has slot0, likely a V3 pool
            try IUniswapV3Pool(potentialPool).token0() returns (address token0) {
                try IUniswapV3Pool(potentialPool).token1() returns (address token1) {
                    isDEX = true;

                    // Check which token is our issueToken
                    if (token0 != issueToken && token1 != issueToken) {
                        return (isDEX, 0); // Not a pool for our token
                    }

                    // Check liquidity
                    try IUniswapV3Pool(potentialPool).liquidity() returns (uint128 liquidity) {
                        if (liquidity == 0) {
                            return (isDEX, 0); // No liquidity
                        }
                    } catch {
                        return (isDEX, 0);
                    }

                    // Calculate price from sqrtPriceX96
                    // sqrtPriceX96 = sqrt(price) * 2^96
                    // price = (sqrtPriceX96 / 2^96)^2
                    // price = token1/token0 (in token0's units)

                    // To avoid overflow, we calculate: price = (sqrtPriceX96 * sqrtPriceX96) / (2^192)
                    // But we want the result in 18 decimals, so we multiply by 1e18
                    // price = (sqrtPriceX96 * sqrtPriceX96 * 1e18) / (2^192)

                    uint256 sqrtPrice = uint256(sqrtPriceX96);
                    uint256 price;

                    // Calculate price with proper decimal handling
                    // We'll use: price = (sqrtPrice^2 * 1e18) >> 192
                    // Split into two shifts to avoid overflow
                    // NOTE: Theoretical overflow possible if sqrtPrice very large (sqrtPrice^2 > 2^256)
                    // In practice, Uniswap V3 constrains prices, so this is safe
                    price = (sqrtPrice * sqrtPrice) >> 64; // First shift by 64
                    price = (price * 1e18) >> 128; // Then shift by remaining 128 (total 192)

                    // Adjust for token position
                    if (token0 == issueToken) {
                        // price is token1/token0, we want token0 in terms of token1
                        // So we need to invert: 1/price
                        if (price > 0) {
                            price = (1e36) / price; // Invert with 18 decimal precision
                        } else {
                            return (isDEX, 0);
                        }
                    }
                    // If token1 == issueToken, price is already correct (token1/token0)

                    // Adjust for decimals difference
                    address quoteToken = (token0 == issueToken) ? token1 : token0;
                    uint8 quoteDecimals = 18;
                    try IERC20Metadata(quoteToken).decimals() returns (uint8 dec) {
                        quoteDecimals = dec;
                    } catch {}

                    // Adjust price for quote token decimals
                    if (quoteDecimals < 18) {
                        price = price * (10 ** (18 - quoteDecimals));
                    } else if (quoteDecimals > 18) {
                        price = price / (10 ** (quoteDecimals - 18));
                    }

                    // Now price is in 18 decimals: quoteToken per issueToken
                    uint256 poolPriceQuote18 = price;

                    // ORACLE CONVERSION: quoteToken → stableCoin (same as V2)
                    if (quoteToken == stableCoinAddress) {
                        return (isDEX, poolPriceQuote18);
                    }

                    uint256 quoteUsd8 = _getChainlinkPrice(tokenUsdFeeds[quoteToken]);
                    uint256 stableUsd8 = _getChainlinkPrice(stableCoinUsdFeed);

                    // FAIL-CLOSED: if either oracle missing/stale, return 0
                    if (quoteUsd8 == 0 || stableUsd8 == 0) {
                        return (isDEX, 0);
                    }

                    priceStableCoin = (poolPriceQuote18 * quoteUsd8) / stableUsd8;

                    return (isDEX, priceStableCoin);
                } catch {
                    return (isDEX, 0);
                }
            } catch {
                return (isDEX, 0);
            }
        } catch {
            return (false, 0);
        }
    }

    /*
     * Add blocked exchange address (CEX deposit addresses) — param exchange
     * DISABLED - CEX blocking abandoned due to UX issues (see _calculateLockedAmount for details)
     */
    /* COMMENTED OUT - CEX blocking disabled
    function addBlockedExchange(address exchange) external onlyTokenAdmin {
        if (exchange == address(0)) revert InvalidUserAddress();
        if (!blockedExchanges[exchange]) {
            blockedExchanges[exchange] = true;
            blockedExchangeList.push(exchange);
            emit BlockedExchangeAdded(exchange);
        }
    }
    */

    /*
     * Remove blocked exchange address (param exchange = address to unblock)
     * DISABLED - CEX blocking abandoned due to UX issues (see _calculateLockedAmount for details)
     * (plain comment: a NatSpec block here would attach to the next live function)
     */
    /* COMMENTED OUT - CEX blocking disabled
    function removeBlockedExchange(address exchange) external onlyTokenAdmin {
        if (blockedExchanges[exchange]) {
            blockedExchanges[exchange] = false;

            // Remove from list
            for (uint256 i = 0; i < blockedExchangeList.length; i++) {
                if (blockedExchangeList[i] == exchange) {
                    blockedExchangeList[i] = blockedExchangeList[blockedExchangeList.length - 1];
                    blockedExchangeList.pop();
                    break;
                }
            }

            emit BlockedExchangeRemoved(exchange);
        }
    }
    */

    /* ========== FEE EXEMPTION MANAGEMENT ========== */

    // NEW: Fee exemption for CEX hot wallets and treasury addresses
    /*
     * Set fee exemption for addresses (CEX hot wallets, treasury multisigs)
     *   accounts — Addresses to set exemption for
     * @param exempt True = exempt from fees, False = subject to fees
     * @dev Only TokenAdmin can manage fee exemptions
     */
    // v43109 — SIDECAR STUBS (bodies + NatSpec in IssueTokenTimeLockSidecar).
    function setFeeExemptBatch(address[] calldata, bool) external { _fwd(); }      // TokenAdmin
    function setExemptDexSells(bool) external { _fwd(); }                         // PLATFORM_TREASURER
    function setExemptDexBuys(bool) external { _fwd(); }                          // PLATFORM_TREASURER
    function setGlobalPermTransferLock(bool) external { _fwd(); }                 // TokenAdmin

    /* ========== ACTIVE HOLDER LIST GETTERS ========== */

    /**
     * @notice Get range of active holders (paginated for large lists)
     * @param start Start index (inclusive)
     * @param end End index (exclusive)
     * @return holders Array of addresses in range [start, end)
     * @dev Use this for large holder lists to avoid gas limits
     *      Example: getActiveHolderRange(0, 100) returns first 100 holders
     */
    function getActiveHolderRange(uint256 start, uint256 end) external view returns (address[] memory holders) {
        require(end <= activeHoldersList.length, "End out of bounds");
        require(start < end, "Invalid range");

        uint256 length = end - start;
        holders = new address[](length);

        for (uint256 i = 0; i < length; i++) {
            holders[i] = activeHoldersList[start + i];
        }
    }

    /**
     * @notice Get total count of active holders
     * @return Total number of active user holders (excludes SmartContracts)
     * @dev Returns activeHoldersList.length (the single source of truth for holder count)
     */
    function getActiveHolderListLength() external view returns (uint256) {
        return activeHoldersList.length;
    }

    /**
     * @notice Check if address is in active holder list
     * @param holder Address to check
     * @return True if holder has balance > 0 and is not a SmartContract
     */
    function isInActiveHolderList(address holder) external view returns (bool) {
        return activeHolderIndex[holder] > 0;
    }

    /**
     * @notice Get complete transfer fee decision (SINGLE SOURCE OF TRUTH for all transfer policy)
     * @param sender Token sender (from transferFrom parameter)
     * @param recipient Token recipient (to parameter)
     * @param tokenSymbol Token symbol (passed from IssueToken for gas-efficient error message construction)
     * @param transferAmount Amount being transferred (to check if sender will have 0 balance after)
     * @return decision Complete decision: collect fees, block transfer, or allow (with pre-built error messages)
     * @dev IssueToken simply enforces the decision returned here
     *      All policy logic centralized: exemptions, DEX detection, blocking, messaging
     *      Error messages are fully constructed here to save bytecode in IssueToken (~5 KB savings)
     */
    function getTransferFeeDecision(
        address sender,
        address recipient,
        string calldata tokenSymbol,
        uint256 transferAmount
    ) external view returns (FeeDecision memory decision) {

        // ========== MAX HOLDERS CHECK (BEFORE ALL OTHER LOGIC) ==========
        // Also determines SmartContract status for fee logic below (reused)
        // Note: Cache is populated on first actual transfer (in handleTransferInheritanceAndUpdateHolderCount)
        bool recipientIsSmartContract = false;
        bool senderIsSmartContract = false;
        uint256 recipientCodeSize;

        if (maxHolders > 0) {
            // SmartContract recipients ALWAYS bypass maxHolders (never count as "holders")
            // Uses cached lookup if available, falls back to full check if cache not yet populated
            recipientIsSmartContract = _isSmartContractEntity(recipient);
            // IMPORTANT: On the very first transfer, cache may not be synced yet (sync happens post-transfer in _update()).
            // Because getTransferFeeDecision() runs pre-transfer, we MUST fail-safe ONLY before the first cache sync,
            // otherwise maxHolders can incorrectly block transfers to system contracts on the first transfer.
            // After first sync, we intentionally rely on the cache (SmartContract set is assumed stable).
            if (!recipientIsSmartContract && !isSmartContractCacheSynced) {
                assembly { recipientCodeSize := extcodesize(recipient) }
                if (recipientCodeSize > 0) {
                    recipientIsSmartContract = IController(controller).isOfficialEntityFast(
                        KECCAK_SMART_CONTRACT, recipient
                    );
                }
            }

            if (!recipientIsSmartContract) {
                // Check if recipient is NEW (balance = 0)
                try IERC20(issueToken).balanceOf(recipient) returns (uint256 recipientBalance) {
                    bool recipientIsNew = (recipientBalance == 0);

                    if (recipientIsNew) {
                        // Check if sender will have 0 balance after (swap scenario)
                        try IERC20(issueToken).balanceOf(sender) returns (uint256 senderBalance) {
                            bool senderIsLeaving = (senderBalance <= transferAmount);

                            // Use activeHoldersList.length (accurate count of users with balance > 0, excludes SCs)
                            if (activeHoldersList.length >= maxHolders && !senderIsLeaving) {
                                return FeeDecision({
                                    shouldCollectFees: false,
                                    collectFromRecipient: false,
                                    shouldBlock: true,
                                    blockMessage: string(abi.encodePacked(
                                        "Maximum holder limit (",
                                        _uint2str(maxHolders),
                                        ") reached for ",
                                        tokenSymbol,
                                        ". Current active holders: ",
                                        _uint2str(activeHoldersList.length),
                                        ". Transfer to existing holders or sell entire balance."
                                    )),
                                    feeApprovalMessage: ""
                                });
                            }
                        } catch {
                            // Can't get sender balance - fail open
                        }
                    }
                    // else: recipient already has balance (existing holder) - ALWAYS ALLOW
                } catch {
                    // Can't get recipient balance - fail open
                }
            }
            // else: SmartContract recipient - ALWAYS ALLOW
        }

        // Query Controller for SmartContract status if not already determined above
        if (maxHolders == 0) {
            senderIsSmartContract = IController(controller).isOfficialEntityFast(
                KECCAK_SMART_CONTRACT, sender
            );

            assembly { recipientCodeSize := extcodesize(recipient) }
            recipientIsSmartContract = (recipientCodeSize > 0) &&
                IController(controller).isOfficialEntityFast(KECCAK_SMART_CONTRACT, recipient);
        } else {
            // If maxHolders > 0, recipient status already determined from cache above
            // Still need to check sender for fee logic
            senderIsSmartContract = IController(controller).isOfficialEntityFast(
                KECCAK_SMART_CONTRACT, sender
            );
            // Double-check recipient with full logic (cache might be stale for new contracts)
            assembly { recipientCodeSize := extcodesize(recipient) }
            if (!recipientIsSmartContract) {
                recipientIsSmartContract = (recipientCodeSize > 0) &&
                    IController(controller).isOfficialEntityFast(KECCAK_SMART_CONTRACT, recipient);
            }
        }

        // TODO: UNAUTHORIZED CONTRACT RECEIVER BLOCKER (REQUIRED IMPLEMENTATION)
        // ======================================================================
        // REQUIREMENT: Block transfers to ANY smart contract that is NOT authorized
        //
        // PURPOSE: Prevent wrapper token attacks and unauthorized pools/exchanges
        //
        // ALLOWED RECIPIENTS:
        //   ✅ EOAs (regular wallets - extcodesize == 0)
        //   ✅ Registered SmartContracts (official protocol contracts in Controller)
        //   ✅ Fee-exempt addresses (CEX hot wallets, Gnosis Safes via isFeeExempt - ALREADY EXISTS!)
        //
        // BLOCKED RECIPIENTS:
        //   ❌ ALL unregistered smart contracts (wrapper tokens, unauthorized pools, etc)
        //
        // IMPLEMENTATION LOGIC (add HERE before scenario checks):
        //   // Check if wrapper blocking is enabled (registeredSafeFactory != 0x0)
        //   if (registeredSafeFactory != address(0) && recipientCodeSize > 0 && !recipientIsSmartContract) {
        //       // Recipient is unregistered contract - check if it's a registered safe wallet
        //       // Note: isFeeExempt already checked above at line 1530, so exempt contracts bypass this
        //
        //       // Interface for RegisteredSafeFactory
        //       interface IRegisteredSafeFactory {
        //           function isSafeWalletRegistered(address safeAddress) external view returns (bool);
        //       }
        //
        //       bool isRegisteredSafe = IRegisteredSafeFactory(registeredSafeFactory).isSafeWalletRegistered(recipient);
        //
        //       if (!isRegisteredSafe) {
        //           // Unregistered contract - BLOCK
        //           return FeeDecision({
        //               shouldCollectFees: false,
        //               collectFromRecipient: false,
        //               shouldBlock: true,
        //               blockMessage: "Transfers to unauthorized smart contracts are disabled. Recipient must be: EOA, registered SmartContract (via Controller), registered Safe Wallet, or fee-exempt address (contact admin).",
        //               feeApprovalMessage: ""
        //           });
        //       }
        //   }
        //
        // SECURITY: RegisteredSafeFactory provides explicit admin-approved safe wallet registry
        //   ✅ Admin registers Gnosis Safes via RegisteredSafeFactory.registerSafe()
        //   ✅ IssueTokenTimeLock checks registry before allowing transfers
        //   ✅ No way to fake registration (requires TokenAdmin approval)
        //   ✅ Alternative: Add safe to isFeeExempt (bypasses all checks)
        //
        // BENEFITS:
        //   ✅ COMPLETELY prevents wrapper token secondary markets
        //   ✅ Blocks all unauthorized DEX pools
        //   ✅ Forces smart contract integrations through official registration
        //   ✅ Maintains CEX withdrawal support via existing isFeeExempt system
        //
        // IMPLEMENTATION STEPS:
        //   1. Add check HERE (after isFeeExempt check at line 1530, before scenario 2):
        //      ~18 lines including interface definition
        //
        //   2. User onboarding for Gnosis Safes:
        //      Option A: Register via RegisteredSafeFactory.registerSafe(safeAddress) - TokenAdmin only
        //      Option B: Add to isFeeExempt list (fee-exempt + authorized receiver)
        //      → Option A recommended for Gnosis Safes (purpose-built for this)
        //      → Option B recommended for CEX hot wallets (fee exemption is primary goal)
        //
        //   3. Deployment flow (automatic):
        //      - ControllerFactory looks up RegisteredSafeFactory from PlatformController
        //      - Calls timeLock.setRegisteredSafeFactory() during deployAll()
        //      - Wrapped in try/catch (allowed to fail for backwards compatibility)
        //      - If RSF exists, wrapper blocking automatically enabled
        //
        //   4. Test extensively with:
        //      - Gnosis Safe transfers (after registering in RSF)
        //      - CEX withdrawals (after adding to isFeeExempt)
        //      - Official protocol contracts (already registered in Controller)
        //      - Wrapper attempts (must be blocked - RSF check will fail)
        //
        //   5. Document in user-facing materials:
        //      - "Only authorized smart contracts can receive tokens"
        //      - "For Gnosis Safe: Register at RegisteredSafeFactory (contact admin)"
        //      - "For CEX listings: Request fee-exempt status for hot wallet"
        //      - "All contract receivers require explicit authorization"
        //
        // NOTE: CEX exemption ALREADY EXISTS via isFeeExempt mapping (line 175, 1511)
        //       Admin can add CEX hot wallet addresses: setFeeExemptBatch([cexAddress], true)
        //       This check only adds wrapper/unauthorized pool protection
        // ======================================================================

        // ========== DECISION LOGIC (5 scenarios) ==========

        // 1. Explicit fee exemptions (CEX hot wallets, treasury multisigs)
        // IMPORTANT: Only sender exemption bypasses fees - NOT recipient exemption!
        // Rationale: If user sends TO a CEX, fees should still be collected from sender.
        //            Only CEX withdrawals (CEX as sender) should be fee-free.
        // Note: Fee-exempt recipients are still allowed (not blocked) - see wrapper prevention check below
        if (isFeeExempt[sender] ) {    // || isFeeExempt[recipient] ← Intentionally commented out
            return FeeDecision({
                shouldCollectFees: false,
                collectFromRecipient: false,
                shouldBlock: false,
                blockMessage: "",
                feeApprovalMessage: ""
            });
        }

        // 1b. WRAPPER ATTACK PREVENTION - Block unregistered contract receivers
        // Only enforced if RegisteredSafeFactory is set (optional feature)
        // EXEMPT: Fee-exempt addresses (CEX hot wallets) bypass this check but still pay fees above
        if (registeredSafeFactory != address(0) && recipientCodeSize > 0 && !recipientIsSmartContract && !isFeeExempt[recipient]) {
            // Recipient is unregistered contract AND not fee-exempt - check if it's a registered safe wallet
            bool isRegisteredSafe = IRegisteredSafeFactory(registeredSafeFactory).isSafeWalletRegistered(recipient);

            if (!isRegisteredSafe) {
                // Unregistered contract - BLOCK
                return FeeDecision({
                    shouldCollectFees: false,
                    collectFromRecipient: false,
                    shouldBlock: true,
                    blockMessage: "Transfers to unauthorized smart contracts are disabled. Recipient must be: EOA, registered SmartContract (via Controller), registered Safe Wallet (via RegisteredSafeFactory), or fee-exempt address (contact admin).",
                    feeApprovalMessage: ""
                });
            }
        }

        // 2. P2P transfers (user → user)
        if (!senderIsSmartContract && !recipientIsSmartContract) {
            return FeeDecision({
                shouldCollectFees: true,  // Always collect fees on P2P
                collectFromRecipient: false,
                shouldBlock: false,
                blockMessage: "",
                feeApprovalMessage: string(abi.encodePacked(
                    "Transfers of ",
                    tokenSymbol,
                    " require USDC pre-approval to pay transfer fee. Visit ",
                    _getDexTradeUrl(),
                    " to pre-approve USDC for trading and transfers."
                ))
            });
        }

        // 3. DEX SELL detection (user → pool)
        if (!senderIsSmartContract && recipientIsSmartContract) {
            (bool recipientIsDEX, ) = _tryGetDEXPrice(recipient);

            if (recipientIsDEX) {
                // This is a DEX sell
                if (!exemptDexSells) {
                    // Fees required on DEX sells

                    if (blockDirectDexSellsToForcePermitFlow) {
                        // OPTION A (STRICT): Block with clear message
                        return FeeDecision({
                            shouldCollectFees: false,
                            collectFromRecipient: false,
                            shouldBlock: true,
                            blockMessage: string(abi.encodePacked(
                                "Direct DEX sales of ",
                                tokenSymbol,
                                " are disabled. Please visit ",
                                _getDexTradeUrl(),
                                " to trade."
                            )),
                            feeApprovalMessage: ""
                        });
                    } else {
                        // OPTION B (PERMISSIVE - DEFAULT): Allow if seller pre-approved USDC
                        return FeeDecision({
                            shouldCollectFees: true,
                            collectFromRecipient: false,  // Collect from seller (sender)
                            shouldBlock: false,
                            blockMessage: "",
                            feeApprovalMessage: string(abi.encodePacked(
                                "DEX sales of ",
                                tokenSymbol,
                                " require USDC pre-approval to pay trading fee. Visit ",
                                _getDexTradeUrl(),
                                " to pre-approve USDC for trading, then try again here or complete your trade there."
                            ))
                        });
                    }
                } else {
                    // Fees exempt for DEX sells
                    return FeeDecision({
                        shouldCollectFees: false,
                        collectFromRecipient: false,
                        shouldBlock: false,
                        blockMessage: "",
                        feeApprovalMessage: ""
                    });
                }
            }
            // Not a DEX, another SmartContract - fallthrough to scenario 5
        }

        // 4. DEX BUY detection (pool → user)
        if (senderIsSmartContract && !recipientIsSmartContract) {
            (bool senderIsDEX, ) = _tryGetDEXPrice(sender);

            if (senderIsDEX) {
                // This is a DEX buy
                if (!exemptDexBuys) {
                    // Fees required on DEX buys

                    if (blockDirectDexBuysToForcePermitFlow) {
                        // OPTION A (DEFAULT): Strict mode - Block with clear message
                        return FeeDecision({
                            shouldCollectFees: false,
                            collectFromRecipient: false,
                            shouldBlock: true,
                            blockMessage: string(abi.encodePacked(
                                "Direct DEX purchases of ",
                                tokenSymbol,
                                " are disabled. Please visit ",
                                _getDexTradeUrl(),
                                " to trade."
                            )),
                            feeApprovalMessage: ""
                        });
                    } else {
                        // OPTION B (PERMISSIVE - DEFAULT): Allow if buyer pre-approved USDC
                        return FeeDecision({
                            shouldCollectFees: true,
                            collectFromRecipient: true,  // Collect from buyer, not pool!
                            shouldBlock: false,
                            blockMessage: "",
                            feeApprovalMessage: string(abi.encodePacked(
                                "DEX purchases of ",
                                tokenSymbol,
                                " require USDC pre-approval to pay trading fee. Visit ",
                                _getDexTradeUrl(),
                                " to pre-approve USDC for trading, then try again here or complete your trade there."
                            ))
                        });
                    }
                } else {
                    // Fees exempt for DEX buys
                    return FeeDecision({
                        shouldCollectFees: false,
                        collectFromRecipient: false,
                        shouldBlock: false,
                        blockMessage: "",
                        feeApprovalMessage: ""
                    });
                }
            }
            // Not a DEX, another SmartContract - fallthrough to scenario 5
        }

        // 5. Other SmartContract transfers (SaleManager → user, Pool → Pool, etc)
        //    These are official protocol operations - no fees, no blocking
        //
        // ⚠️ SECURITY MODEL: Fee exemption for OFFICIAL protocol contracts only
        //    SmartContract status requires TWO conditions (AND):
        //    1. Address has bytecode (extcodesize > 0)
        //    2. Registered in Controller as KECCAK_SMART_CONTRACT (admin-controlled)
        //
        //    INTENDED FOR:
        //    ✅ RestrictedSaleManager (official escrow)
        //    ✅ Protocol treasuries (ProjectRevenueTreasury, etc)
        //    ✅ Official DEX routers/integrations
        //    ✅ Staking, vesting, rewards contracts
        //
        //    NOT INTENDED FOR (and now hard-blocked at scenario 1b above):
        //    ❌ Third-party CEXes (they should pay fees or users trade on YOUR pool)
        //    ❌ Wrapper token contracts (deposit attempts are blocked — see below)
        //    ❌ Unofficial escrows/exchanges
        //
        // ✅ WRAPPER ATTACK — MITIGATED via scenario 1b (above, ~L1755)
        //    The historic "deploy a permissionless WrappedIssueToken to escape transfer
        //    restrictions" vector is now closed at the deposit step. Scenario 1b runs
        //    BEFORE this scenario 5 fall-through and blocks any transfer whose recipient
        //    is a contract (extcodesize > 0) that is NOT one of:
        //       • a registered SmartContract entity in the Controller, OR
        //       • a registered Safe in IRegisteredSafeFactory, OR
        //       • on the isFeeExempt allow-list (CEX hot wallets, treasury multisigs).
        //    A user's `transferFrom(user, wrapper, amount)` deposit attempt therefore
        //    reverts with the "Transfers to unauthorized smart contracts are disabled"
        //    block message — the wrapper can never accumulate IssueToken balance and
        //    no parallel secondary market can form.
        //
        //    Residual conditions for the bypass to re-open (admin-discipline issues,
        //    not code defects):
        //      1. registeredSafeFactory == address(0) on this TimeLock → scenario 1b
        //         is skipped. ControllerFactory wires this automatically on new
        //         deploys, but legacy TimeLocks may need a manual
        //         setRegisteredSafeFactory() call.
        //      2. A wrapper address is added to isFeeExempt (admin error — CEX-only
        //         exemption being abused as a generic bypass).
        //      3. A wrapper address is registered as KECCAK_SMART_CONTRACT in the
        //         Controller (admin error or rogue platform admin) AND
        //         permLockPlatform() is later invoked, locking the bad registration
        //         in permanently. Hygiene before permLockPlatform() is critical.
        return FeeDecision({
            shouldCollectFees: false,
            collectFromRecipient: false,
            shouldBlock: false,
            blockMessage: "",
            feeApprovalMessage: ""
        });
    }

    /*
     * Toggle blocking of direct DEX buys when fees are required
     *   blocked — True = Strict mode (block DEX buys, force website)
     *                False = Permissive mode (allow DEX buys if buyer pre-approved USDC)
     * @dev Only PLATFORM_TREASURER can modify this economic policy setting
     */
    function setBlockDirectDexBuysToForcePermitFlow(bool) external { _fwd(); }   // v43109 sidecar stub (PLATFORM_TREASURER)
    function setBlockDirectDexSellsToForcePermitFlow(bool) external { _fwd(); }  // v43109 sidecar stub (PLATFORM_TREASURER)

    /**
     * @notice Get all fee-exempt addresses
     * @return Array of fee-exempt addresses
     */
    function getFeeExemptAddresses() external view returns (address[] memory) {
        return feeExemptList;
    }

    /*
     * Set custom DEX trade URL for error messages
     *   url — Custom URL to display (empty string = use default https://equitymint.org/dex)
     * @dev Only TreasuryAdmin can set this (user-facing content decision)
     *      Examples: "https://app.mytoken.com/trade", "https://equitymint.org/trade/SYMBOL"
     */
    function setDexTradeUrl(string calldata) external { _fwd(); }                // v43109 sidecar stub (TokenAdmin)
    function setMaxHolders(uint256) external { _fwd(); }                         // v43109 sidecar stub (TokenAdmin; >0 is reduced by 6)
    function setRegisteredSafeFactory(address) external { _fwd(); }              // v43109 sidecar stub (TokenAdmin ∨ SmartContract)

    /**
     * @notice Get the DEX trade URL to display in error messages
     * @return URL string (custom if set, otherwise default)
     * @dev Internal helper to centralize URL logic
     */
    function _getDexTradeUrl() internal view returns (string memory) {
        if (bytes(dexTradeUrl).length > 0) {
            return dexTradeUrl;
        }
        return "https://equitymint.org/dex";
    }

    /**
     * @notice Convert uint to string for error messages
     * @dev Internal helper for gas-efficient numeric error messages
     */
    function _uint2str(uint256 _i) internal pure returns (string memory) {
        if (_i == 0) return "0";
        uint256 j = _i;
        uint256 len;
        while (j != 0) {
            len++;
            j /= 10;
        }
        bytes memory bstr = new bytes(len);
        uint256 k = len;
        while (_i != 0) {
            k = k - 1;
            bstr[k] = bytes1(uint8(48 + _i % 10));
            _i /= 10;
        }
        return string(bstr);
    }

    /*
     * Set default minimum price and duration
     *   minPriceUSD — Minimum price in USD (18 decimals, 0 = disabled)
     * @param minPriceDurationSeconds Total duration for min price lock in seconds (0 = permanent if minPriceUSD > 0)
     * @dev Only TreasuryAdmin can modify price parameters - this is a financial/economic decision
     */
    function setMinPriceDefaults(uint256, uint256) external { _fwd(); }          // v43109 sidecar stub (TokenAdmin)
    function setTimeLockDuration(uint256) external { _fwd(); }                   // v43109 sidecar stub (TokenAdmin)
    function setTimeLockActive(bool) external { _fwd(); }                        // v43109 sidecar stub (TokenAdmin)

    /**
     * @notice Get all timelock allocations for a user
     */
    function getUserTimeLocks(address user) external view returns (
        uint256[] memory amounts,
        uint256[] memory unlockTimes,
        uint256[] memory minPricesUSD,
        uint256[] memory minPriceExpiries,
        bool[] memory released
    ) {
        TimeLockAllocation[] storage allocations = userTimeLocks[user];
        uint256 length = allocations.length;

        amounts = new uint256[](length);
        unlockTimes = new uint256[](length);
        minPricesUSD = new uint256[](length);
        minPriceExpiries = new uint256[](length);
        released = new bool[](length);

        for (uint256 i = 0; i < length; i++) {
            amounts[i] = allocations[i].amount;
            unlockTimes[i] = allocations[i].unlockTime;
            minPricesUSD[i] = allocations[i].minPriceUSD;
            minPriceExpiries[i] = allocations[i].minPriceExpiry;
            released[i] = allocations[i].released;
        }

        return (amounts, unlockTimes, minPricesUSD, minPriceExpiries, released);
    }

    /**
     * @notice Get active (non-released, still locked) timelock allocations for a user
     */
    function getActiveTimeLocks(address user) external view returns (
        uint256[] memory amounts,
        uint256[] memory unlockTimes,
        uint256[] memory minPricesUSD,
        uint256[] memory minPriceExpiries,
        uint256[] memory indices
    ) {
        TimeLockAllocation[] storage allocations = userTimeLocks[user];
        uint256 currentTime = block.timestamp;

        // Count active locks
        uint256 activeCount = 0;
        for (uint256 i = 0; i < allocations.length; i++) {
            if (!allocations[i].released) {
                bool timeLocked = allocations[i].unlockTime > currentTime;
                bool priceLocked = allocations[i].minPriceUSD > 0 &&
                                   (allocations[i].minPriceExpiry == 0 || allocations[i].minPriceExpiry > currentTime);
                if (timeLocked || priceLocked) {
                    activeCount++;
                }
            }
        }

        // Populate arrays
        amounts = new uint256[](activeCount);
        unlockTimes = new uint256[](activeCount);
        minPricesUSD = new uint256[](activeCount);
        minPriceExpiries = new uint256[](activeCount);
        indices = new uint256[](activeCount);

        uint256 j = 0;
        for (uint256 i = 0; i < allocations.length; i++) {
            if (!allocations[i].released) {
                bool timeLocked = allocations[i].unlockTime > currentTime;
                bool priceLocked = allocations[i].minPriceUSD > 0 &&
                                   (allocations[i].minPriceExpiry == 0 || allocations[i].minPriceExpiry > currentTime);
                if (timeLocked || priceLocked) {
                    amounts[j] = allocations[i].amount;
                    unlockTimes[j] = allocations[i].unlockTime;
                    minPricesUSD[j] = allocations[i].minPriceUSD;
                    minPriceExpiries[j] = allocations[i].minPriceExpiry;
                    indices[j] = i;
                    j++;
                }
            }
        }

        return (amounts, unlockTimes, minPricesUSD, minPriceExpiries, indices);
    }

    /*
     * Mark allocations as released (admin function for emergency or manual release)
     *   user — Address to release
     * @param allocationIndices Array of allocation indices to release
     */
    function releaseTimeLocks(address, uint256[] calldata) external { _fwd(); }  // v43109 sidecar stub (TokenAdmin)

    /**
     * @notice Check if timelock is currently active
     * @return True if timelocks are being enforced
     */
    function isTimeLockActive() external view returns (bool) {
        return timeLockActive;
    }

    /**
     * @notice Get count of allocations for a user
     * @param user Address to check
     * @return Number of timelock allocations
     */
    function getUserTimeLockCount(address user) external view returns (uint256) {
        return userTimeLocks[user].length;
    }

    /**
     * @notice Get a specific allocation for a user
     * @param user Address to check
     * @param index Allocation index
     */
    function getTimeLockByIndex(address user, uint256 index) external view returns (
        uint256 amount,
        uint256 unlockTime,
        uint256 minPriceUSD,
        uint256 minPriceExpiry,
        bool released
    ) {
        if (index >= userTimeLocks[user].length) revert InvalidAllocationIndex();
        TimeLockAllocation storage allocation = userTimeLocks[user][index];
        return (allocation.amount, allocation.unlockTime, allocation.minPriceUSD, allocation.minPriceExpiry, allocation.released);
    }

    /**
     * @notice Get all blocked exchange addresses
     * @return Array of blocked exchange addresses
     * @dev DISABLED - CEX blocking abandoned due to UX issues
     */
    /* COMMENTED OUT - CEX blocking disabled
    function getBlockedExchanges() external view returns (address[] memory) {
        return blockedExchangeList;
    }
    */
}

// =====================================================================
//  IssueTokenTimeLockSidecar — cold-path bodies for IssueTokenTimeLock (v43109)
// =====================================================================
//  Bytecode carrier for initialize() and every cold admin setter of the
//  model above, so those bytes count against THIS contract's EIP-170 budget,
//  not the model's. Deployed by the model's own constructor (`new` in
//  IssueTokenTimeLock's constructor); its address is an immutable inside the
//  model and NO factory / PPAM / UI change is required. The model's stubs
//  forward msg.data here via delegatecall: bodies execute against the CLONE's
//  storage with address(this) = clone and the caller's msg.sender — byte-
//  identical semantics (events are emitted from the clone address).
//
//  ⚠️ STORAGE LAYOUT CONTRACT (verify via solc storageLayout diff):
//  Same bases in the same order as the parent (TreasuryConstants has no
//  storage; CloneInitializable's _initState at slot 0), then a VERBATIM copy
//  of EVERY parent declaration in the same order, including inline
//  initializers (they only run in creation code, which is irrelevant here,
//  but keeping them verbatim keeps the diff trivially reviewable).
//  NEVER reorder, retype, or insert declarations here without re-diffing the
//  storage layouts of parent and sidecar.
contract IssueTokenTimeLockSidecar is TreasuryConstants, CloneInitializable {

    /* ===== storage mirror (verbatim copy of the parent's declarations) ===== */
    struct TimeLockAllocation {
        uint256 amount;
        uint256 unlockTime;
        uint256 minPriceUSD;
        uint256 minPriceExpiry;
        bool released;
    }
    address public controller;
    address public issueToken;
    address public stableCoinAddress;
    address public stableCoinUsdFeed;
    mapping(address => address) public tokenUsdFeeds;
    address public registeredSafeFactory;
    bool public timeLockActive;
    uint256 public timeLockDuration = 0;
    uint256 public defaultMinPriceUSD = 0;
    uint256 public defaultMinPriceDuration = 0;
    mapping(address => TimeLockAllocation[]) public userTimeLocks;
    mapping(address => bool) public blockedExchanges;
    address[] public blockedExchangeList;
    mapping(address => mapping(uint256 => bool)) public usedRequestTransferNonces;
    mapping(address => bool) public isFeeExempt;
    address[] public feeExemptList;
    bool public exemptDexSells = false;
    bool public exemptDexBuys = false;
    bool public blockDirectDexBuysToForcePermitFlow = false;
    bool public globalPermTransferLock = false;
    bool public blockDirectDexSellsToForcePermitFlow = false;
    string public dexTradeUrl;
    uint256 public maxHolders = 0;
    mapping(address => bool) public isSmartContractCached;
    bool public isSmartContractCacheSynced;
    address[] private activeHoldersList;
    mapping(address => uint256) private activeHolderIndex;

    /* ===== events re-declared (same signatures ⇒ same topics; emitted from the clone) ===== */
    event TimeLockAdded(address indexed user, uint256 amount, uint256 unlockTime, uint256 minPriceUSD, uint256 minPriceExpiry, uint256 allocationIndex);
    event TimeLockActiveChanged(bool active);
    event TimeLockDurationChanged(uint256 newDuration);
    event MinPriceDefaultsChanged(uint256 minPriceUSD, uint256 minPriceDuration);
    event FeeExemptionChanged(address indexed account, bool exempt, address indexed changedBy);
    event ExemptDexSellsChanged(bool exempt, address indexed changedBy);
    event ExemptDexBuysChanged(bool exempt, address indexed changedBy);
    event BlockDirectDexBuysToForcePermitFlowChanged(bool blocked, address indexed changedBy);
    event BlockDirectDexSellsToForcePermitFlowChanged(bool blocked, address indexed changedBy);
    event DexTradeUrlChanged(string newUrl, address indexed changedBy);
    event MaxHoldersChanged(uint256 newMaxHolders, address indexed changedBy);
    event GlobalPermTransferLockChanged(bool locked, address indexed changedBy);
    event SmartContractCacheSynced(uint256 count);
    event StableCoinAddressChanged(address indexed oldAddress, address indexed newAddress, address indexed changedBy);
    event StableCoinUsdFeedChanged(address indexed newFeed, address indexed changedBy);
    event TokenUsdFeedSet(address indexed token, address indexed feed, address indexed changedBy);
    /// @notice v43109 — emitted by migrateAllocations (ERC-3643 recovery).
    event AllocationsMigrated(address indexed from, address indexed to, uint256 count, uint256 totalAmount, address indexed by);

    /// @dev Set at deployment; used to reject DIRECT calls (which would run against the
    ///      sidecar's own storage). Under delegatecall address(this) is the clone, never __SELF.
    address private immutable __SELF;
    error DirectCallForbidden();

    constructor() {
        __SELF = address(this);
        _disableInitializers();
    }

    /* ===== modifiers duplicated from the parent ===== */
    modifier notDirect() {
        if (address(this) == __SELF) revert DirectCallForbidden();
        _;
    }
    modifier onlyTokenAdmin() {
        if (!IController(controller).isOfficialEntityFast(KECCAK_TOKEN_ADMIN, msg.sender)) revert NotTokenAdmin();
        _;
    }
    modifier onlyAuthorized() {
        if (!IController(controller).isOfficialDoubleEntityFast(KECCAK_TOKEN_ADMIN, msg.sender, KECCAK_SMART_CONTRACT, msg.sender, false)) revert NotAuthorized();
        _;
    }
    modifier onlyPlatformTreasurer() {
        if (!IController(controller).isPlatformAdmin(msg.sender, KECCAK_TREASURY_ADMIN)) revert NotAuthorized();
        _;
    }
    modifier onlyIssueToken() {
        if (msg.sender != issueToken) revert OnlyIssueToken();
        _;
    }

    /* ========== CLONE CONSTRUCTOR-EQUIVALENT (former constructor, verbatim) ========== */

    /// @notice Clone constructor-equivalent. Reached ONLY via the model stub's delegatecall
    ///         (the stub's `initializer` modifier already ran against clone storage).
    /// @param _controller Controller contract address
    /// @param _initialLockDurationMonths Initial time lock duration in months (0-60, uses 31-day periods)
    /// @param _minPriceUSD Minimum price in USD (18 decimals, 0 = disabled)
    /// @param _minPriceLockMonths Additional months for min price lock AFTER time lock expires (0 = no min price lock)
    /// @param _maxHolders Maximum number of user holders (0 = unlimited)
    /// @dev Example: (controller, 18, 2.21e18, 18, 100) = 18 month time lock, then $2.21 min price for months 19-36, max 94 user holders (100-6)
    function initialize(
        address _controller,
        uint256 _initialLockDurationMonths,
        uint256 _minPriceUSD,
        uint256 _minPriceLockMonths,
        uint256 _maxHolders
    ) external notDirect {
        if (_controller == address(0)) revert InvalidController();
        if (_initialLockDurationMonths > 60) revert MaxLockDurationExceeded();
        if (_minPriceLockMonths > 120) revert MaxLockDurationExceeded();

        timeLockActive = true; // ex-inline initializer (see declaration)
        controller = _controller;
        IController(_controller).init(address(this), "IssueTokenTimeLock");
        // 31 days * 24 hours * 60 min * 60 sec = 2,678,400 seconds per month
        timeLockDuration = _initialLockDurationMonths * 2678400;
        defaultMinPriceUSD = _minPriceUSD;
        // _minPriceLockMonths == 0 && _minPriceUSD > 0 ⇒ PERMANENT price lock;
        // _minPriceLockMonths > 0 ⇒ ends at timeLockDuration + minPriceLockMonths.
        if (_minPriceLockMonths > 0) {
            defaultMinPriceDuration = timeLockDuration + (_minPriceLockMonths * 2678400);
        }
        maxHolders = _maxHolders;
    }

    /* ========== LIFETIME TOKEN BINDING / ORACLES ========== */

    /// @notice One-time IssueToken binding. `_issueToken` must already be a SmartContract on THIS
    ///         controller (front-running defense); the symbol is passed to avoid an external call
    ///         during token construction. See the parent's historical NatSpec for the full rationale.
    function setLifetimeTokenAddress(address _issueToken, string calldata tokenSymbol, address _stableCoinAddress) external notDirect {
        if (issueToken != address(0)) revert TokenAddressAlreadySet();
        if (_issueToken == address(0)) revert InvalidUserAddress();
        if (!IController(controller).isOfficialEntityFast(KECCAK_SMART_CONTRACT, _issueToken)) revert TokenNotRegisteredAsSmartContract();
        issueToken = _issueToken;
        stableCoinAddress = _stableCoinAddress;
        dexTradeUrl = string(abi.encodePacked("https://equitymint.org/trade/", tokenSymbol));
    }

    /// @notice Stablecoin rotation sync — bound IssueToken only.
    function setStableCoinAddress(address _stableCoinAddress) external notDirect onlyIssueToken {
        address oldAddress = stableCoinAddress;
        stableCoinAddress = _stableCoinAddress;
        emit StableCoinAddressChanged(oldAddress, _stableCoinAddress, msg.sender);
    }

    /// @notice Chainlink stablecoin/USD feed (8 decimals).
    function setStableCoinUsdFeed(address feedAddress) external notDirect onlyTokenAdmin {
        stableCoinUsdFeed = feedAddress;
        emit StableCoinUsdFeedChanged(feedAddress, msg.sender);
    }

    /// @notice Chainlink USD feeds per pool quote token (8 decimals), batch.
    function setTokenUsdFeeds(address[] calldata tokens, address[] calldata feeds) external notDirect onlyTokenAdmin {
        require(tokens.length == feeds.length, "Array length mismatch");
        for (uint256 i = 0; i < tokens.length; i++) {
            tokenUsdFeeds[tokens[i]] = feeds[i];
            emit TokenUsdFeedSet(tokens[i], feeds[i], msg.sender);
        }
    }

    /* ========== CUSTOM / BATCH ALLOCATIONS ========== */

    /// @notice Custom unlock time, no price lock (3-param compatibility form).
    function addTimeLockCustom(address user, uint256 amount, uint256 unlockTime) external notDirect onlyAuthorized {
        _addTimeLockCustomInternal(user, amount, unlockTime, 0, 0);
    }

    /// @notice Custom unlock time + optional price lock.
    /// @param minPriceUSD Minimum price in USD (18 decimals, 0 = no price lock)
    /// @param minPriceExpiry Timestamp when price lock expires (0 = never expires if minPriceUSD > 0)
    function addTimeLockCustom(address user, uint256 amount, uint256 unlockTime, uint256 minPriceUSD, uint256 minPriceExpiry) external notDirect onlyAuthorized {
        _addTimeLockCustomInternal(user, amount, unlockTime, minPriceUSD, minPriceExpiry);
    }

    function _addTimeLockCustomInternal(address user, uint256 amount, uint256 unlockTime, uint256 minPriceUSD, uint256 minPriceExpiry) internal {
        if (user == address(0)) revert InvalidUserAddress();
        if (amount == 0) revert InvalidAmount();
        userTimeLocks[user].push(TimeLockAllocation({
            amount: amount,
            unlockTime: unlockTime,
            minPriceUSD: minPriceUSD,
            minPriceExpiry: minPriceExpiry,
            released: false
        }));
        emit TimeLockAdded(user, amount, unlockTime, minPriceUSD, minPriceExpiry, userTimeLocks[user].length - 1);
    }

    /// @notice Batch add allocations.
    function addTimeLockBatch(
        address[] calldata users,
        uint256[] calldata amounts,
        uint256[] calldata unlockTimes,
        uint256[] calldata minPricesUSD,
        uint256[] calldata minPriceExpiries
    ) external notDirect onlyAuthorized {
        if (users.length != amounts.length ||
            users.length != unlockTimes.length ||
            users.length != minPricesUSD.length ||
            users.length != minPriceExpiries.length) revert ArrayLengthMismatch();
        for (uint256 i = 0; i < users.length; i++) {
            _addTimeLockCustomInternal(users[i], amounts[i], unlockTimes[i], minPricesUSD[i], minPriceExpiries[i]);
        }
    }

    /* ========== v43109 — ERC-3643 RECOVERY: ALLOCATION MIGRATION ========== */

    /// @notice Move every UNRELEASED allocation of `from` onto `to` (Rule 144 / price locks follow the
    ///         beneficial owner), marking the originals released. SmartContract-gated: the project's
    ///         DistributionManager calls this inside recoverHolder() BEFORE IssueToken.forcedTransfer,
    ///         so handleTransferInheritanceAndUpdateHolderCount sees no sender allocations and cannot
    ///         double-inherit onto `to`. Idempotent for an address with nothing unreleased.
    /// @dev    Gate uses the SC cache (synced lazily, same as the hot path) — no Controller call.
    function migrateAllocations(address from, address to) external notDirect {
        if (!isSmartContractCacheSynced) _syncSmartContractCache();
        if (!isSmartContractCached[msg.sender]) revert NotAuthorized();
        if (from == address(0) || to == address(0) || from == to) revert InvalidUserAddress();

        TimeLockAllocation[] storage src = userTimeLocks[from];
        TimeLockAllocation[] storage dst = userTimeLocks[to];
        uint256 moved;
        uint256 total;
        for (uint256 i = 0; i < src.length; i++) {
            if (src[i].released) continue;
            dst.push(TimeLockAllocation({
                amount: src[i].amount,
                unlockTime: src[i].unlockTime,
                minPriceUSD: src[i].minPriceUSD,
                minPriceExpiry: src[i].minPriceExpiry,
                released: false
            }));
            src[i].released = true;
            moved++;
            total += src[i].amount;
        }
        emit AllocationsMigrated(from, to, moved, total, msg.sender);
    }

    /// @notice Mark every UNRELEASED allocation of `holder` released WITHOUT a successor (EQM-3643
    ///         BURN and RESCISSION sinks). The DM calls this BEFORE IssueToken.forcedTransfer so the
    ///         transfer-inheritance hook cannot push the holder's Rule-144 / price locks onto the
    ///         Token Treasury (the IssueToken address) — treasury supply must stay lock-free for
    ///         resale. Emits AllocationsMigrated with to == address(0) (= released, not moved).
    function releaseAllocations(address holder) external notDirect {
        if (!isSmartContractCacheSynced) _syncSmartContractCache();
        if (!isSmartContractCached[msg.sender]) revert NotAuthorized();
        if (holder == address(0)) revert InvalidUserAddress();

        TimeLockAllocation[] storage src = userTimeLocks[holder];
        uint256 released;
        uint256 total;
        for (uint256 i = 0; i < src.length; i++) {
            if (src[i].released) continue;
            src[i].released = true;
            released++;
            total += src[i].amount;
        }
        emit AllocationsMigrated(holder, address(0), released, total, msg.sender);
    }

    /// @dev Verbatim copy of the parent's syncSmartContractCache (additive, active-only).
    function _syncSmartContractCache() private {
        IController.OfficialEntityStruct[] memory smartContracts =
            IController(controller).getAllOfficialEntities("SmartContract", false);
        uint256 count = 0;
        for (uint256 i = 0; i < smartContracts.length; i++) {
            address scAddress = smartContracts[i].pubAddress;
            if (scAddress != address(0) && smartContracts[i].active) {
                isSmartContractCached[scAddress] = true;
                count++;
            }
        }
        isSmartContractCacheSynced = true;
        emit SmartContractCacheSynced(count);
    }

    /* ========== FEE EXEMPTION / DEX POLICY / LOCK SWITCHES ========== */

    /// @notice Fee exemption for CEX hot wallets and treasury multisigs (TokenAdmin).
    function setFeeExemptBatch(address[] calldata accounts, bool exempt) external notDirect onlyTokenAdmin {
        for (uint256 i = 0; i < accounts.length; i++) {
            if (exempt && !isFeeExempt[accounts[i]]) {
                feeExemptList.push(accounts[i]);
            }
            isFeeExempt[accounts[i]] = exempt;
            emit FeeExemptionChanged(accounts[i], exempt, msg.sender);
        }
    }

    /// @notice DEX sell fee exemption policy (PLATFORM_TREASURER — economic decision).
    function setExemptDexSells(bool exempt) external notDirect onlyPlatformTreasurer {
        exemptDexSells = exempt;
        emit ExemptDexSellsChanged(exempt, msg.sender);
    }

    /// @notice DEX buy fee exemption policy (PLATFORM_TREASURER — economic decision).
    function setExemptDexBuys(bool exempt) external notDirect onlyPlatformTreasurer {
        exemptDexBuys = exempt;
        emit ExemptDexBuysChanged(exempt, msg.sender);
    }

    /// @notice Global permanent transfer lock; SmartContract recipients always bypass (TokenAdmin).
    function setGlobalPermTransferLock(bool locked) external notDirect onlyTokenAdmin {
        globalPermTransferLock = locked;
        emit GlobalPermTransferLockChanged(locked, msg.sender);
    }

    /// @notice Strict (block) vs permissive direct DEX buys when fees are due (PLATFORM_TREASURER).
    function setBlockDirectDexBuysToForcePermitFlow(bool blocked) external notDirect onlyPlatformTreasurer {
        blockDirectDexBuysToForcePermitFlow = blocked;
        emit BlockDirectDexBuysToForcePermitFlowChanged(blocked, msg.sender);
    }

    /// @notice Strict (block) vs permissive direct DEX sells when fees are due (PLATFORM_TREASURER).
    function setBlockDirectDexSellsToForcePermitFlow(bool blocked) external notDirect onlyPlatformTreasurer {
        blockDirectDexSellsToForcePermitFlow = blocked;
        emit BlockDirectDexSellsToForcePermitFlowChanged(blocked, msg.sender);
    }

    /// @notice Custom DEX trade URL for error messages (empty = default) (TokenAdmin).
    function setDexTradeUrl(string calldata url) external notDirect onlyTokenAdmin {
        dexTradeUrl = url;
        emit DexTradeUrlChanged(url, msg.sender);
    }

    /// @notice Maximum user holders; >0 is reduced by 6 reserved system slots (TokenAdmin).
    ///         ⚠️ Do not use CEXs when > 0 — failed transfers fail silently on the exchange side.
    function setMaxHolders(uint256 _maxHolders) external notDirect onlyTokenAdmin {
        if (_maxHolders > 0) {
            maxHolders = _maxHolders > 6 ? _maxHolders - 6 : 1;
        } else {
            maxHolders = 0;
        }
        emit MaxHoldersChanged(maxHolders, msg.sender);
    }

    /// @notice RegisteredSafeFactory binding — enables wrapper-attack prevention (TokenAdmin ∨ SmartContract;
    ///         ControllerFactory sets it during deployAll). No event (low-level security config).
    function setRegisteredSafeFactory(address _registeredSafeFactory) external notDirect onlyAuthorized {
        registeredSafeFactory = _registeredSafeFactory;
    }

    /// @notice Default min price + duration for addTimeLockedAllocation (TokenAdmin).
    function setMinPriceDefaults(uint256 minPriceUSD, uint256 minPriceDurationSeconds) external notDirect onlyTokenAdmin {
        defaultMinPriceUSD = minPriceUSD;
        defaultMinPriceDuration = minPriceDurationSeconds;
        emit MinPriceDefaultsChanged(minPriceUSD, minPriceDurationSeconds);
    }

    /// @notice Lock duration for addTimeLockedAllocation (0 = no lock) (TokenAdmin).
    function setTimeLockDuration(uint256 durationInSeconds) external notDirect onlyTokenAdmin {
        timeLockDuration = durationInSeconds;
        emit TimeLockDurationChanged(durationInSeconds);
    }

    /// @notice Enable / disable timelock enforcement globally (TokenAdmin).
    function setTimeLockActive(bool active) external notDirect onlyTokenAdmin {
        timeLockActive = active;
        emit TimeLockActiveChanged(active);
    }

    /// @notice Mark allocations released (emergency / manual release) (TokenAdmin).
    function releaseTimeLocks(address user, uint256[] calldata allocationIndices) external notDirect onlyTokenAdmin {
        TimeLockAllocation[] storage allocations = userTimeLocks[user];
        for (uint256 i = 0; i < allocationIndices.length; i++) {
            if (allocationIndices[i] >= allocations.length) revert InvalidAllocationIndex();
            allocations[allocationIndices[i]].released = true;
        }
    }
}

@openzeppelin/contracts/utils/cryptography/ECDSA.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     */
    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError, bytes32) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

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;
    }
}

contracts/TreasuryConstants.sol

// SPDX-License-Identifier: UNLICENSED
// =====================================================================
//  EquityMint.org / DataCloud OS  —  Official Sovereign Issuance Suite
//  Module: TreasuryConstants.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
// 
// Permission to use, copy, modify, or distribute this software is strictly prohibited
// without prior written consent from US Fintech LLC.
// 
// 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.

pragma solidity 0.8.35;

/// @title TreasuryConstants
/// @notice Shared constants for treasury contracts to avoid diamond inheritance conflicts
/// @dev This abstract contract provides keccak256 hashes for entity type strings used across treasury contracts
/// @author Ken Silverman
abstract contract TreasuryConstants {
    /// @notice Pre-computed keccak256 hash of "Super" for gas-optimized entity checks
    bytes32 public constant KECCAK_SUPER = keccak256(bytes("Super"));
    
    /// @notice Pre-computed keccak256 hash of "TreasuryAdmin" for gas-optimized entity checks
    bytes32 public constant KECCAK_TREASURY_ADMIN = keccak256(bytes("TreasuryAdmin"));
    
    /// @notice Pre-computed keccak256 hash of "SmartContract" for gas-optimized entity checks
    bytes32 public constant KECCAK_SMART_CONTRACT = keccak256(bytes("SmartContract"));
    
    /// @notice Pre-computed keccak256 hash of "TokenAdmin" for gas-optimized entity checks
    bytes32 public constant KECCAK_TOKEN_ADMIN = keccak256(bytes("TokenAdmin"));

    /// @notice Pre-computed keccak256 hash of "Registrar" for gas-optimized entity checks (platform/project registrars)
    bytes32 public constant KECCAK_REGISTRAR = keccak256(bytes("Registrar"));
    
    /// @notice Pre-computed keccak256 hash of "ThirdPartyRegistrar" for gas-optimized entity checks (third-party KYC providers)
    bytes32 public constant KECCAK_THIRD_PARTY_REGISTRAR = keccak256(bytes("ThirdPartyRegistrar"));
    
    /// @notice Pre-computed keccak256 hash of "SwappableToken" for gas-optimized entity checks
    bytes32 public constant KECCAK_SWAPPABLE_TOKEN = keccak256(bytes("SwappableToken"));

    /// @notice Pre-computed keccak256 hash of "TransferAgent" — ERC-3643 recovery / forced-transfer operator.
    /// @dev    The admin type is created per project by IssueTokenDistributionManager.initialize(), which
    ///         registers the DM itself as the first TransferAgent (Controller only lets an existing
    ///         SmartContract entity auto-register a new admin type). Project Super then adds human agents.
    ///         Gates: DM.recoverHolder (agent EOAs), IssueToken.restrictWhitelistedUsers (Registrar ∨ agent,
    ///         so the DM can vacate a wallet atomically), RSM / ReleaseManager permanentRestrictThenCancel.
    bytes32 public constant KECCAK_TRANSFER_AGENT = keccak256(bytes("TransferAgent"));

    /// @notice ⚠️ DEPRECATED: PLATFORM_TREASURER check - use controller.isPlatformTreasuryAdmin() instead
    /// @dev Kept for backwards compatibility. New architecture checks TreasuryAdmin in PLATFORM_CONTROLLER
    bytes32 public constant KECCAK_PLATFORM_TREASURER = keccak256(bytes("PLATFORM_TREASURER"));

    /// @notice Pre-computed keccak256 hash of "PLATFORM_CONTROLLER" for entity type registration
    /// @dev Used to register the platform controller as an official entity in project controllers
    bytes32 public constant KECCAK_PLATFORM_CONTROLLER = keccak256(bytes("PLATFORM_CONTROLLER"));

    /// @notice Pre-computed keccak256 hash of "ControllerFactory" for entity type registration
    /// @dev Used to authorize factory deployments in Controller.init()
    bytes32 public constant KECCAK_CONTROLLER_FACTORY = keccak256(bytes("ControllerFactory"));

    /// @notice ⚠️ DEPRECATED: FEE_CHAIN_TYPE is now encapsulated in FeeManager as DEFAULT_FEE_CHAIN_TYPE
    bytes32 public constant KECCAK_PLATFORM_FEE_CHAINED_ENTITY = keccak256(bytes("PLATFORM_FEE_CHAINED_ENTITY"));
    /// @notice Pre-computed keccak256 hash of "LiquidityPool" for gas-optimized entity checks
    bytes32 public constant KECCAK_LIQUIDITY_POOL = keccak256(bytes("LiquidityPool"));
    
    /// @notice Pre-computed keccak256 hash of "RegisteredSafeFactory" for multi-sig safe registration
    /// @dev Used by IssueTokenTimeLock to distinguish legitimate multi-sig wallets from wrapper contracts
    bytes32 public constant KECCAK_REGISTERED_SAFE_FACTORY = keccak256(bytes("RegisteredSafeFactory"));
    
    /// @notice Pre-computed keccak256 hash of "OfficialStablecoin" for stablecoin validation
    /// @dev Used to validate only approved stablecoins can be used for fees and settlements
    bytes32 public constant KECCAK_OFFICIAL_STABLECOIN = keccak256(bytes("OfficialStableCoin"));

    /// @notice Shared errors to avoid duplicate declarations across treasury contracts
    error NotTokenAdmin();
    error InvalidStablecoin();
}

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);
}
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.