Skip to content
Verified contractPartialUNLICENSED

ControllerFactory

Address0x7419dfc1a02f378ec084f7bb926bdda61e1b2b27
Balance

0 ETH

 

Transactions

5

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 700 runs
Via IR
yes
License
UNLICENSED
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,148,941
Creation transaction
0xcffa160713…6394b689d8

contracts/ControllerFactory.sol

// SPDX-License-Identifier: UNLICENSED
// =====================================================================
//  EquityMint.org / DataCloud OS  —  Official Sovereign Issuance Suite
//  Module: ControllerFactory.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.
//
// Controller Factory - Deterministic deployment factory for the complete EquityMint suite including
// Controller, ProjectRevenueTreasury, TokenContent, Token, TimeLock, SalesManager, LiquidityProvider,
// and RestrictedSaleManager. Manages subdomain fee templates, PropertyNFT GADM registry, and deployment
// tracking across all chains. Uses CREATE2 for predictable addresses and integrates with PlatformUniverse
// for fee validation.
//
// Chief Architect and CEO: Ken Silverman, US Fintech LLC
// Designed by Ken Silverman as part of the EquityMint deployment 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.
// See Equitymint.org or other authorized Data Cloud OS entities for more details.
// tokens created under this framework are subject to the terms and conditions of the subscription agreement.
// See Equitymint.org/tokensale for more information on the token project provided to you by the project owner.
// Enter the (Controller or token address) and symbol of such project there for more details.
// there you will be able to verify that the subscription agremeent is hosted properly
// at the URL/tokenAddress for the token you are deploying.
pragma solidity 0.8.35;

import "../interfaces/IController.sol";
import "../interfaces/IFeeManager.sol";

interface IPlatformProjectsAndModels {
    function PLATFORM_CONTROLLER() external view returns (address);
    function recordProjectContract(address deployedContract, bytes32 pureInitHash, uint32 initCodeLength) external;
}

// Minimal interface for IssueToken peer treasury transfers
interface IIssueToken {
    function peerTreasuryTransferTokensDirect(address token, address to, uint256 amount) external;
    function stableCoinAddress() external view returns (address);
}

interface IIssueTokenTimeLock {
    function setRegisteredSafeFactory(address _registeredSafeFactory) external;
}

// Minimal ERC20 Permit interface (EIP-2612)
interface IERC20Permit {
    function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
}

// Minimal Uniswap V2 Pair interface for pool validation
interface IUniswapV2Pair {
    function factory() external view returns (address);
    function token0() external view returns (address);
    function token1() external view returns (address);
}

/// @author Ken Silverman
/// @notice This contract is used to deploy the Controller, TokenContent, Token, and SaleManager contracts.
/// @notice Also manages subdomain fee configurations for whitelabel deployments
contract ControllerFactory {

    // ===== Events =====
    event DeployFeeCollected(address indexed deployer, address indexed feeManager, uint256 amount);

    // ===== Constants =====
    bytes32 private constant KECCAK_SMART_CONTRACT = keccak256(bytes("SmartContract"));
    bytes32 private constant KECCAK_FEE_DEPLOY = keccak256("Deploy");

    // ===== Factory Configuration =====
    address public immutable FACTORY_CONTROLLER;  // The ONE controller this factory belongs to
    address public immutable PLATFORM_UNIVERSE;   // 🆕 PlatformUniverse for fee validation & holder settlements
    address public immutable REGISTERED_SAFE_FACTORY; // 🆕 RegisteredSafeFactory for multi-sig safe registration (required, validated as SmartContract)
    address public platformProjectsAndModels;
    string public constant BASE_DOMAIN = "equitymint.org";

    // 🔥 Keccak256 constants for fast entity checks (matching Controller.sol)
    bytes32 public constant KECCAK_SUPER_ADMIN = keccak256(bytes("Super"));
    bytes32 public constant KECCAK_TREASURY_ADMIN = keccak256(bytes("TreasuryAdmin"));
    bytes32 public constant KECCAK_TOKEN_ADMIN = keccak256(bytes("TokenAdmin"));
    uint16 public constant CONTRACT_VERSION = 43105;

    // ===== Fee Templates MOVED TO PLATFORMUNIVERSE =====
    // All fee template management is now handled by PlatformUniverse contract
    // This keeps ControllerFactory lean and under 24KB size limit


    // ===== Deployment Registry See PlatformUniverse.sol for the majority of storage =====
    // PRIMARY STORAGE: Full deployment data stored ONCE by controller address
    // INDEXES: All mappings store only controller addresses as references
    mapping(address => address[]) internal controllersByUser;  // user -> controller[]
    //mapping(address => mapping(string => mapping(uint256 => address))) internal controllerByDeployerSubdomainChain;  // deployer -> subdomain -> chainId -> controller
    //mapping(string => mapping(address => mapping(uint256 => address))) internal controllerByCompositeKey;  // compositeKey -> deployer -> chainId -> controller
    //mapping(string => address[]) internal deployersBySubdomain;  // subdomain -> deployer[]
    //mapping(address => mapping(string => bool)) private hasDeployedForSubdomain;  // deployer -> subdomain -> bool

    // ===== 🆕 Model Contract Registry =====
    // Maps controller address to ordered array of 13 model addresses (same order as PlatformUniverse.Deployment):
    // [0] controller, [1] feeManager, [2] tokenContent, [3] timeLockManager, [4] token, 
    // [5] saleManager, [6] navPoolManager, [7] liquidityProvider, [8] distributionManager,
    // [9] projectRevenueTreasury, [10] restrictedSaleManager, [11] teamManager, [12] releaseManager
    mapping(address => address[]) private modelAddressesByController;

    // Enumerate all project controllers deployed by this factory (for migration/UI)
    address[] public allProjectControllers;
    mapping(address => bool) private _isProjectControllerTracked;

    // ===== PropertyNFT GADM Registry =====
    // Maps GADM location hash (4 or 5-level hierarchy) to PropertyNFT contract address
    // Prevents duplicate PropertyNFTs for same physical location
    mapping(bytes32 => address) public propertyNFTAddressesByGADMHash;
    mapping(address => bytes32) public gadmHashByPropertyNFT;  // Reverse lookup

    // ========================================================================
    // STRIPPED INITCODE CACHE (on-chain, for calldata reduction)
    // ========================================================================
    // Key: keccak256(bytes(contractTypeStringLower))
    // Value: one or more pointer contracts whose runtime code is: 0x00 || strippedInitCodeChunk
    // (SSTORE2-style; read via EXTCODECOPY starting at offset 1)
    //
    // IMPORTANT:
    // - We cache INITCODE BYTES (creation bytecode without constructor args), but we store it USING pointer contract runtime.
    // - Pointer runtime code is limited by EIP-170 (24,576 bytes). Therefore we CHUNK the initcode across multiple pointers.
    //
    // We keep pointer0 mapping for backward compatibility/getters, but the canonical source is the chunk maps below.
    mapping(bytes32 => address) private strippedInitCodePointerByType; // pointer for chunk 0
    mapping(bytes32 => mapping(uint16 => address)) private strippedInitCodeChunkPointerByType;
    mapping(bytes32 => uint16) private strippedInitCodeChunkCountByType;
    mapping(bytes32 => uint32) private strippedInitCodeTotalLenByType;

    // SSTORE2 pointer runtime is: 0x00 || data. Runtime size limit is 24,576 bytes, so data max is 24,575 bytes.
    uint256 private constant _SSTORE2_MAX_DATA_BYTES = 24575;
    // Use 5% headroom (requested) to avoid edge-case overhead and future changes.
    uint256 private constant _SSTORE2_CHUNK_BYTES = (_SSTORE2_MAX_DATA_BYTES * 95) / 100; // 23,346 bytes

    event StrippedInitCodeCached(
        bytes32 indexed contractTypeHash,
        address indexed pointer,
        uint256 initCodeLength,
        address indexed uploader
    );
    event StrippedInitCodeCachedChunk(
        bytes32 indexed contractTypeHash,
        uint16 indexed chunkIndex,
        address indexed pointer,
        uint256 chunkLength,
        address uploader
    );
    event StrippedInitCodeCleared(bytes32 indexed contractTypeHash, address indexed caller);
    event StrippedInitCodePointerSet(bytes32 indexed contractTypeHash, address indexed pointer, address indexed caller);
    
    // 🔍 DEBUG EVENT: Log initcode hash before CREATE2 (compare working vs failing deploys)
    event InitCodeAssembled(
        string indexed label,
        bytes32 initCodeHash,
        uint256 initCodeLength,
        uint256 paramsLength,
        uint256 totalLength
    );

    /// @notice Emitted once per CREATE2-deployed project contract for off-chain
    ///         constructor-args reconstruction (used by ConstructorParamsReconstructor).
    /// @dev    `encodedArgs` is decoded with the model's constructor ABI off-chain.
    ///         `pureInitHash` identifies the model used for this CREATE2 (matches
    ///         PPAM.ModelContractRecord.pureInitHash for the corresponding model).
    ///         Param NAMES are NOT stored on chain — they live in the verified
    ///         model ABI, which the reader fetches anyway. Lookup is bounded by
    ///         the block number stored in PPAM.getProjectContractRecord(addr).blockNumber.
    /// @param  deployedContract  The freshly CREATE2-deployed contract address.
    /// @param  pureInitHash      keccak256 of the init code with NO ctor args.
    /// @param  encodedArgs       The exact ABI-encoded constructor args bytes.
    event ProjectContractDeployed(
        address indexed deployedContract,
        bytes32 indexed pureInitHash,
        bytes   encodedArgs
    );

    uint256 public totalDeployments;
    
    // ⚠️ CRITICAL: projectDeploymentNumberIndex is incremented IMMEDIATELY when deployAll1 starts
    // This ensures each new project gets a unique salt counter even if multiple deployAll1 calls
    // happen in the same block or if a previous deployment is incomplete.
    uint256 public projectDeploymentNumberIndex;

    // ===== LEGACY STRUCT REMOVED =====
    // The Deployment struct has been removed to save bytecode (~150-200 bytes).
    // Use IPlatformUniverse.Deployment from the interface for all deployment queries.

    // Return struct for deployAll to avoid stack too deep
    struct DeploymentResult {
        address controller;
        address feeManager;              // 🆕 NEW: FeeManager deployed after Controller
        address projectRevenueTreasury;  // 🔄 RENAMED from platformChainTreasury
        address tokenContent;
        address timeLockManager;
        address token;
        address saleManager;
        address liquidityProvider;
        address restrictedSaleManager;
        address teamManager;
        address liquidityPool;
        address navPoolManager;          // 🆕 NAV Pool Manager
        address distributionManager;     // 🆕 Distribution Manager
        address releaseManager;          // 🆕 OPTIONAL: ExecutiveReleaseManager
        address batchTransferAndExtrasManager; // 🆕 Phase 7: BatchTransferAndExtrasManager (after ReleaseManager)
    }

    // Bytecode struct to separate large byte arrays
    struct Bytecodes {
        bytes controller;
        bytes feeManager;              // 🆕 NEW: FeeManager bytecode
        bytes projectRevenueTreasury;  // 🔄 RENAMED from platformChainTreasury
        bytes tokenContent;
        bytes timeLock;
        bytes token;
        bytes saleManager;
        bytes liquidityProvider;
        bytes restrictedSaleManager;
        bytes teamManager;
        bytes navPoolManager;          // 🆕 NAV Pool Manager bytecode
        bytes distributionManager;     // 🆕 Distribution Manager bytecode
        bytes releaseManager;          // 🆕 OPTIONAL: ExecutiveReleaseManager bytecode (empty = skip)
        bytes batchTransferAndExtrasManager; // 🆕 Phase 7: BTM bytecode (after ReleaseManager)
    }

    // Constructor params struct
    struct DeploymentParams {
        ControllerParams controllerParams;
        FeeManagerParams feeManagerParams;         // 🆕 NEW: FeeManager params (separated from Controller)
        TokenContentParams tokenContentParams;
        TimeLockParams timeLockParams;
        TokenParams tokenParams;
        SaleManagerParams saleManagerParams;
        LiquidityProviderParams liquidityParams;
        ProjectRevenueTreasuryParams treasuryParams;  // 🔄 MOVED after LiquidityProviderParams
        RestrictedSaleManagerParams restrictedSaleParams;
        NavPoolManagerParams navPoolParams;           // 🆕 NAV Pool Manager params (REQUIRED)
        DistributionManagerParams distributionParams; // 🆕 Distribution Manager params (REQUIRED)
        string domain;
        string subdomain;
        uint256 permitDeadline;    // 🆕 Permit deadline for deploy fee (0 = no fee expected)
        uint8 permitV;             // 🆕 Permit signature v
        bytes32 permitR;           // 🆕 Permit signature r
        bytes32 permitS;           // 🆕 Permit signature s
    }

    // ✅ Structs to reduce stack depth
    struct ControllerParams {
        address projectSuperAddress;
        string projectSuperName;
        string projectSuperId;
        string projectName;
        string projectId;
    }

    struct FeeManagerParams {
        IFeeManager.EntityFeesWithNames[] platformTreasuryConfigs;
    }

    struct TokenParams {
        address initialAdmin;
        string tokenName;
        string tokenSymbol;
        string tokenDescription;
        uint256 initialMaxSupply;   // 🔄 RENAMED from maxSupply for clarity (matches constructor param)
        uint8 decimals;
        address stableCoinAddress;  // USDC/USDT for fees and liquidity
    }

    struct TokenContentParams {
        string tokenDocBaseUrl;
        bytes32 tokenDocHash;
        string tokenDocDescription;
    }

    /// @notice Params for IssueTokenSaleManager construction.
    /// @dev v43105 alignment:
    ///      - Dropped `usdcAddress`. SaleManager no longer bakes USDC in as a
    ///        special payment mode — projects that want USDC call
    ///        IssueTokenSaleManager.addPaymentToken(usdc, usdcUsdFeed) AFTER deployment.
    ///      - `purchasePriceInUSD` is kept as the FACTORY-SIDE field name because
    ///        the deployer literally specifies USD at deploy time (SaleManager
    ///        boots with fiatSymbol="USD"). Inside the SaleManager the same number
    ///        is stored as `purchasePriceInFIAT` since at runtime that slot is
    ///        reinterpreted under whatever fiat is currently active. If the
    ///        project later runs SaleManager.setFiat(...) the stored number stays
    ///        the same but is read in the new fiat.
    struct SaleManagerParams {
        uint256 purchasePriceInUSD;     // Initial price (18 decimals) in USD — assigned to SaleManager.purchasePriceInFIAT
        address ethUsdPriceFeed;
        address usdtUsdPriceFeed;
        address stablecoinUsdPriceFeed; // saleStable / USD feed (8 dec)
        address usdtAddress;
    }

    struct ProjectRevenueTreasuryParams {  // 🔄 RENAMED from PlatformChainTreasuryParams
        address targetTokenAddress;
        uint256 liquidityPercentageBps;        // 🆕 Percentage for liquidity (e.g., 4000 = 40%)
        uint256 distributionPercentageBps;     // 🆕 Percentage for distribution (e.g., 3000 = 30%)
        uint256 navPoolPercentageBps;          // 🆕 Percentage for NAV pool (e.g., 3000 = 30%)
        uint256 projectTransferBaseFeeAmount;  // 🆕 Base transfer fee (USDC, 6 decimals)
        uint256 initialDisburseThreshold;      // 🆕 Initial disburse threshold in stablecoin units (e.g., 5000 for $5000)
    }

    struct TimeLockParams {
        uint256 initialDurationMonths;
        uint256 minPriceUSD;
        uint256 minPriceLockMonths;
        uint256 maxHolders;
    }

    struct LiquidityProviderParams {
        address trustedFactory;          // Trusted DEX factory address (e.g., Uniswap V2 factory)
        string factoryIdentifier;        // Factory type identifier (e.g., "UNI-V2", "CAKE", "SUSHI")
        address liquidityPoolAddress;    // 🆕 Pre-existing pool address (address(0) if creating new)
        bool createPoolIfZero;           // 🆕 If liquidityPoolAddress==0, create pool via DEX factory
    }

    struct NavPoolManagerParams {
        uint256 initialOnDays;        // Initial redemption window on-days (e.g., 3)
        uint256 initialOffDays;       // Initial redemption window off-days (e.g., 3)
        // NOTE: initialNavAdmin is auto-set to first TreasuryAdmin from Controller (if any exists)
    }

    struct DistributionManagerParams {
        uint256 initialAutoDistributeThreshold;  // Initial auto-distribute threshold (0 = disabled, >= 100 to enable)
        uint256 distributionSupplyBasis;          // Expected total supply for distribution calculations (0 = disabled, uses actual supply)
    }

    struct RestrictedSaleManagerParams {
        address usdcAddress;
        address usdcUsdPriceFeed;
        uint256 minSalePriceUSD;  // Minimum sale price in USD (18 decimals)
        uint256 minHoldTime;      // Minimum hold time in months
    }

    event DeploymentComplete(
        address indexed deployer,
        address indexed controller,
        uint256 timestamp
    );

    event PropertyNFTRegistered(
        bytes32 indexed gadmHash,
        address indexed propertyNFT,
        address indexed deployer,
        uint256 timestamp
    );

    // Errors
    error Unauthorized();
    error SubdomainNotApproved();
    error InvalidFeeConfiguration();
    error NotAuthorized();
    error FeeTemplateMismatch();
    error FeeTemplateNotConfigured();
    error InvalidPlatformUniverse();
    error InvalidRegisteredSafeFactory();
    error InvalidControllerFromPlatformUniverse();
    error TransferFeeRequired();
    error InitWindowAlreadyOpen();
    error InvalidGADMHash();
    error InvalidPropertyNFTAddress();
    error PropertyNFTAlreadyExists();
    error ControllerMustBePlatformController();
    error RegisteredSafeFactoryNotRegistered();
    error DexFactoryNotApproved();
    error PoolCreationFailed();
    error NoDeployments();
    error CachedInitCodeNotFound(bytes32 contractTypeHash);
    error InvalidInitCode();
    error IncompleteDeploymentExists();
    error PoolCreationReturnedZero();
    error TokenSaleNotOfficial();
    error StablecoinMismatch();
    error FactoryAddressZero();
    error FactoryIdentifierEmpty();
    error LiquidityProviderNotRegistered();
    error PoolFactoryMismatch();
    error PoolMissingToken();
    error PoolMissingStablecoin();
    error DeploymentFailed(string label);
    error DebugStop(string label);

    constructor(address platformUniverse, address registeredSafeFactory, address platformProjectsAndModelsAddress) {
        if (platformUniverse == address(0)) revert InvalidPlatformUniverse();
        if (registeredSafeFactory == address(0)) revert InvalidRegisteredSafeFactory();
        if (platformProjectsAndModelsAddress == address(0)) revert InvalidControllerFromPlatformUniverse();

        // 🔒 SECURITY: Get platform controller from PlatformUniverse and validate it's self-referential
        address factoryController = IPlatformUniverse(platformUniverse).PLATFORM_CONTROLLER();
        if (factoryController == address(0)) revert InvalidControllerFromPlatformUniverse();

        // 🔒 SECURITY: Validate that the controller is the platform controller (self-referential)
        // This ensures the factory can't be deployed with a child project controller
        if (!IController(factoryController).isPlatform()) revert ControllerMustBePlatformController();

        // 🔒 SECURITY: Validate RegisteredSafeFactory is registered as SmartContract in platform controller
        // Used by IssueTokenTimeLock to distinguish legitimate multi-sig wallets from wrapper contracts
        if (!IController(factoryController).isOfficialEntityFast(KECCAK_SMART_CONTRACT, registeredSafeFactory)) {
            revert RegisteredSafeFactoryNotRegistered();
        }

        FACTORY_CONTROLLER = factoryController;
        PLATFORM_UNIVERSE = platformUniverse;
        REGISTERED_SAFE_FACTORY = registeredSafeFactory;
        // 🔒 SECURITY: PlatformProjectsAndModels must be bound to THIS platform controller
        if (IPlatformProjectsAndModels(platformProjectsAndModelsAddress).PLATFORM_CONTROLLER() != factoryController) {
            revert InvalidControllerFromPlatformUniverse();
        }
        platformProjectsAndModels = platformProjectsAndModelsAddress;
        
        // ⚠️ CRITICAL: Initialize projectDeploymentNumberIndex to 0 (explicit for clarity)
        // First project will use index 1 (after pre-increment in deployAll1)
        projectDeploymentNumberIndex = 0;

        // Register factory as SmartContract official entity in the platform controller
        // See controller init and addofficialentity for more details.
        IController(FACTORY_CONTROLLER).init(address(this), "ControllerFactory");

        // 🆕 Auto-register this factory inside PlatformUniverse (no manual post-deploy tx required)
        // Requires: tx.origin is Platform Admin and this contract is registered as SmartContract.
        IPlatformUniverse(platformUniverse).setControllerFactory(address(this));
    }

    function setPlatformProjectsAndModelsAddress(address a) external {
        if (!IController(FACTORY_CONTROLLER).isOfficialTripleEntityFast(KECCAK_TREASURY_ADMIN, msg.sender, KECCAK_SUPER_ADMIN, msg.sender, KECCAK_TOKEN_ADMIN, msg.sender, false)) revert NotAuthorized();
        if (a == address(0)) revert Unauthorized();
        if (IPlatformProjectsAndModels(a).PLATFORM_CONTROLLER() != FACTORY_CONTROLLER) revert InvalidControllerFromPlatformUniverse();
        platformProjectsAndModels = a;
    }

    // ========================================================================
    // STRIPPED INITCODE CACHE (Platform Treasury Admin only)
    // ========================================================================

    /**
     * @notice Cache stripped initcode (creation bytecode WITHOUT constructor args) on-chain.
     * @dev Auth: FACTORY_CONTROLLER.isPlatformAdmin(msg.sender, KECCAK_TREASURY_ADMIN)
     * @param contractTypeHash keccak256(bytes(contractTypeStringLower)) used as lookup key
     * @param strippedInitCode creation bytecode WITHOUT constructor args
     */
    function cacheStrippedInitCode(bytes32 contractTypeHash, bytes calldata strippedInitCode) external {
        if (!IController(FACTORY_CONTROLLER).isPlatformAdmin(msg.sender, KECCAK_TREASURY_ADMIN)) revert NotAuthorized();
        if (contractTypeHash == bytes32(0)) revert InvalidInitCode();
        // ✅ Allow "0x override": empty bytes means CLEAR cache for this type.
        if (strippedInitCode.length == 0) {
            _clearStrippedInitCodeInternal(contractTypeHash);
            emit StrippedInitCodeCleared(contractTypeHash, msg.sender);
            return;
        }

        // Clear existing cache first (idempotent).
        _clearStrippedInitCodeInternal(contractTypeHash);

        // Chunk and store across multiple pointers.
        uint256 totalLen = strippedInitCode.length;
        strippedInitCodeTotalLenByType[contractTypeHash] = uint32(totalLen);

        uint16 chunkCount = uint16((totalLen + _SSTORE2_CHUNK_BYTES - 1) / _SSTORE2_CHUNK_BYTES);
        if (chunkCount == 0) revert InvalidInitCode();
        strippedInitCodeChunkCountByType[contractTypeHash] = chunkCount;

        for (uint16 i = 0; i < chunkCount; i++) {
            uint256 start = uint256(i) * _SSTORE2_CHUNK_BYTES;
            uint256 end = start + _SSTORE2_CHUNK_BYTES;
            if (end > totalLen) end = totalLen;
            uint256 len = end - start;
            if (len == 0) revert InvalidInitCode();
            if (len > _SSTORE2_MAX_DATA_BYTES) revert InvalidInitCode();

            bytes memory chunk = strippedInitCode[start:end];
            address pointer = _sstore2Write(chunk);
            strippedInitCodeChunkPointerByType[contractTypeHash][i] = pointer;

            if (i == 0) {
                strippedInitCodePointerByType[contractTypeHash] = pointer; // backward compat pointer0
                emit StrippedInitCodeCached(contractTypeHash, pointer, totalLen, msg.sender);
            }
            emit StrippedInitCodeCachedChunk(contractTypeHash, i, pointer, len, msg.sender);
        }
    }

    /**
     * @notice Clear a cached stripped initcode pointer for a contractTypeHash.
     * @dev Auth: FACTORY_CONTROLLER.isPlatformAdmin(msg.sender, KECCAK_TREASURY_ADMIN)
     */
    function clearStrippedInitCode(bytes32 contractTypeHash) external {
        if (!IController(FACTORY_CONTROLLER).isPlatformAdmin(msg.sender, KECCAK_TREASURY_ADMIN)) revert NotAuthorized();
        _clearStrippedInitCodeInternal(contractTypeHash);
        emit StrippedInitCodeCleared(contractTypeHash, msg.sender);
    }

    /**
     * @notice Set the cached pointer directly (advanced/admin use).
     * @dev Auth: FACTORY_CONTROLLER.isPlatformAdmin(msg.sender, KECCAK_TREASURY_ADMIN)
     * @dev Pointer must have non-empty runtime code (>1 byte because first byte is 0x00 sentinel).
     */
    function setStrippedInitCodePointer(bytes32 contractTypeHash, address pointer) external {
        if (!IController(FACTORY_CONTROLLER).isPlatformAdmin(msg.sender, KECCAK_TREASURY_ADMIN)) revert NotAuthorized();
        if (contractTypeHash == bytes32(0)) revert InvalidInitCode();
        if (pointer == address(0)) revert InvalidInitCode();
        uint256 size;
        assembly ("memory-safe") { size := extcodesize(pointer) }
        if (size <= 1) revert InvalidInitCode();
        // Treat this as a single-chunk override.
        _clearStrippedInitCodeInternal(contractTypeHash);
        uint256 len = size - 1;
        if (len > _SSTORE2_MAX_DATA_BYTES) revert InvalidInitCode();
        strippedInitCodePointerByType[contractTypeHash] = pointer;
        strippedInitCodeChunkPointerByType[contractTypeHash][0] = pointer;
        strippedInitCodeChunkCountByType[contractTypeHash] = 1;
        strippedInitCodeTotalLenByType[contractTypeHash] = uint32(len);
        emit StrippedInitCodePointerSet(contractTypeHash, pointer, msg.sender);
    }

    function getStrippedInitCodePointer(bytes32 contractTypeHash) external view returns (address pointer) {
        return strippedInitCodePointerByType[contractTypeHash];
    }

    function getStrippedInitCodePointers(bytes32 contractTypeHash) external view returns (address[] memory pointers) {
        uint16 n = strippedInitCodeChunkCountByType[contractTypeHash];
        pointers = new address[](n);
        for (uint16 i = 0; i < n; i++) {
            pointers[i] = strippedInitCodeChunkPointerByType[contractTypeHash][i];
        }
    }

    function isStrippedInitCodeCached(bytes32 contractTypeHash) external view returns (bool) {
        return strippedInitCodeChunkCountByType[contractTypeHash] != 0;
    }


    function _clearStrippedInitCodeInternal(bytes32 contractTypeHash) internal {
        // Clear all chunk pointers for this type (loop is bounded by prior chunkCount).
        uint16 n = strippedInitCodeChunkCountByType[contractTypeHash];
        if (n != 0) {
            for (uint16 i = 0; i < n; i++) {
                strippedInitCodeChunkPointerByType[contractTypeHash][i] = address(0);
            }
        }
        strippedInitCodeChunkCountByType[contractTypeHash] = 0;
        strippedInitCodeTotalLenByType[contractTypeHash] = 0;
        strippedInitCodePointerByType[contractTypeHash] = address(0);
    }

    // Minimal SSTORE2-style write: deploy a contract whose runtime code is 0x00 || data
    function _sstore2Write(bytes memory data) internal returns (address pointer) {
        bytes memory runtime = abi.encodePacked(hex"00", data);
        if (runtime.length == 0) revert InvalidInitCode();

        // creation code:
        // PUSH2 <len> RETURNDATASIZE DUP2 PUSH1 0x0a RETURNDATASIZE CODECOPY RETURN <runtime>
        bytes memory init = abi.encodePacked(
            hex"61",
            uint16(runtime.length),
            hex"3d81600a3d39f3",
            runtime
        );

        assembly ("memory-safe") {
            pointer := create(0, add(init, 0x20), mload(init))
        }
        if (pointer == address(0)) revert InvalidInitCode();
    }

    function _sstore2Read(address pointer) internal view returns (bytes memory data) {
        uint256 size;
        assembly ("memory-safe") { size := extcodesize(pointer) }
        // runtime has leading 0x00 byte
        if (size <= 1) revert InvalidInitCode();
        uint256 len = size - 1;
        data = new bytes(len);
        assembly ("memory-safe") {
            extcodecopy(pointer, add(data, 0x20), 1, len)
        }
    }

    /**
     * @notice MULTI-PHASE DEPLOYMENT PATTERN (Phase 1): Deploy Controller + FeeManager
     * @dev Phase 1: Controller, FeeManager only (lightest phase)
     * @dev Then: collects deploy fee, saves state with currentPhase=1
     * @dev Reverts if deployer already has an incomplete deployment for this domain
     * @param bytecodes Contract bytecodes (phase 1: controller, feeManager)
     * @param params Full deployment params
     * @param models Array of model addresses in PlatformUniverse.Deployment order (should be 13 elements):
     *               [0] controller, [1] feeManager, [2] tokenContent, [3] timeLockManager,
     *               [4] token, [5] saleManager, [6] navPoolManager, [7] liquidityProvider,
     *               [8] distributionManager, [9] projectRevenueTreasury, [10] restrictedSaleManager,
     *               [11] teamManager, [12] releaseManager (pass address(0) for unused slots)
     * @return controller The deployed Controller address
     */
    function deployAll1(
        Bytecodes calldata bytecodes,
        DeploymentParams calldata params,
        address[] calldata models,
        bool doNotCharge
    ) external returns (address controller) {
        if (doNotCharge) {
            if (!IController(FACTORY_CONTROLLER).isPlatformAdmin(msg.sender, KECCAK_TREASURY_ADMIN)) revert NotAuthorized();
        }
        // Universal project number (for display/audit in PlatformUniverse.Deployment)
        projectDeploymentNumberIndex++;
        uint256 projectDeploymentNumber = projectDeploymentNumberIndex;
        
        string memory finalDomain = bytes(params.domain).length > 0 ? params.domain : BASE_DOMAIN;

        // Deterministic per-deployer counter for CREATE2 salts (avoids global race; safe for USDT pre-approve)
        // Convenience list used for CREATE2 salt determinism only (NOT a migration index).
        // We intentionally do not "migrate" controllersByUser, because msg.sender would be TokenAdmin.
        // If migration ever needs it, it must infer a real deployer (e.g., TreasuryAdmin/Super from the Controller)
        // or read PlatformUniverse.getDeployerByController(controller).
        uint256 deployerProjectCount = controllersByUser[msg.sender].length + 1;

        // ✅ Guard: Check PlatformUniverse for incomplete deployment (source of truth)
        // expectedPhase=0 means: return any incomplete OR empty struct (currentPhase=0) if none exists
        IPlatformUniverse.Deployment memory existingDep = IPlatformUniverse(PLATFORM_UNIVERSE).getIncompleteDeployment(
            msg.sender,
            finalDomain,
            params.subdomain,
            0  // expectedPhase = 0 (returns empty struct with currentPhase=0 if no deployment)
        );
        
        // Block new phase 1 if incomplete deployment exists (currentPhase > 0 means deployment exists)
        if (existingDep.currentPhase > 0 && !existingDep.isComplete) {
            revert IncompleteDeploymentExists();
        }

        IFeeManager.EntityFeesWithNames[] memory validatedFees = IPlatformUniverse(PLATFORM_UNIVERSE).validateFeesMatchTemplate(
            params.feeManagerParams.platformTreasuryConfigs, params.domain, params.subdomain
        );

        // Deploy phase 1 contracts (Controller + FeeManager only)
        DeploymentResult memory result;

        result.controller = _deployController(bytecodes.controller, params.controllerParams, deployerProjectCount);

        bool opened = IController(result.controller).openInit();
        if (!opened) revert InitWindowAlreadyOpen();
        IController(result.controller).init(address(this), "ControllerFactory");

        result.feeManager = _deployFeeManager(bytecodes.feeManager, result, validatedFees, deployerProjectCount);

        IController(result.controller).closeInit();

        // Collect deploy fee (skipped when platformAdmin waives via doNotCharge)
        if (!doNotCharge) {
            (IFeeManager.CalculatedEntityAmount[] memory deployFees, uint256 totalDeployFee) = 
                IFeeManager(result.feeManager).calculateChainedAmounts(
                    0,          // totalVal = 0 (flat fee)
                    10000,      // maxPct = 100%
                    KECCAK_FEE_DEPLOY
                );
            
            if (totalDeployFee > 0) {
                if (params.permitDeadline != 0) {
                    IERC20Permit(params.tokenParams.stableCoinAddress).permit(
                        tx.origin,
                        result.feeManager,
                        totalDeployFee,
                        params.permitDeadline,
                        params.permitV,
                        params.permitR,
                        params.permitS
                    );
                }
                
                IFeeManager(result.feeManager).distributeFees(deployFees, tx.origin, params.tokenParams.stableCoinAddress);
                
                emit DeployFeeCollected(tx.origin, result.feeManager, totalDeployFee);
            }
        }

        IPlatformUniverse(PLATFORM_UNIVERSE).savePhase1Deployment(
            msg.sender,
            finalDomain,
            params.subdomain,
            params.controllerParams.projectName,
            result.controller,
            result.feeManager,
            projectDeploymentNumber,
            deployerProjectCount
        );

        controllersByUser[msg.sender].push(result.controller);
        // controllerByDeployerSubdomainChain[msg.sender][params.subdomain][block.chainid] = result.controller;

        // Track project controller once (enumeration helper)
        if (!_isProjectControllerTracked[result.controller]) {
            _isProjectControllerTracked[result.controller] = true;
            allProjectControllers.push(result.controller);
        }

        // 🆕 Save all model addresses (pass empty array [] in phases 2-6 if models unchanged)
        _appendModels(result.controller, models);

        return result.controller;
    }

    /**
     * @notice MULTI-PHASE DEPLOYMENT PATTERN (Phase 2): Deploy TokenContent + TimeLock
     * @dev Phase 2: TokenContent, TimeLock
     * @dev Retrieves controller/feeManager from phase 1, opens init window, deploys, saves phase 2 state
     * @param bytecodes Contract bytecodes (phase 2: tokenContent, timeLock)
     * @param params Params needed for tokenContent and timeLock
     * @param models Optional array of model addresses to append (pass empty array [] if none)
     * @return controller The Controller address (from phase 1)
     */
    function deployAll2(
        Bytecodes calldata bytecodes,
        DeploymentParams calldata params,
        address[] calldata models
    ) external returns (address controller) {
        string memory dom = bytes(params.domain).length > 0 ? params.domain : BASE_DOMAIN;
        IPlatformUniverse.Deployment memory savedDep = IPlatformUniverse(PLATFORM_UNIVERSE).getIncompleteDeployment(
            msg.sender,
            dom,
            params.subdomain,
            1  // expectedPhase = 1 (must be at phase 1 to deploy phase 2)
        );

        _reopenInitWindow(savedDep.controller);

        DeploymentResult memory result;
        result.controller = savedDep.controller;
        result.feeManager = savedDep.feeManager;

        // 🔑 CRITICAL: Use deployerProjectCount from Phase 1 for CREATE2 salts in all subsequent phases
        uint256 projectDeploymentNumber = savedDep.deployerProjectCount;

        // Deploy phase 2 contracts
        result.tokenContent = _deployTokenContent(bytecodes.tokenContent, result, params.tokenContentParams, projectDeploymentNumber);
        result.timeLockManager = _deployTimeLock(bytecodes.timeLock, result, params.timeLockParams, projectDeploymentNumber);

        // 🆕 Set RegisteredSafeFactory in TimeLock if needed
        if (REGISTERED_SAFE_FACTORY != address(0)) {
            try IIssueTokenTimeLock(result.timeLockManager).setRegisteredSafeFactory(REGISTERED_SAFE_FACTORY) {} catch {}
        }

        IController(result.controller).closeInit();

        IPlatformUniverse(PLATFORM_UNIVERSE).savePhase2Deployment(
            msg.sender,
            dom,
            params.subdomain,
            result.tokenContent,
            result.timeLockManager
        );

        _appendModels(result.controller, models);

        return result.controller;
    }

    /**
     * @notice MULTI-PHASE DEPLOYMENT PATTERN (Phase 3): Deploy Token + SaleManager
     * @dev Phase 3: Token, SaleManager
     * @dev Retrieves addresses from phase 1-2, opens init window, deploys, saves phase 3 state
     * @param bytecodes Contract bytecodes (phase 3: token, saleManager)
     * @param params Params needed for token and saleManager
     * @param models Optional array of model addresses to append (pass empty array [] if none)
     * @return controller The Controller address (from phase 1)
     */
    function deployAll3(
        Bytecodes calldata bytecodes,
        DeploymentParams calldata params,
        address[] calldata models
    ) external returns (address controller) {
        string memory dom = bytes(params.domain).length > 0 ? params.domain : BASE_DOMAIN;
        IPlatformUniverse.Deployment memory savedDep = IPlatformUniverse(PLATFORM_UNIVERSE).getIncompleteDeployment(
            msg.sender,
            dom,
            params.subdomain,
            2  // expectedPhase = 2 (must be at phase 2 to deploy phase 3)
        );

        _reopenInitWindow(savedDep.controller);

        DeploymentResult memory result;
        result.controller = savedDep.controller;
        result.feeManager = savedDep.feeManager;
        result.tokenContent = savedDep.tokenContent;
        result.timeLockManager = savedDep.timeLockManager;

        // 🔑 CRITICAL: Use deployerProjectCount from Phase 1 for CREATE2 salts in all subsequent phases
        uint256 projectDeploymentNumber = savedDep.deployerProjectCount;

        result.token = _deployToken(bytecodes.token, result, params.tokenParams, projectDeploymentNumber);
        result.saleManager = _deploySaleManager(bytecodes.saleManager, result, params.saleManagerParams, projectDeploymentNumber);

        IController(result.controller).closeInit();

        IPlatformUniverse(PLATFORM_UNIVERSE).savePhase3Deployment(
            msg.sender,
            dom,
            params.subdomain,
            result.token,
            result.saleManager
        );

        _appendModels(result.controller, models);

        return result.controller;
    }

    /**
     * @notice MULTI-PHASE DEPLOYMENT PATTERN (Phase 4): NavPoolManager + LiquidityProvider
     * @dev Phase 4: NavPoolManager + LiquidityProvider only
     * @dev Handles pool creation if needed
     * @param bytecodes Contract bytecodes (phase 4)
     * @param params Params needed for phase 4
     * @param models Optional array of model addresses to append (pass empty array [] if none)
     * @return controller The Controller address (from phase 1)
     */
    function deployAll4(
        Bytecodes calldata bytecodes,
        DeploymentParams calldata params,
        address[] calldata models
    ) external returns (address controller) {
        string memory dom = bytes(params.domain).length > 0 ? params.domain : BASE_DOMAIN;
        IPlatformUniverse.Deployment memory savedDep = IPlatformUniverse(PLATFORM_UNIVERSE).getIncompleteDeployment(
            msg.sender,
            dom,
            params.subdomain,
            3  // expectedPhase = 3 (must be at phase 3 to deploy phase 4)
        );

        _reopenInitWindow(savedDep.controller);

        DeploymentResult memory result;
        result.controller = savedDep.controller;
        result.feeManager = savedDep.feeManager;
        result.token = savedDep.token;
        result.saleManager = savedDep.saleManager;
        
        // 🔑 CRITICAL: Use deployerProjectCount from Phase 1 for CREATE2 salts in all subsequent phases
        uint256 projectDeploymentNumber = savedDep.deployerProjectCount;

        // Phase 4 deploys: NavPoolManager + LiquidityProvider (+ pool creation if needed)
        result.navPoolManager = _deployNavPoolManager(bytecodes.navPoolManager, result, params.navPoolParams, projectDeploymentNumber);

        if (params.liquidityParams.liquidityPoolAddress != address(0)) {
            result.liquidityPool = params.liquidityParams.liquidityPoolAddress;
        } else if (params.liquidityParams.createPoolIfZero && params.liquidityParams.trustedFactory != address(0)) {
            result.liquidityPool = _createPool(
                result.token,
                params.tokenParams.stableCoinAddress,
                params.liquidityParams.trustedFactory
            );
            if (result.liquidityPool == address(0)) revert PoolCreationReturnedZero();
        } else {
            result.liquidityPool = address(0);
        }

        if (result.liquidityPool != address(0)) {
            _validatePool(
                result.liquidityPool,
                result.token,
                params.tokenParams.stableCoinAddress,
                params.liquidityParams.trustedFactory
            );
        }

        if (!IController(result.controller).isOfficialDoubleEntityFast(
                KECCAK_SMART_CONTRACT, result.token,
                KECCAK_SMART_CONTRACT, result.saleManager,
                true
            )) revert TokenSaleNotOfficial();

        address tokenStableCoin = IIssueToken(result.token).stableCoinAddress();
        if (tokenStableCoin != params.tokenParams.stableCoinAddress) revert StablecoinMismatch();

        if (params.liquidityParams.trustedFactory == address(0)) revert FactoryAddressZero();
        if (bytes(params.liquidityParams.factoryIdentifier).length == 0) revert FactoryIdentifierEmpty();

        result.liquidityProvider = _deployLiquidityProviderContract(
            bytecodes.liquidityProvider,
            result,
            params.liquidityParams.trustedFactory,
            params.liquidityParams.factoryIdentifier,
            projectDeploymentNumber
        );

        if (!IController(result.controller).isOfficialEntityFast(KECCAK_SMART_CONTRACT, result.liquidityProvider)) {
            revert LiquidityProviderNotRegistered();
        }

        IController(result.controller).closeInit();

        IPlatformUniverse(PLATFORM_UNIVERSE).savePhase4Deployment(
            msg.sender,
            dom,
            params.subdomain,
            result.navPoolManager,
            result.liquidityProvider
        );

        _appendModels(result.controller, models);

        return result.controller;
    }

    /**
     * @notice MULTI-PHASE DEPLOYMENT PATTERN (Phase 5): DistributionManager + ProjectRevenueTreasury
     * @dev Phase 5: DistributionManager + ProjectRevenueTreasury
     * @param bytecodes Contract bytecodes (phase 5)
     * @param params Params needed for phase 5
     * @param models Optional array of model addresses to append (pass empty array [] if none)
     * @return controller The Controller address (from phase 1)
     */
    function deployAll5(
        Bytecodes calldata bytecodes,
        DeploymentParams calldata params,
        address[] calldata models
    ) external returns (address controller) {
        if (params.treasuryParams.projectTransferBaseFeeAmount == 0) revert TransferFeeRequired();

        string memory dom = bytes(params.domain).length > 0 ? params.domain : BASE_DOMAIN;
        IPlatformUniverse.Deployment memory savedDep = IPlatformUniverse(PLATFORM_UNIVERSE).getIncompleteDeployment(
            msg.sender,
            dom,
            params.subdomain,
            4  // expectedPhase = 4 (must be at phase 4 to deploy phase 5)
        );

        _reopenInitWindow(savedDep.controller);

        DeploymentResult memory result;
        result.controller = savedDep.controller;
        result.feeManager = savedDep.feeManager;
        result.token = savedDep.token;
        result.saleManager = savedDep.saleManager;
        
        // 🔑 CRITICAL: Use deployerProjectCount from Phase 1 for CREATE2 salts in all subsequent phases
        uint256 projectDeploymentNumber = savedDep.deployerProjectCount;

        result.distributionManager = _deployDistributionManager(bytecodes.distributionManager, result, params.distributionParams, projectDeploymentNumber);

        result.projectRevenueTreasury = _deployProjectRevenueTreasury(
            bytecodes.projectRevenueTreasury,
            result,
            params.treasuryParams,
            projectDeploymentNumber
        );

        IController(result.controller).closeInit();

        IPlatformUniverse(PLATFORM_UNIVERSE).savePhase5Deployment(
            msg.sender,
            dom,
            params.subdomain,
            result.distributionManager,
            result.projectRevenueTreasury
        );

        _appendModels(result.controller, models);

        return result.controller;
    }

    /**
     * @notice MULTI-PHASE DEPLOYMENT PATTERN (Phase 6): RestrictedSaleManager + TeamManager
     * @dev Phase 6 was split from a 3-contract step into Phase 6 + Phase 7 because the original
     *      deployAll6() ran out of gas at large block-gas limits when handling all three
     *      sub-contracts (RestrictedSaleManager, TeamManager, ReleaseManager) in one tx.
     * @dev ReleaseManager and final-deployment bookkeeping moved to deployAll7().
     * @param bytecodes Contract bytecodes (phase 6 uses: restrictedSaleManager, teamManager)
     * @param params Restricted sale params needed for phase 6
     * @param models Model addresses to append for THIS phase's contracts (restrictedSale,
     *               teamManager). Pass empty array [] if none.
     * @return controller The Controller address (from phase 1)
     */
    function deployAll6(
        Bytecodes calldata bytecodes,
        DeploymentParams calldata params,
        address[] calldata models
    ) external returns (address controller) {
        string memory dom = bytes(params.domain).length > 0 ? params.domain : BASE_DOMAIN;
        IPlatformUniverse.Deployment memory savedDep = IPlatformUniverse(PLATFORM_UNIVERSE).getIncompleteDeployment(
            msg.sender,
            dom,
            params.subdomain,
            5  // expectedPhase = 5 (must be at phase 5 to deploy phase 6)
        );

        _reopenInitWindow(savedDep.controller);

        DeploymentResult memory result;
        result.controller = savedDep.controller;
        result.feeManager = savedDep.feeManager;
        result.token = savedDep.token;

        // 🔑 Use deployerProjectCount from Phase 1 for CREATE2 salts in all subsequent phases
        uint256 projectDeploymentNumber = savedDep.deployerProjectCount;

        result.restrictedSaleManager = _deployRestrictedSaleManager(bytecodes.restrictedSaleManager, result, params.restrictedSaleParams, projectDeploymentNumber);
        result.teamManager = _deployTeamManager(bytecodes.teamManager, result, projectDeploymentNumber);

        IController(result.controller).closeInit();

        IPlatformUniverse(PLATFORM_UNIVERSE).savePhase6Deployment(
            msg.sender,
            dom,
            params.subdomain,
            result.restrictedSaleManager,
            result.teamManager
        );

        _appendModels(result.controller, models);

        return result.controller;
    }

    /**
     * @notice MULTI-PHASE DEPLOYMENT PATTERN (Phase 7): ReleaseManager + finalization
     * @dev Final phase: deploys ExecutiveReleaseManager, closes init, completes the deployment
     *      in PlatformUniverse, appends optional models, and emits DeploymentComplete.
     * @dev Split out of deployAll6 to stay within block gas limits (see deployAll6 note).
     * @param bytecodes Contract bytecodes (phase 7 uses: releaseManager)
     * @param params Domain/subdomain params (only domain + subdomain are read here)
     * @param models Model addresses to append for THIS phase's contracts (releaseManager).
     *               Pass empty array [] if none.
     * @return controller The Controller address (from phase 1)
     */
    function deployAll7(
        Bytecodes calldata bytecodes,
        DeploymentParams calldata params,
        address[] calldata models
    ) external returns (address controller) {
        string memory dom = bytes(params.domain).length > 0 ? params.domain : BASE_DOMAIN;
        IPlatformUniverse.Deployment memory savedDep = IPlatformUniverse(PLATFORM_UNIVERSE).getIncompleteDeployment(
            msg.sender,
            dom,
            params.subdomain,
            6  // expectedPhase = 6 (must be at phase 6 to deploy phase 7)
        );

        _reopenInitWindow(savedDep.controller);

        DeploymentResult memory result;
        result.controller = savedDep.controller;
        result.feeManager = savedDep.feeManager;
        result.token = savedDep.token;

        result.releaseManager = _deployReleaseManager(bytecodes.releaseManager, result, savedDep.deployerProjectCount);

        // Phase 7 (after ReleaseManager): deploy singleton BatchTransferAndExtrasManager.
        // BTM ctor takes only (controller); it self-resolves FeeManager / IssueToken /
        // IssueTokenSaleManager from the project Controller's SmartContract registry.
        result.batchTransferAndExtrasManager = _deployBatchTransferAndExtrasManager(
            bytecodes.batchTransferAndExtrasManager, result, savedDep.deployerProjectCount
        );

        IController(result.controller).closeInit();

        IPlatformUniverse(PLATFORM_UNIVERSE).completePhase7Deployment(
            msg.sender,
            dom,
            params.subdomain,
            result.releaseManager,
            result.batchTransferAndExtrasManager
        );

        _appendModels(result.controller, models);

        totalDeployments++;

        emit DeploymentComplete(msg.sender, result.controller, block.timestamp);

        return result.controller;
    }

    // ===== LEGACY deployAll() REMOVED =====
    // Single-transaction deployment is impossible on Ethereum mainnet (exceeds 30M gas block limit)
    // Use two-phase deployment: deployAll1() + deployAll2()

    function _reopenInitWindow(address controller) private {
        IController(controller).openInit();
        IController(controller).init(address(this), "ControllerFactory");
    }

    /**
     * @notice Internal helper to append model addresses to controller's model array
     * @param controller The controller address
     * @param models Array of model addresses to append (pass empty array [] if none)
     */
    function _appendModels(address controller, address[] calldata models) internal {
        for (uint256 i = 0; i < models.length; i++) {
            modelAddressesByController[controller].push(models[i]);
        }
    }

    /// @notice Override (replace) model lists for one or more controllers (batch migration).
    /// @dev Auth: Platform TokenAdmin only. controllers[i] pairs with models[i].
    function overrideProjectModelsSnapshot(address[] calldata controllers, address[][] calldata models) external {
        if (!IController(FACTORY_CONTROLLER).isPlatformAdmin(msg.sender, KECCAK_TOKEN_ADMIN)) revert NotAuthorized();
        if (controllers.length != models.length) revert Unauthorized();
        for (uint256 c = 0; c < controllers.length; c++) {
            address ctrl = controllers[c];
            if (!_isProjectControllerTracked[ctrl]) {
                _isProjectControllerTracked[ctrl] = true;
                allProjectControllers.push(ctrl);
            }
            delete modelAddressesByController[ctrl];
            address[] calldata m = models[c];
            for (uint256 i = 0; i < m.length; i++) {
                modelAddressesByController[ctrl].push(m[i]);
            }
        }
    }

    /// @notice Enumerate project controllers. If count == 0, returns ALL from start.
    /// @dev Two distinct paths:
    ///      - start  > len  -> REVERT (programmer/UI error: asking past the end of the array).
    ///      - start <= len  -> CLIP count to (len - start) and return that many entries.
    ///        start == len returns an empty array (legitimate end-of-list signal).
    function getAllProjectControllers(uint256 start, uint256 count) external view returns (address[] memory out) {
        uint256 len = allProjectControllers.length;
        if (start > len) revert Unauthorized();
        uint256 remaining = len - start;
        if (count == 0 || count > remaining) count = remaining;
        out = new address[](count);
        for (uint256 i = 0; i < count; i++) out[i] = allProjectControllers[start + i];
    }

    /// @notice Convenience getter for UI CREATE2 salt determinism (NOT migrated).
    /// @dev Used to predict deployerProjectCount = getDeployerControllerCount(deployer) + 1 for pre-approve flows (e.g., USDT).
    function getDeployerControllerCount(address deployer) external view returns (uint256) {
        return controllersByUser[deployer].length;
    }

    function _deployController(
        bytes calldata bytecode,
        ControllerParams calldata params,
        uint256 projectDeploymentNumber
    ) private returns (address controller) {
        bytes memory ctorArgs = abi.encode(
            params.projectSuperAddress,
            FACTORY_CONTROLLER,  // platformControllerAddress (platform controller)
            params.projectSuperName,
            params.projectSuperId,
            params.projectName,
            params.projectId
        );
        
        controller = _deployStreamed(
            bytecode,
            keccak256(bytes("controller")),
            ctorArgs,
            "Controller",
            projectDeploymentNumber
        );
    }

    // ===== LEGACY _findFeeManagerInController() / _syncFeeTypesFromPlatform() COMMENTED OUT =====
    // Both are private and were only invoked from a now-commented call site in _deployFeeManager.
    // Kept here (commented) so they can be revived if/when platform-fee-type sync is re-enabled
    // (would require allowing any platform SmartContract entity caller — see TODO in _deployFeeManager).
    // Removed from source so we don't rely on the Solidity optimizer stripping dead private code.
    //
    // function _findFeeManagerInController(address controllerAddr) private view returns (address) {
    //     IController.OfficialEntityStruct[] memory contracts = IController(controllerAddr).getAllOfficialEntities("SmartContract", true);
    //     for (uint256 i = 0; i < contracts.length; i++) {
    //         address contractAddr = contracts[i].pubAddress;
    //         if (!contracts[i].active) continue;
    //         try IFeeManager(contractAddr).currentMaxFeeType() returns (uint8) {
    //             return contractAddr;
    //         } catch {}
    //     }
    //     return address(0);
    // }
    //
    // function _syncFeeTypesFromPlatform(address platformController, address newFeeManager) private {
    //     address platformCtrlCheck = IController(platformController).PLATFORM_CONTROLLER();
    //     require(platformCtrlCheck == platformController, "ControllerFactory: Invalid platform controller - not self-referential");
    //     address platformFeeManager = _findFeeManagerInController(platformController);
    //     require(platformFeeManager != address(0), "ControllerFactory: No FeeManager found in platform controller");
    //     uint8 newFeeManagerMaxType = IFeeManager(newFeeManager).currentMaxFeeType();
    //     string[] memory platformLabels = IFeeManager(platformFeeManager).getAllFeeTypeLabels();
    //     for (uint8 i = 0; i < platformLabels.length; i++) {
    //         if (bytes(platformLabels[i]).length > 0) {
    //             uint8 feeType = i + 1;
    //             if (feeType > newFeeManagerMaxType) {
    //                 IFeeManager(newFeeManager).addFeeType(platformLabels[i]);
    //             }
    //         }
    //     }
    // }

    function _deployFeeManager(
        bytes calldata bytecode,
        DeploymentResult memory result,
        IFeeManager.EntityFeesWithNames[] memory platformTreasuryConfigs,
        uint256 projectDeploymentNumber
    ) private returns (address feeManager) {
        bytes memory ctorArgs = abi.encode(result.controller, platformTreasuryConfigs);
        
        feeManager = _deployStreamed(
            bytecode,
            keccak256(bytes("feemanager")),
            ctorArgs,
            "FeeManager",
            projectDeploymentNumber
        );
        // FeeManager self-registers via its constructor calling controller.init()
        // FeeManager also processes platformTreasuryConfigs to set up default fee hierarchy
        //
        // NOTE: Fee-type sync from the platform FeeManager (_syncFeeTypesFromPlatform)
        // is intentionally disabled — new fee types require a token-system upgrade
        // anyway, and platform-only caller restrictions would make the call revert
        // for project deployers. The lookup + dead branch were removed to save bytecode.
        // See commented _syncFeeTypesFromPlatform below if it ever needs to be revived.
    }

    function _deployProjectRevenueTreasury(
        bytes calldata bytecode,
        DeploymentResult memory result,
        ProjectRevenueTreasuryParams calldata params,
        uint256 projectDeploymentNumber
    ) private returns (address treasury) {
        // ProjectRevenueTreasury constructor:
        // (controller, feeManager, token, saleManager, liquidityProvider,
        //  distributionManager, navPoolManager, liquidityPercentageBps,
        //  distributionPercentageBps, navPoolPercentageBps, projectTransferBaseFeeAmount, initialDisburseThreshold)
        bytes memory ctorArgs = abi.encode(
            result.controller,
            result.feeManager,
            result.token,
            result.saleManager,
            result.liquidityProvider,
            result.distributionManager,
            result.navPoolManager,
            params.liquidityPercentageBps,
            params.distributionPercentageBps,
            params.navPoolPercentageBps,
            params.projectTransferBaseFeeAmount,
            params.initialDisburseThreshold
        );
        
        treasury = _deployStreamed(
            bytecode,
            keccak256(bytes("projectrevenuetreasury")),
            ctorArgs,
            "ProjectRevenueTreasury",
            projectDeploymentNumber
        );
        // NOTE: ProjectRevenueTreasury self-registers via its constructor,
    }

    function _deployNavPoolManager(
        bytes calldata bytecode,
        DeploymentResult memory result,
        NavPoolManagerParams calldata params,
        uint256 projectDeploymentNumber
    ) private returns (address navPool) {
        // NavPoolManager constructor:
        // (controller, feeManager, issueTokenAddress, initialOnDays, initialOffDays)
        // NOTE: counterAsset is auto-retrieved from token.stableCoinAddress()
        // NOTE: initialNavAdmin is auto-set to first TreasuryAdmin from Controller (if any exists)
        bytes memory ctorArgs = abi.encode(
            result.controller,
            result.feeManager,
            result.token,
            params.initialOnDays,
            params.initialOffDays
        );
        
        navPool = _deployStreamed(
            bytecode,
            keccak256(bytes("navpoolmanager")),
            ctorArgs,
            "NavPoolManager",
            projectDeploymentNumber
        );
    }

    function _deployDistributionManager(
        bytes calldata bytecode,
        DeploymentResult memory result,
        DistributionManagerParams calldata params,
        uint256 projectDeploymentNumber
    ) private returns (address distributionMgr) {
        // IssueTokenDistributionManager constructor (v43106):
        // (controller, feeManager, issueTokenAddress, saleManager,
        //  initialAutoDistributeThreshold, distributionSupplyBasis)
        // saleManager is the Phase-3 deployment, already in result.saleManager
        // (savedDep.saleManager → result.saleManager in deployAll5). DM binds it
        // immutably and uses it for the v43106 referrer-expansion self-service
        // flow (and any future DM-driven SM-side helpers).
        bytes memory ctorArgs = abi.encode(
            result.controller,
            result.feeManager,
            result.token,
            result.saleManager,
            params.initialAutoDistributeThreshold,
            params.distributionSupplyBasis
        );
        
        distributionMgr = _deployStreamed(
            bytecode,
            keccak256(bytes("distributionmanager")),
            ctorArgs,
            "IssueTokenDistributionManager",
            projectDeploymentNumber
        );
    }

    function _deployTokenContent(
        bytes calldata bytecode,
        DeploymentResult memory result,
        TokenContentParams calldata params,
        uint256 projectDeploymentNumber
    ) private returns (address content) {
        bytes memory ctorArgs = abi.encode(
            result.controller,
            result.feeManager,
            params.tokenDocBaseUrl,
            params.tokenDocHash,
            params.tokenDocDescription
        );
        
        content = _deployStreamed(
            bytecode,
            keccak256(bytes("tokencontent")),
            ctorArgs,
            "IssueTokenContentManager",
            projectDeploymentNumber
        );
        // NOTE: ContentManager does NOT need to be registered as SmartContract - no validation checks its registration
    }

    function _deployTimeLock(
        bytes calldata bytecode,
        DeploymentResult memory result,
        TimeLockParams calldata params,
        uint256 projectDeploymentNumber
    ) private returns (address timeLock) {
        // IssueTokenTimeLock constructor:
        // (controller, initialLockDurationMonths, minPriceUSD, minPriceLockMonths, maxHolders)
        bytes memory ctorArgs = abi.encode(
            result.controller,
            params.initialDurationMonths,
            params.minPriceUSD,
            params.minPriceLockMonths,
            params.maxHolders
        );
        
        timeLock = _deployStreamed(
            bytecode,
            keccak256(bytes("tokentimelock")),
            ctorArgs,
            "IssueTokenTimeLock",
            projectDeploymentNumber
        );
        // NOTE: TimeLock does NOT need to be registered as SmartContract - no validation checks its registration
    }

    function _deployToken(
        bytes calldata bytecode,
        DeploymentResult memory result,
        TokenParams calldata params,
        uint256 projectDeploymentNumber
    ) private returns (address token) {
        bytes memory ctorArgs = abi.encode(
            result.controller,
            params.initialAdmin,
            params.tokenName,
            params.tokenSymbol,
            params.tokenDescription,
            params.initialMaxSupply,
            params.decimals,
            result.tokenContent,
            result.timeLockManager,
            result.feeManager,
            params.stableCoinAddress
        );
        
        token = _deployStreamed(
            bytecode,
            keccak256(bytes("token")),
            ctorArgs,
            "IssueToken",
            projectDeploymentNumber
        );
    }

    function _deploySaleManager(
        bytes calldata bytecode,
        DeploymentResult memory result,
        SaleManagerParams calldata params,
        uint256 projectDeploymentNumber
    ) private returns (address manager) {
        // IssueTokenSaleManager v43105 constructor:
        // (controller, issueTokenAddress, purchasePriceInUSD, ethUsdPriceFeed,
        //  usdtUsdPriceFeed, stablecoinUsdPriceFeed, usdtAddress, feeManager)
        // v43105: usdcAddress argument removed; USDC support is now opt-in via
        // SaleManager.addPaymentToken() post-deployment.
        bytes memory ctorArgs = abi.encode(
            result.controller,
            result.token,
            params.purchasePriceInUSD,
            params.ethUsdPriceFeed,
            params.usdtUsdPriceFeed,
            params.stablecoinUsdPriceFeed,
            params.usdtAddress,
            result.feeManager
        );
        
        manager = _deployStreamed(
            bytecode,
            keccak256(bytes("tokensale")),
            ctorArgs,
            "IssueTokenSaleManager",
            projectDeploymentNumber
        );
    }

    function _deployLiquidityProviderContract(
        bytes calldata bytecode,
        DeploymentResult memory result,
        address trustedFactory,
        string memory factoryIdentifier,
        uint256 projectDeploymentNumber
    ) private returns (address provider) {
        // LiquidityProvider constructor:
        // (controller, trustedFactory, factoryIdentifier, issueToken, salesManager, primaryLiquidityPool)
        bytes memory ctorArgs = abi.encode(
            result.controller,
            trustedFactory,
            factoryIdentifier,
            result.token,
            result.saleManager,
            result.liquidityPool
        );
        
        provider = _deployStreamed(
            bytecode,
            keccak256(bytes("liquidityprovider")),
            ctorArgs,
            "LiquidityProvider",
            projectDeploymentNumber
        );
        // NOTE: LiquidityProvider self-registers via its constructor
    }

    function _deployRestrictedSaleManager(
        bytes calldata bytecode,
        DeploymentResult memory result,
        RestrictedSaleManagerParams calldata params,
        uint256 projectDeploymentNumber
    ) private returns (address manager) {
        bytes memory ctorArgs = abi.encode(
            result.controller,
            result.feeManager,
            result.token,
            params.usdcAddress,
            params.usdcUsdPriceFeed,
            params.minSalePriceUSD,
            params.minHoldTime
        );
        
        manager = _deployStreamed(
            bytecode,
            keccak256(bytes("restrictedsalemanager")),
            ctorArgs,
            "RestrictedSaleManager",
            projectDeploymentNumber
        );
    }

    function _deployTeamManager(
        bytes calldata bytecode,
        DeploymentResult memory result,
        uint256 projectDeploymentNumber
    ) private returns (address manager) {
        bytes memory ctorArgs = abi.encode(result.controller, result.token);
        
        manager = _deployStreamed(
            bytecode,
            keccak256(bytes("teammanager")),
            ctorArgs,
            "IssueTokenTeamManager",
            projectDeploymentNumber
        );
    }

    function _deployReleaseManager(
        bytes calldata bytecode,
        DeploymentResult memory result,
        uint256 projectDeploymentNumber
    ) private returns (address manager) {
        bytes memory ctorArgs = abi.encode(result.controller, result.feeManager, result.token);
        
        manager = _deployStreamed(
            bytecode,
            keccak256(bytes("releasemanager")),
            ctorArgs,
            "ExecutiveReleaseManager",
            projectDeploymentNumber
        );
    }

    /// @dev Deploy singleton BatchTransferAndExtrasManager in phase 7 (after ReleaseManager).
    ///      BTM ctor takes only (controller) — it self-resolves FeeManager / IssueToken /
    ///      IssueTokenSaleManager from the project Controller's SmartContract registry.
    function _deployBatchTransferAndExtrasManager(
        bytes calldata bytecode,
        DeploymentResult memory result,
        uint256 projectDeploymentNumber
    ) private returns (address btm) {
        bytes memory ctorArgs = abi.encode(result.controller);

        btm = _deployStreamed(
            bytecode,
            keccak256(bytes("batchtransfermanager")),
            ctorArgs,
            "BatchTransferAndExtrasManager",
            projectDeploymentNumber
        );
    }

    // ===== LEGACY _registerDeployment() REMOVED =====
    // Single-phase deployment registration is no longer used.
    // Two-phase deployment uses PlatformUniverse as the single source of truth:
    // - Phase 1: PlatformUniverse.savePhase1Deployment()
    // - Phase 2: PlatformUniverse.completePhase2Deployment()
    // This eliminates data duplication and ensures consistent state.

    /**
     * @notice Create liquidity pool via DEX factory and register it
     * @param controller Controller address
     * @param token IssueToken address
     * @param primaryStablecoin Stablecoin address for pairing
     * @param dexFactory DEX factory address
     * @param tokenSymbol Token symbol for pool label
     * @return liquidityPool Created pool address
     */

    /**
     * @notice Validate liquidity pool matches expected tokens and comes from trusted factory
     * @param poolAddress Pool address to validate
     * @param issueToken Expected token address
     * @param stablecoin Expected stablecoin address
     * @param trustedFactory Expected factory address
     * @dev Performs same validation as LiquidityProvider._trySetPool (without Controller registration)
     */
    function _validatePool(
        address poolAddress,
        address issueToken,
        address stablecoin,
        address trustedFactory
    ) internal view {
        // Validate it's a real Uniswap V2 pair with standard methods
        address token0;
        address token1;
        address factory;

        // Get token0 (must not revert)
        try IUniswapV2Pair(poolAddress).token0() returns (address _token0) {
            token0 = _token0;
        } catch {
            revert PoolCreationFailed(); // Pool doesn't implement token0()
        }

        // Get token1 (must not revert)
        try IUniswapV2Pair(poolAddress).token1() returns (address _token1) {
            token1 = _token1;
        } catch {
            revert PoolCreationFailed(); // Pool doesn't implement token1()
        }

        // Get factory (must not revert)
        try IUniswapV2Pair(poolAddress).factory() returns (address _factory) {
            factory = _factory;
        } catch {
            revert PoolCreationFailed(); // Pool doesn't implement factory()
        }

        if (factory != trustedFactory) revert PoolFactoryMismatch();
        if (token0 != issueToken && token1 != issueToken) revert PoolMissingToken();
        address detectedCounterAsset = (token0 == issueToken) ? token1 : token0;
        if (detectedCounterAsset != stablecoin) revert PoolMissingStablecoin();
    }

    /**
     * @notice Create liquidity pool via DEX factory (does NOT register - LiquidityProvider does that)
     * @param token IssueToken address
     * @param primaryStablecoin Stablecoin address for pairing
     * @param dexFactory DEX factory address
     * @return liquidityPool Created pool address
     * @dev Pool will be registered by LiquidityProvider constructor via _trySetPool
     */
    function _createPool(
        address token,
        address primaryStablecoin,
        address dexFactory
    ) internal returns (address liquidityPool) {
        // `dexFactory` is mapped per-chain and passed in by the trusted
        // Deployer/UI. If wrong, the project's LP fails — trivially auditable
        // by inspecting `pool.factory()` / `pool.token0()` / `pool.token1()`.
        // The post-creation `_validatePool()` still enforces
        // `pool.factory() == trustedFactory` and the correct token pair.
        // To re-enable on-chain whitelisting, uncomment the three lines below.
        // uint256 chainId = block.chainid;
        // bool factoryApproved = _isFactoryApprovedForChain(dexFactory, chainId);
        // if (!factoryApproved) revert DexFactoryNotApproved();

        // Call external DEX factory to create pair
        (bool success, bytes memory data) = dexFactory.call(
            abi.encodeWithSignature("createPair(address,address)", token, primaryStablecoin)
        );

        // If pool already exists, createPair returns existing address (doesn't revert)
        if (!success) revert PoolCreationFailed();
        liquidityPool = abi.decode(data, (address));

        // NOTE: Pool registration is handled by LiquidityProvider constructor via _trySetPool
        // This keeps authorization simpler (LiquidityProvider is already a registered SmartContract)

        return liquidityPool;
    }

    function _getTokenSymbol(address tokenAddr) internal view returns (string memory) {
        // Try to get symbol from ERC20 token
        (bool success, bytes memory data) = tokenAddr.staticcall(
            abi.encodeWithSignature("symbol()")
        );

        if (success && data.length > 0) {
            return abi.decode(data, (string));
        }

        // Fallback for tokens without symbol()
        return "PAIR";
    }

    /**
     * @notice Check if DEX factory is approved for given chain
     * @param factoryAddress Factory address to check
     * @param chainId Chain ID to validate against
     * @return approved True if factory is in approved list for this chain
     * @dev Matches LiquidityProvider's approved factories per chain
     *
     *      ⚠️ CURRENTLY UNREACHABLE: the only call site (in `_createPool`)
     *      is commented out. `dexFactory` is mapped per-chain and passed in
     *      by the trusted Deployer/UI; a bogus value produces a non-functional
     *      LP that any auditor can detect by inspecting `pool.factory()`.
     *      Kept here for reference / re-enable.
     */
    function _isFactoryApprovedForChain(address factoryAddress, uint256 chainId) internal pure returns (bool approved) {
        // Ethereum Mainnet (Chain ID: 1)
        if (chainId == 1) {
            if (factoryAddress == 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f) return true; // Uniswap V2
            if (factoryAddress == 0x1F98431c8aD98523631AE4a59f267346ea31F984) return true; // Uniswap V3
            if (factoryAddress == 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac) return true; // SushiSwap
        }
        // BSC (Chain ID: 56)
        else if (chainId == 56) {
            if (factoryAddress == 0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73) return true; // PancakeSwap V2
            if (factoryAddress == 0xc35DADB65012eC5796536bD9864eD8773aBc74C4) return true; // SushiSwap
            if (factoryAddress == 0x858E3312ed3A876947EA49d572A7C42DE08af7EE) return true; // Biswap
        }
        // Polygon (Chain ID: 137)
        else if (chainId == 137) {
            if (factoryAddress == 0x5757371414417b8C6CAad45bAeF941aBc7d3Ab32) return true; // QuickSwap
            if (factoryAddress == 0xc35DADB65012eC5796536bD9864eD8773aBc74C4) return true; // SushiSwap
        }
        // Arbitrum (Chain ID: 42161)
        else if (chainId == 42161) {
            if (factoryAddress == 0xc35DADB65012eC5796536bD9864eD8773aBc74C4) return true; // SushiSwap
            if (factoryAddress == 0xf1D7CC64Fb4452F05c498126312eBE29f30Fbcf9) return true; // Camelot
        }

        return false;
    }



    // ===== LEGACY _deploy() COMMENTED OUT — waiting for higher gas limits =====
    // Predates multi-phase deployment; no callers remain in current factory. Kept here
    // (commented) so it can be revived if/when block gas limits permit single-tx deploys.
    // function _deploy(bytes memory bytecodeWithParams, string memory label) internal returns (address deployed) {
    //     // NOTE: CREATE2 salt must be predictable client-side so the frontend can pre-compute
    //     // the FeeManager address for EIP-2612 permit signing (spender = new FeeManager).
    //     //
    //     // We intentionally do NOT use block.timestamp here.
    //     //
    //     // Collision avoidance:
    //     // - Within a single deployAll(): labels are unique ("Controller", "FeeManager", ...)
    //     // - Across deployAll() calls: totalDeployments increments once per successful deployAll()
    //     // - Across deployers: msg.sender differs
    //     bytes32 salt = keccak256(abi.encodePacked(msg.sender, totalDeployments, label));
    //     assembly ("memory-safe") {
    //         deployed := create2(0, add(bytecodeWithParams, 0x20), mload(bytecodeWithParams), salt)
    //     }
    //     if (deployed == address(0)) revert DeploymentFailed(label);
    // }

    /**
     * @notice 🔥 GAS-OPTIMIZED STREAMED CREATE2 DEPLOYMENT
     * @dev ELIMINATES multiple memory expansions by streaming chunks directly into final buffer
     * @dev Gas savings: ~400k - 1.2M per deploy for large contracts (26KB+ initCode)
     * 
     * OLD PATTERN (expensive):
     *   _resolveInitCode() → big memory allocation #1
     *   abi.encodePacked() → big memory allocation #2
     *   CREATE2 → copy #3
     * 
     * NEW PATTERN (optimized):
     *   Compute final length
     *   Allocate once
     *   Stream chunks directly into final buffer
     *   Append params directly
     *   CREATE2 once
     * 
     * @param providedInitCode Calldata initCode (if provided, skips cache lookup)
     * @param contractTypeHash Keccak256 hash for cache lookup (if providedInitCode empty)
     * @param ctorArgs ABI-encoded constructor arguments
     * @param label Contract-name label, used for BOTH the CREATE2 salt AND the
     *              human-readable string surfaced via DebugStop / deployment errors.
     * @param projectDeploymentNumber The salt counter for this deployment (set in Phase 1, used throughout all phases)
     * @return deployed Deployed contract address
     */
    function _deployStreamed(
        bytes calldata providedInitCode,
        bytes32 contractTypeHash,
        bytes memory ctorArgs,
        string memory label,
        uint256 projectDeploymentNumber
    ) internal returns (address deployed) {

        uint256 initLen;
        uint16 chunkCount;

        // ===== Resolve Init Length =====
        if (providedInitCode.length > 0) {
            // DEBUG TOOL: If caller deliberately passes 0x01, treat it as hard-stop sentinel
            if (providedInitCode.length == 1 && providedInitCode[0] == 0x01) {
                revert DebugStop(label);
            }
            initLen = providedInitCode.length;
        } else {
            chunkCount = strippedInitCodeChunkCountByType[contractTypeHash];
            if (chunkCount == 0) revert CachedInitCodeNotFound(contractTypeHash);

            initLen = uint256(strippedInitCodeTotalLenByType[contractTypeHash]);
            if (initLen == 0) revert CachedInitCodeNotFound(contractTypeHash);

            // DEBUG TOOL: Check for 0x01 sentinel in cached initCode
            if (initLen == 1 && chunkCount == 1) {
                address pointer0 = strippedInitCodeChunkPointerByType[contractTypeHash][0];
                if (pointer0 == address(0)) revert InvalidInitCode();

                uint256 pointer0Size;
                assembly ("memory-safe") { pointer0Size := extcodesize(pointer0) }

                // Runtime is 0x00 || data, so size 2 means 1 byte of data
                if (pointer0Size == 2) {
                    bytes memory chunk0 = new bytes(1);
                    assembly ("memory-safe") {
                        extcodecopy(pointer0, add(chunk0, 0x20), 1, 1)
                    }
                    if (chunk0[0] == 0x01) {
                        revert DebugStop(label);
                    }
                }
            }
        }

        uint256 paramsLen = ctorArgs.length;
        uint256 totalLen = initLen + paramsLen;

        // ===== 🔥 YUL RAW ALLOCATION (no zero-fill, no safety overhead) =====
        uint256 codeStart;
        uint256 writePtr;

        assembly ("memory-safe") {
            let ptr := mload(0x40)
            
            // Store length like bytes[] would (for any future debugging)
            mstore(ptr, totalLen)
            
            codeStart := add(ptr, 0x20)
            writePtr := codeStart
            
            // Advance free memory pointer with 32-byte alignment
            // Formula: round up (codeStart + totalLen) to next 32-byte boundary
            // and(add(x, 31), not(31)) rounds x up to next multiple of 32
            let newFreePtr := and(add(add(codeStart, totalLen), 31), not(31))
            mstore(0x40, newFreePtr)
        }

        // ===== Copy InitCode =====
        if (providedInitCode.length > 0) {
            // Direct calldatacopy from provided bytecode
            assembly ("memory-safe") {
                calldatacopy(writePtr, providedInitCode.offset, initLen)
            }
        } else {
            // Stream chunks directly into final buffer
            uint256 offset = 0;

            for (uint16 i = 0; i < chunkCount; i++) {
                address pointer = strippedInitCodeChunkPointerByType[contractTypeHash][i];
                if (pointer == address(0)) revert InvalidInitCode();

                uint256 size;
                assembly ("memory-safe") { size := extcodesize(pointer) }

                // 🚨 CRITICAL CHECK: Pointer must have runtime code (>1 byte with sentinel)
                if (size <= 1) revert InvalidInitCode();

                uint256 chunkLen = size - 1; // skip 0x00 sentinel

                // 🚨 CRITICAL CHECK: Chunk length must not exceed remaining space
                if (offset + chunkLen > initLen) revert InvalidInitCode();

                // 🔥 DIRECT EXTCODECOPY into final buffer (no intermediate allocation)
                assembly ("memory-safe") {
                    extcodecopy(pointer, add(writePtr, offset), 1, chunkLen)
                }

                offset += chunkLen;
            }

            // 🚨 CRITICAL CHECK: Total assembled length MUST exactly match expected
            if (offset != initLen) revert InvalidInitCode();
        }

        // ===== Copy Constructor Args =====
        if (paramsLen > 0) {
            assembly ("memory-safe") {
                let dest := add(writePtr, initLen)
                let src := add(ctorArgs, 0x20)

                // Copy in 32-byte chunks for gas efficiency
                for { let i := 0 } lt(i, paramsLen) { i := add(i, 0x20) } {
                    mstore(add(dest, i), mload(add(src, i)))
                }
            }
        }

        // ===== Hash init code =====
        // Two hashes over the same assembled buffer (init + ctor args):
        //   initCodeHash = keccak256(init || ctorArgs)  — matches CREATE2 input; used for the event.
        //   pureInitHash = keccak256(init)              — matches the MODEL's audited init-code hash.
        // pureInitHash is written to PPAM for per-contract on-chain audit verification. This is the
        // single common point where the pure init code is known for both calldata-provided and
        // SSTORE2-cached deployment paths, so no further plumbing is needed in the per-slot helpers.
        bytes32 initCodeHash;
        bytes32 pureInitHash;
        assembly ("memory-safe") {
            initCodeHash := keccak256(codeStart, totalLen)
            pureInitHash := keccak256(codeStart, initLen)
        }
        emit InitCodeAssembled(label, initCodeHash, initLen, paramsLen, totalLen);

        // ===== CREATE2 (Yul-optimized - uses raw pointers) =====
        // ⚠️ CRITICAL: Use projectDeploymentNumber (not totalDeployments) for deterministic salt across all phases
        bytes32 salt = keccak256(abi.encodePacked(msg.sender, projectDeploymentNumber, label));

        assembly ("memory-safe") {
            deployed := create2(0, codeStart, totalLen, salt)
        }

        if (deployed == address(0)) revert DeploymentFailed(label);

        // Record per-contract init-code hash in PPAM for on-chain audit verification.
        // Factory-gated on PPAM side via _resolveControllerFactory(). One call per deploy.
        IPlatformProjectsAndModels(platformProjectsAndModels).recordProjectContract(deployed, pureInitHash, uint32(initLen));

        // Emit per-project-contract event so off-chain readers (ConstructorParamsReconstructor)
        // can recover the exact constructor argument values without depending on Etherscan
        // creation-tx parsing or any other off-chain indexer. The block number is recoverable
        // from PPAM.getProjectContractRecord(deployed).blockNumber, so eth_getLogs lookups
        // can be bounded to a single block.
        emit ProjectContractDeployed(deployed, pureInitHash, ctorArgs);
    }

    /**
     * @notice Validate incoming fees exactly match the stored template for this domain/subdomain
     * @dev These fees will be passed to the NEW project controller's constructor
     * @param incomingFees Fee structure from deployment request (from Ajax)
     * @param domain Domain name
     * @param subdomain Subdomain name (empty string if none)
     * @return The same fees (if validation passes)
     */
    // ========================================================================
    // FEE TEMPLATE MANAGEMENT - MOVED TO PLATFORMUNIVERSE
    // ========================================================================
    // All fee template management functions have been moved to PlatformUniverse contract
    // to keep ControllerFactory under the 24KB size limit.
    // Use PlatformUniverse.setSubdomainFeeTemplate() instead.

    // ========================================================================
    // VERIFICATION (Registry lookups - that's it!)
    // ========================================================================

    /**
     * @notice Check if a controller address is an official deployment from this factory
     * @param controllerAddress Address to check
     * @return True if controller has a deployer registered in PlatformUniverse
     * @dev Simplified method - returns only boolean. Query PlatformUniverse directly for full deployment data.
     */
    function isOfficialDeployment(address controllerAddress) external view returns (bool) {
        return IPlatformUniverse(PLATFORM_UNIVERSE).getDeployerByController(controllerAddress) != address(0);
    }

    // ===== LEGACY FUNCTIONS REMOVED =====
    // The following functions have been removed to save bytecode (~140-200 bytes):
    // - getDeployment(address) - Cannot provide full data without domain/subdomain context
    // - getUserDeployments(address) - Cannot iterate all domains efficiently
    // - getLastDeployment(address) - Cannot determine latest without domain context
    //
    // Use PlatformUniverse contract directly:
    // - PlatformUniverse.getDeployment(deployer, domain, subdomain, index)
    // - PlatformUniverse.getDeploymentCount(deployer, domain, subdomain)
    // - PlatformUniverse.getDeployerByController(controller)

    // ===== 🆕 Cross-Chain Deployment Queries =====

    // ===== getProjectDeployment REMOVED =====
    // This function has been removed to save bytecode (~80-100 bytes).
    // It was a wrapper that converted IPlatformUniverse.Deployment to the old Deployment struct.
    //
    // Use PlatformUniverse directly:
    // - PlatformUniverse.getDeployment(deployer, BASE_DOMAIN, subdomain, index)
    // - PlatformUniverse.getDeploymentCount(deployer, BASE_DOMAIN, subdomain)

    /**
     * @notice Check if a deployment exists for deployer + subdomain + chain (LEGACY - proxies to PlatformUniverse)
     * @param deployer Address of the deployer
     * @param subdomain Subdomain identifier
     * @param chainId Chain ID
     * @return exists True if deployment exists
     */
    function hasProjectDeployment(address deployer, string memory subdomain, uint256 chainId)
        external view returns (bool)
    {
        uint256 count = IPlatformUniverse(PLATFORM_UNIVERSE).getDeploymentCount(deployer, BASE_DOMAIN, subdomain);
        
        if (count == 0 || chainId != block.chainid) return false;
        
        // Check if most recent deployment is on this chain
        IPlatformUniverse.Deployment memory dep = IPlatformUniverse(PLATFORM_UNIVERSE).getDeployment(
            deployer,
            BASE_DOMAIN,
            subdomain,
            count - 1
        );
        
        return dep.chainId == chainId;
    }

    /**
     * @notice Get all deployers who have deployed for a subdomain
     * @param domain Domain name (e.g., "equitymint.org")
     * @param subdomain Subdomain identifier
     * @return deployers Array of deployer addresses
     */
    function getSubdomainDeployers(string memory domain, string memory subdomain)
        external view returns (address[] memory)
    {
        return IPlatformUniverse(PLATFORM_UNIVERSE).getDeployersForDomain(domain, subdomain, 0, 0);
    }

    /**
     * @notice Get all deployments for a subdomain across all deployers and chains (LEGACY - returns empty)
     * @param subdomain Subdomain identifier
     * @param chainIds Array of chain IDs to query
     * @return deployers Parallel array of deployer addresses (empty)
     * @return deployments Parallel array of deployment structs (empty)
     * @dev REMOVED: Use PlatformUniverse.getDeployersForDomain() + getDeployment() in a loop.
     */

    // ===== 🆕 Project Lookup by Composite Key (Name + Domain Path) =====

    // ===== getProjectByNameAndPath REMOVED =====
    // This function has been removed to save bytecode (~50-70 bytes).
    // It returned empty data because tokenInfoBaseUrl is not stored in PlatformUniverse.
    //
    // Use PlatformUniverse with domain/subdomain lookup instead.


    // ===== getDeploymentByProjectAndDeployer REMOVED =====
    // This function has been removed to save bytecode (~50-70 bytes).
    // It returned empty data because projectName-only lookup is not supported.
    //
    // Use PlatformUniverse.getDeployment(deployer, domain, subdomain, index) instead.
    

    // ===== REMOVED: getDeploymentsByDomain() =====
    // Legacy function removed - used old local storage instead of PlatformUniverse
    // For querying all deployments by domain, use off-chain indexing (events/subgraph)
    // Individual deployer's deployments can be queried via PlatformUniverse.getDeployment()

    /**
     * @notice Get all deployments across ALL subdomains for a given domain (LEGACY - use PlatformUniverse)
     * @param domain Domain name (e.g., "equitymint.org")
     * @param chainId Chain ID (0 for current chain)
     * @return controllers Array of controller addresses (empty)
     * @return subdomains Array of subdomain names (empty)
     * @return deployers Array of deployer addresses (empty)
     * @dev DEPRECATED: Use PlatformUniverse directly for queries:
     *      1. Call PlatformUniverse.getAllSubdomainsForDomain(domain) to get all subdomains
     *      2. For each subdomain, call PlatformUniverse.getDeployersForDomain(domain, subdomain)
     *      3. For each deployer, call PlatformUniverse.getDeploymentCount(deployer, domain, subdomain)
     *      4. For each deployment index, call PlatformUniverse.getDeployment(deployer, domain, subdomain, index)
     *      This approach is more gas-efficient and provides access to full deployment history.
     */
    //function getAllDeploymentsForDomain(
    //    string memory domain,
    //    uint256 chainId
    //) external view returns (
    //    address[] memory controllers,
    //    string[] memory subdomains,
    //    address[] memory deployers
    //) {
    //    domain;
    //    chainId;

    // ===== PropertyNFT GADM Registration =====

    /// @notice Register a PropertyNFT with its GADM location hash
    /// @param gadmHash Keccak256 hash of 4 or 5-level GADM hierarchy (e.g., keccak256("US|NY|SUFFOLK|SOUTHAMPTON") or with 5th level)
    /// @param propertyNFT Address of the PropertyNFT contract
    /// @dev Reverts if GADM hash already registered. Only platform TokenAdmin can register a GADM propertyNFT.
    /// @dev SECURITY: Prevents squatting/poisoning of GADM registry by unauthorized parties
    function registerPropertyNFTByGADM(bytes32 gadmHash, address propertyNFT) external {
        if (gadmHash == bytes32(0)) revert InvalidGADMHash();
        if (propertyNFT == address(0)) revert InvalidPropertyNFTAddress();
        if (propertyNFTAddressesByGADMHash[gadmHash] != address(0)) revert PropertyNFTAlreadyExists();

        // 🔒 SECURITY: Only platform TokenAdmin can register PropertyNFTs to prevent registry poisoning
        if (!IController(FACTORY_CONTROLLER).isPlatformAdmin(msg.sender, KECCAK_TOKEN_ADMIN)) {
            revert NotAuthorized();
        }

        propertyNFTAddressesByGADMHash[gadmHash] = propertyNFT;
        gadmHashByPropertyNFT[propertyNFT] = gadmHash;

        emit PropertyNFTRegistered(gadmHash, propertyNFT, msg.sender, block.timestamp);
    }

    /// @notice Check if PropertyNFT exists for a GADM location
    /// @param gadmHash Keccak256 hash of 4 or 5-level GADM hierarchy
    /// @return exists True if PropertyNFT registered for this location
    /// @return propertyNFT Address of registered PropertyNFT (address(0) if none)
    function getPropertyNFTByGADM(bytes32 gadmHash) external view returns (bool exists, address propertyNFT) {
        propertyNFT = propertyNFTAddressesByGADMHash[gadmHash];
        exists = (propertyNFT != address(0));
    }

    /// @notice Get GADM hash for a PropertyNFT contract
    /// @param propertyNFT Address of the PropertyNFT contract
    /// @return gadmHash The GADM location hash (bytes32(0) if not registered)
    function getGADMHashByPropertyNFT(address propertyNFT) external view returns (bytes32 gadmHash) {
        return gadmHashByPropertyNFT[propertyNFT];
    }

    // ===== 🆕 Model Addresses Getter (Restricted Access) =====
    
    /// @notice Get model addresses used for a controller deployment
    /// @param controller The controller address to query
    /// @return models Fixed-size array[13] of model addresses in PlatformUniverse.Deployment order:
    ///                [0] controller, [1] feeManager, [2] tokenContent, [3] timeLockManager,
    ///                [4] token, [5] saleManager, [6] navPoolManager, [7] liquidityProvider,
    ///                [8] distributionManager, [9] projectRevenueTreasury, [10] restrictedSaleManager,
    ///                [11] teamManager, [12] releaseManager
    /// @dev Restricted: Caller must be registered as both TokenAdmin AND Registrar on FACTORY_CONTROLLER
    /// @dev Not otherwise unobtainable, however this method makes a strong statement that these models
    ///      are copyright protected and offered only to registrars and auditors for the strict purpose
    ///      of confirming projects are official and secure according to tier 1 auditor standards.
    function getModels(address controller) external view returns (address[] memory models) {
        // Require caller to be TokenAdmin OR Registrar
        if (!IController(FACTORY_CONTROLLER).isOfficialDoubleEntityFast(
            KECCAK_TOKEN_ADMIN, msg.sender,
            keccak256(bytes("Registrar")), msg.sender,
            false // requireBothActive - only need one
        )) revert NotAuthorized();
        return modelAddressesByController[controller];
    }

    /// @notice Returns the keccak256 hash of all model addresses for a given controller
    /// @dev For audits
    /// @param controller The controller address to query
    /// @return hash The keccak256 hash of abi.encodePacked(models array)
    function getModelsHash(address controller) external view returns (bytes32 hash) {
        return keccak256(abi.encodePacked(modelAddressesByController[controller]));
    }

}

// Interface for PlatformUniverse
interface IPlatformUniverse {
    // Deployment struct (mirrors PlatformUniverse.Deployment)
    struct Deployment {
        address controller;              // Phase 1
        address feeManager;              // Phase 1
        address tokenContent;            // Phase 2
        address timeLockManager;         // Phase 2
        address token;                   // Phase 3
        address saleManager;             // Phase 3
        address navPoolManager;          // Phase 4
        address liquidityProvider;       // Phase 4
        address distributionManager;     // Phase 5
        address projectRevenueTreasury;  // Phase 5
        address restrictedSaleManager;   // Phase 6
        address teamManager;             // Phase 6
        address releaseManager;          // Phase 7
        address batchTransferAndExtrasManager; // Phase 7 (after ReleaseManager)
        address deployer;                // Original deployer (set in Phase 1)
        uint256 timestamp;
        string projectName;
        string domain;
        string subdomain;
        uint256 chainId;
        uint8 currentPhase;              // 1-6 = incomplete, 7 = complete
        bool isComplete;                 // true only after phase 7
        uint256 projectDeploymentNumber; // Universal project number (set in Phase 1)
        uint256 deployerProjectCount;    // CREATE2 salt counter (set in Phase 1, used throughout all phases)
    }

    function PLATFORM_CONTROLLER() external view returns (address);

    function setControllerFactory(address _factory) external;

    function validateFeesMatchTemplate(
        IFeeManager.EntityFeesWithNames[] memory incomingFees,
        string memory domain,
        string memory subdomain
    ) external view returns (IFeeManager.EntityFeesWithNames[] memory);

    function registerDeployment(
        address tokenAddress,
        address controllerAddress,
        address treasuryAddress
    ) external;

    // Multi-phase deployment functions
    function savePhase1Deployment(
        address deployer,
        string memory domain,
        string memory subdomain,
        string memory projectName,
        address controller,
        address feeManager,
        uint256 projectDeploymentNumber,
        uint256 deployerProjectCount
    ) external;

    function savePhase2Deployment(
        address deployer,
        string memory domain,
        string memory subdomain,
        address tokenContent,
        address timeLockManager
    ) external;

    function savePhase3Deployment(
        address deployer,
        string memory domain,
        string memory subdomain,
        address token,
        address saleManager
    ) external;

    function savePhase4Deployment(
        address deployer,
        string memory domain,
        string memory subdomain,
        address navPoolManager,
        address liquidityProvider
    ) external;

    function savePhase5Deployment(
        address deployer,
        string memory domain,
        string memory subdomain,
        address distributionManager,
        address projectRevenueTreasury
    ) external;

    function savePhase6Deployment(
        address deployer,
        string memory domain,
        string memory subdomain,
        address restrictedSaleManager,
        address teamManager
    ) external;

    function completePhase7Deployment(
        address deployer,
        string memory domain,
        string memory subdomain,
        address releaseManager,
        address batchTransferAndExtrasManager
    ) external returns (address controller);

    function getIncompleteDeployment(
        address deployer,
        string memory domain,
        string memory subdomain,
        uint8 expectedPhase
    ) external view returns (Deployment memory);

    function getDeployersForDomain(
        string memory domain,
        string memory subdomain,
        uint256 start,
        uint256 count
    ) external view returns (address[] memory);

    function getDeployerByController(address controller) external view returns (address);

    function settleHolderFees(
        address tokenAddress,
        address projectTreasuryAddress,
        uint256 currentAllTimeHolderCount
    ) external returns (uint256 feeAmount);

    function getAllSubdomainsForDomain(string memory domain, uint256 start, uint256 count) external view returns (string[] memory);

    function collectDeployFeeWithPermit(
        address projectFeeManagerAddress,
        address stableCoinAddress,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint256 deployFee);

    function calculateDeployFee(
        address projectFeeManagerAddress
    ) external view returns (uint256 totalDeployFee);
    
    function getDeploymentCount(
        address deployer,
        string memory domain,
        string memory subdomain
    ) external view returns (uint256);
    
    function getDeployment(
        address deployer,
        string memory domain,
        string memory subdomain,
        uint256 index
    ) external view returns (Deployment memory);

}

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

    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);
    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);
    
    // 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);
    
    // Constants
    function BASIS_POINTS_DIVISOR() external view returns (uint256);
}

interfaces/IFeeManager.sol

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

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

    struct CalculatedEntityAmount {
        address entityAddress;
        uint256 amount;
    }

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

    // Core fee management functions (simplified - uses default chain type)
    function addChainedEntity(EntityFeesWithNames memory entity) external returns (bool);
    function removeChainedEntity(address entity, bool includeSelf) external returns (bool);
    function setChainedEntityLock(address entity, bool shouldLock) external returns (bool);
    
    // Core fee management functions (advanced - custom chain type)
    function addChainedEntity(bytes32 chainType, EntityFeesWithNames memory entity) external returns (bool);
    function removeChainedEntity(bytes32 chainHash, address entity, bool includeSelf) external returns (bool);
    function setChainedEntityLock(string calldata chainType, address entity, bool shouldLock) external returns (bool);
    
    // Lock/unlock (tiered sovereignty: Platform TokenAdmin for constructor entities, Project Admin for non-constructor)
    function lockChild(string calldata chainType, address child, bool isLock) external returns (bool);
    function lockAllMyChildren(string calldata chainType, address subtreeRoot, bool includeSubtreeRoot, bool isLock) external returns (uint256);
    
    // Payout override (tiered: Platform TokenAdmin for constructor roots, Project Admin for project-added roots)
    function changeRoot(string calldata chainType, address root, address newPayout) external returns (bool);
    
    // Per-root permanent lock (tiered: IRREVERSIBLE, no time restriction)
    function permLockRoot(string calldata chainType, address root) external returns (uint256 lockedCount);
    
    // Global locks (Super/TreasuryAdmin, after 6 months)
    function permLockAllRootChainedEntities(string calldata chainType, bool includeSelf, bool isFreezeLock) external returns (uint256 lockedCount);
    function lockNewRootEntityAdds(bool shouldLock) external returns (bool);
    
    // Query functions
    function isChainedEntity(string calldata chainType, address entity) external view returns (bool);
    
    function isChainedEntityFast(bytes32 hashedChainType, address entity) external view returns (bool);
    
    function getChainedEntity(string calldata chainType, address entity) external view returns (ChainedEntityStruct memory);
    
    function getActiveChainedEntities(string calldata chainType) external view returns (ChainedEntityStruct[] memory);
    
    // Fee calculation with hash (GAS-OPTIMIZED: ~200-300 gas savings vs string version)
    // Saves gas by avoiding ABI encoding overhead (96 bytes for string vs 32 bytes for hash)
    function calculateChainedAmounts(
        uint256 totalVal,
        uint256 maxPct,
        bytes32 feeTypeHash
    ) external view returns (
        CalculatedEntityAmount[] memory calculatedAmounts,
        uint256 totalAmount
    );
    
    // Fee calculation (advanced - custom chain type with uint8 feeType)
    function calculateChainedAmounts(
        bytes32 chainType,
        uint256 totalVal,
        uint256 maxPct,
        uint8 feeType
    ) external view returns (
        CalculatedEntityAmount[] memory calculatedAmounts,
        uint256 totalAmount
    );
    
    function distributeFees(
        CalculatedEntityAmount[] calldata calculatedFees,
        address payer,
        address paymentToken
    ) external returns (uint256 totalDistributed);
    
    function triggerNotify() external;
    
    // Fee type management
    function addFeeType(string calldata label) external;  // Auto-assigns next fee type
    function getAllFeeTypeLabels() external view returns (string[] memory);  // Batch getter for all labels
    function feeTypeLabels(uint8 index) external view returns (string memory);  // Query by array index 0-49!
    function feeTypeLabelToType(string calldata label) external view returns (uint8);  // Reverse mapping: label → type
    function getTypeForLabel(string calldata label) external view returns (uint8);  // Get type by label (reverts if undefined)
    function currentMaxFeeType() external view returns (uint8);  // Returns current max fee type (dynamic, starts at 7, max 50)
    function ABSOLUTE_MAX_FEE_TYPES() external view returns (uint8);  // Returns 50
    
    // ProjectRevenueTreasury notification registration
    function setProjectRevenueTreasury(address treasury) external;  // One-time registration of treasury for fee notifications
    
    // Constants
    function BASIS_POINTS_DIVISOR() external view returns (uint256);
    function ACTION_ADD() external view returns (uint8);
    function ACTION_UPDATE() external view returns (uint8);
    function ACTION_REMOVE() external view returns (uint8);
    function ACTION_LOCK() external view returns (uint8);
    function ACTION_UNLOCK() external view returns (uint8);
    function ACTION_REACTIVATE() external view returns (uint8);
}

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

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.