Skip to content
Verified contractExactUNLICENSED

PlatformUniverse

Address0x39710aa1b211c038d2106d32fc6febf003cf3247
Balance

0 ETH

 

Transactions

7

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 400 runs
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,172,093
Creation transaction
0x092b8d5b2f…f53a2053cb

contracts/PlatformUniverse.sol

// SPDX-License-Identifier: UNLICENSED
// =====================================================================
//  EquityMint.org / DataCloud OS  —  Official Sovereign Issuance Suite
//  Module: PlatformUniverse.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.
//
// Platform Universe - Central coordinator for platform-wide operations including fee validation,
// holder settlement tracking, and domain/subdomain fee template management. Offloads heavy logic
// from ControllerFactory to keep deployment gas costs manageable while ensuring all deployments
// comply with approved fee structures and regulatory requirements.
//
// Chief Architect and CEO: Ken Silverman, US Fintech LLC
// Designed by Ken Silverman as part of the EquityMint platform architecture.
// @author Ken Silverman
//
// ⚖️  AUTHORIZED USE RESTRICTIONS:
// Only projects deploying these contracts via the EquityMint platform at equitymint.org
// which contain this preamble and Fee structures generated through EquityMint.org have
// permission to use these contracts or any derivative works thereto. Any such deployment
// must contain these words. This contract is part of a greater system. They are owned
// and licensed exclusively in writing and through US Fintech, LLC.
//
// Any breach of these terms will be investigated and pursued through all available civil
// and criminal remedies to the fullest extent permitted by applicable law. Enforcement is
// discretionary. The failure to enforce any provision shall not constitute a waiver of the
// right to enforce at any time. All projects and platform users interacting with this system
// are subject to additional terms and conditions as may be published or updated from time to
// time at https://equitymint.org and/or https://DataCloudOS.com.
pragma solidity 0.8.35;

import "../interfaces/IController.sol";
import "../interfaces/IFeeManager.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

// Fee Type Hashes (Gas-Optimized - Compile-time Constants)
// Used with FeeManager.calculateChainedAmounts() for ~200-300 gas savings per call
bytes32 constant KECCAK_FEE_DEPLOY = keccak256("Deploy");
bytes32 constant KECCAK_FEE_TOKENPURCHASE = keccak256("TokenPurchase");

interface IControllerFactoryPM {
    function platformProjectsAndModels() external view returns (address);
}

interface IPlatformProjectsAndModelsAuth {
    function requireDeployerAuthorizedForDomain(string calldata domain, string calldata subdomain, address deployer) external view;
    function requireDeployerWhiteLabelWhitelisted(string calldata domain, string calldata subdomain, address deployer) external view;
}

/// @title PlatformUniverse
/// @author Ken Silverman
/// @notice Central coordinator for platform-wide operations: fee settlement, domain fee templates, and validation
/// @dev Offloads heavy logic from ControllerFactory to keep deployment gas costs manageable
contract PlatformUniverse {
    using SafeERC20 for IERC20;

    uint16 public constant CONTRACT_VERSION = 43108; // 43108: abandonIncompleteDeployment (force-restart escape hatch — platform-admin gated, marks ABANDONED + controller warning, decrements white-label cap slot)

    // Custom errors
    error Unauthorized();
    error InvalidTokenAddress();
    error InvalidController();
    error NoDeploymentFound();
    error FeeTemplateNotConfigured();
    error FeeTemplateMismatch();
    error InvalidFeeConfiguration();
    error TreasuryBalanceInsufficient();
    error IncompleteDeploymentExists();
    error NoIncompleteDeploymentFound();
    error NotExpectedPhase(uint8 expected, uint8 actual);
    error PhaseMatchButComplete(uint8 phase);
    error DeploymentAlreadyComplete();
    error InvalidDeploymentParams();
    error ControllerAlreadyLinked();
    error TokenAlreadyRegistered();
    error InvalidPhaseSequence();
    error IndexOutOfBounds();
    error InvalidFeeManager();
    error FeesArrayEmpty();
    error InvalidFirstFeeEntity();
    error FeeCountMismatch();

    // Platform controller (THE platform controller)
    address public immutable PLATFORM_CONTROLLER;

    // Reference to ControllerFactory for deployment lookups
    address public controllerFactory;

    // Keccak hashes for authorization checks
    bytes32 public constant KECCAK_SUPER_ADMIN = keccak256(bytes("Super"));
    bytes32 public constant KECCAK_TREASURY_ADMIN = keccak256(bytes("TreasuryAdmin"));
    bytes32 public constant KECCAK_SMART_CONTRACT = keccak256(bytes("SmartContract"));
    bytes32 public constant KECCAK_TOKEN_ADMIN = keccak256(bytes("TokenAdmin"));

    // ===== MULTI-PHASE DEPLOYMENT TRACKING =====

    /// @notice Final phase number — a deployment is complete when
    ///         currentPhase == FINAL_PHASE (see savePhaseDeployment).
    uint8 public constant FINAL_PHASE = 8;

    /// @notice Deployment state for multi-phase pattern (8 phases)
    /// @dev Phase 1: Controller + FeeManager
    /// @dev Phase 2: TokenContent + TimeLock
    /// @dev Phase 3: Token + SaleManager
    /// @dev Phase 4: NavPoolManager + LiquidityProvider
    /// @dev Phase 5: DistributionManager + ProjectRevenueTreasury
    /// @dev Phase 6: RestrictedSaleManager + TeamManager
    /// @dev Phase 7: ReleaseManager + BatchTransferAndExtrasManager.
    /// @dev Phase 8: Governance + CapitalCallManager (BOTH OPTIONAL) + finalization
    ///      / token-treasury registration. Governance moved here from phase 7 in
    ///      v43107 because a phase safely deploys at most 2 contracts. Omitted
    ///      peers carry `address(0)`, mirroring the sentinel pattern established
    ///      when BatchTransferAndExtrasManager was added.
    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 governance;                     // Phase 8 (address(0) if project has no Governance)
        address capitalCallManager;             // Phase 8 (after Governance; address(0) if project has no CapitalCallManager)
        address deployer;                       // Original deployer (set in Phase 1)
        uint256 timestamp;
        string projectName;
        string domain;     // Actually a DomainKey (see DOMAIN FEE TEMPLATES note) — struct field name frozen
        string subdomain;  // Actually a SubDomainKey — platform-determined at template-add time
        uint256 chainId;
        uint8 currentPhase;              // 1-7 = incomplete, 8 (FINAL_PHASE) = complete
        bool isComplete;                 // true only after phase 8
        uint256 projectDeploymentNumber; // Universal project number (set in Phase 1)
        uint256 deployerProjectCount;    // CREATE2 salt counter (set in Phase 1, used throughout all phases)
    }

    /// @notice Track all deployments by deployer and FULL domain (subdomain.domain)
    /// @dev Key = fullDomainKey built by _buildFullDomainKey(domain, subdomain)
    /// deployer => fullDomainKey => Deployment[] (chronological, last = most recent)
    mapping(address => mapping(string => Deployment[])) public deploymentsByDeployerDomain;

    /// @notice Lightweight lookup: controller => deployment location pointer
    /// @dev Stores WHERE to find the deployment, not the deployment itself
    struct DeploymentPointer {
        address deployer;
        string fullDomainKey;
        uint256 arrayIndex;
    }
    mapping(address => DeploymentPointer) internal _deploymentPointerByController;

    /// @notice Reverse lookup: controller => deployer
    mapping(address => address) public deployerByController;

    /// @notice Track all deployers who have deployed to a fullDomain
    /// fullDomainKey => deployer[] (unique deployers)
    mapping(string => address[]) public deployersByFullDomain;
    mapping(string => mapping(address => bool)) private hasDeployerForFullDomain;

    /// @notice Total projects ever registered per fullDomainKey (phase-1 registrations +
    ///         migrated inserts; overwrites don't count). Drives the restrictAllWhiteLabels cap.
    mapping(string => uint256) public projectCountByFullDomainKey;

    /// @notice Global white-label exclusivity cap (set via restrictAllWhiteLabels).
    ///         0 (default) or >= 1_000_000 => never force-restrict — the normal opt-in rule
    ///         applies (a white label is only gated if it added >= 1 whitelisted deployer).
    ///         1..999_999 => once a non-base white label already holds this many projects,
    ///         its NEXT deployer must be an EXPLICIT member of that white label's whitelist
    ///         in PlatformProjectsAndModels — even if the white label never opted in.
    ///         Auto-enforces invite-only exclusivity per white label; BASE_DOMAIN (and empty
    ///         domain, which defaults to base) is exempt so the direct channel stays open.
    uint256 public maxProjectsOpenPerWhiteLabel;

    // ===== HOLDER FEE SETTLEMENT =====
    //  now handled only within PRT itself auto-settling upon thresholded-transfers

    /// @notice Registry of all deployed projects for settlement automation
    address[] public allTokens;                                     // All registered tokens
    mapping(address => address) public treasuryByToken;            // token => ProjectRevenueTreasury (non-zero = registered)
    mapping(address => address) public controllerByToken;          // token => Controller

    // ===== DOMAIN FEE TEMPLATES =====
    //
    // NOTE — "domain"/"subdomain" ARE REALLY DomainKey/SubDomainKey: everywhere PU
    // (and PPAM) takes a `domain` + `subdomain` pair, the strings are PLATFORM-DETERMINED
    // KEYS chosen at template-add time — they may equal the white label's real DNS
    // domain/subdomain, or be deliberately obscure labels handed to the partner
    // off-chain. Nothing in the contracts requires them to resolve as DNS. This
    // key-system is enforced by EquityMint so on-chain data never hands a snooper a
    // contact-ready partner list (anti-self-competing); combined with
    // restrictAllWhiteLabels invite-only enforcement, key discovery is harmless.
    // Field/param names keep the legacy domain/subdomain spelling (ABI/struct frozen).
    //
    // Nested mapping: domain -> `subdomain#flavor` -> fee structure (see FLAVORS below)
    // Empty subdomain ("") = base domain, empty domain ("") = BASE_DOMAIN
    mapping(string => mapping(string => IFeeManager.EntityFeesWithNames[])) internal subdomainFeeTemplates;
    // domain -> `subdomain#flavor` = that flavor's template exists;
    // domain -> plain `subdomain`  = subdomain has >= 1 flavor (deployment-authorization gate)
    mapping(string => mapping(string => bool)) public subdomainTemplateExists;
    mapping(string => string[]) internal subdomainsByDomain;

    // ===== FEE TEMPLATE FLAVORS =====
    // v43107: EVERY template is a named "flavor" — there is no separately-stored plain
    // template. Each flavor's fees live in subdomainFeeTemplates under the synthetic
    // second-level key `subdomain#flavor` ('#' is illegal in a DNS label so flavored keys
    // can never collide with a real subdomain). The legacy no-title READ ABI is preserved
    // by aliasing: getSubdomainFeeTemplate returns the DEFAULT_FLAVOR ("BASE") flavor.
    // ALL writes go through setSubdomainFeeTemplateFlavorBatch (a base template is just
    // the "BASE"-flavored entry) — the legacy single setter was removed for bytecode.
    //
    // flavorsBySubdomain is the single source of truth for a subdomain's offering:
    // zero flavors == zero templates == subdomain NOT authorized for deployment.
    // Flavor names are tracked here (NOT in subdomainsByDomain), so subdomain enumeration
    // and Deployment records stay clean: the Deployment struct is untouched and a
    // project's flavor is implied by which template its fees matched.
    // domain => subdomain => flavor names
    mapping(string => mapping(string => string[])) internal flavorsBySubdomain;

    /// @dev Flavor title used by the legacy (no-title) set/get ABI. Admins may later
    ///      remove/replace it like any other flavor — it has no special standing in
    ///      validation, which simply loops ALL registered flavors.
    string internal constant DEFAULT_FLAVOR = "BASE";

    // Track all registered base domains
    string[] public allDomains;
    mapping(string => bool) private isDomainTracked;

    string public constant BASE_DOMAIN = "equitymint.org";

    // ===== OTHER PLATFORM UNIVERSES (FOR VERSIONING/SUPERSESSION) =====

    /// @notice Record of other PlatformUniverse versions with active status
    /// @dev Never removed - only deactivated to maintain historical confidence
    struct PlatformUniverseRecord {
        address platformUniverse;
        bool isActive;
    }

    /// @notice Array of other PlatformUniverse addresses with active status
    /// @dev Used only to support project list indexes when we supersede PlatformUniverse versions.
    /// @dev This allows new versions to reference historical deployments from previous versions.
    /// @dev Historical records are NEVER removed - only deactivated to maintain trust/confidence.
    /// @dev IMPORTANT: Only PLATFORM_CONTROLLER's TreasuryAdmin or Super can add or toggle active status.
    PlatformUniverseRecord[] public otherPlatformUniverses;
    mapping(address => bool) public isOtherPlatformUniverse;
    mapping(address => uint256) private otherPlatformUniverseIndex; // address => array index (for O(1) lookups)

    // ===== PLATFORM WARNINGS =====

    /// @notice Per-project warnings, keyed by project controller address.
    /// @dev Set by any Platform TreasuryAdmin / TokenAdmin / Super via
    ///      `setProjectWarning` to flag problematic or superceded projects.
    /// @dev Empty string = no warning, non-empty = warning message (practical max: ~256 chars)
    /// @dev Controller address is the lookup key (from any deployment)
    mapping(address => string) public warningByController;

    // ===== EVENTS =====

    /// @notice A per-project warning (keyed by controller) was set, updated, or cleared
    ///         by a Platform Admin (TreasuryAdmin, TokenAdmin, or Super).
    /// @dev    Naming: "Project" (not "Platform") because the warning is ABOUT a specific
    ///         project (controller), even though it is SET BY a platform admin.
    /// @dev    A cleared warning is signalled by `bytes(warning).length == 0`.  This
    ///         merges the previous `PlatformWarningSet` / `PlatformWarningCleared`
    ///         pair — indexers should check the string length to distinguish set from
    ///         cleared, or filter on `controller` to receive both transitions.
    event ProjectWarningChanged(address indexed controller, string warning, address indexed changedBy);

    event SubdomainFeeTemplateSet(string indexed domain, string subdomain, uint256 feeCount);
    event SubdomainFeeTemplateRemoved(string indexed domain, string subdomain);
    event ControllerFactoryUpdated(address indexed oldFactory, address indexed newFactory);

    /// @notice Emit of DeploymentPhaseComplete has been DISABLED across all phases.
    /// @dev    No room in contract to emit this event.  Unnecessary since state
    ///         changes each time and deploy1 comes with timestamp of that phase1.
    ///         Clients observe phase transitions by reading
    ///         `getDeployment*(...).currentPhase` and `.isComplete`, and the
    ///         phase-1 start timestamp is preserved on-chain as
    ///         `Deployment.timestamp` (set at `savePhase1Deployment`).
    ///         Definition kept (commented) below so the ABI history is discoverable
    ///         and so a future release with more bytecode headroom can trivially
    ///         re-enable it by uncommenting the definition + an emit at the
    ///         tail of the unified `savePhaseDeployment` (search for
    ///         "DeploymentPhaseComplete emit disabled").
    // event DeploymentPhaseComplete(address indexed deployer, string domain, address indexed controller, uint8 phase);

    // ===== MODIFIERS =====
    // Modifier bodies live in internal functions so the auth check is emitted once and
    // JUMPed to, instead of inlined at every use site (bytecode saving).

    modifier onlyPlatformAdmin() {
        _checkPlatformAdmin();
        _;
    }

    function _checkPlatformAdmin() internal view {
        if (!IController(PLATFORM_CONTROLLER).isOfficialTripleEntityFast(
            KECCAK_TREASURY_ADMIN, msg.sender,
            KECCAK_TOKEN_ADMIN, msg.sender,
            KECCAK_SUPER_ADMIN, msg.sender,
            false  // OR logic — any of Treasury / Token / Super passes
        )) revert Unauthorized();
    }

    modifier onlyAuthorizedContract() {
        _checkAuthorizedContract();
        _;
    }

    function _checkAuthorizedContract() internal view {
        // ✅ Expanded authorization (requested):
        // Allow when EITHER:
        // A) msg.sender is the configured controllerFactory (normal production path), OR
        // B) msg.sender is a Platform Admin (TreasuryAdmin OR TokenAdmin), OR
        // C) msg.sender is an Official SmartContract entity in the PLATFORM controller ("internal access")
        //
        // This enables step-wise tracing / recovery even if controllerFactory pointer is stale,
        // while still requiring platform-controlled identities.
        bool isFactory = (msg.sender == controllerFactory);
        bool isAuthorized = IController(PLATFORM_CONTROLLER).isOfficialTripleEntityFast(
            KECCAK_TREASURY_ADMIN, msg.sender,
            KECCAK_TOKEN_ADMIN, msg.sender,
            KECCAK_SMART_CONTRACT, msg.sender,
            false  // OR logic
        );
        if (!(isFactory || isAuthorized)) revert Unauthorized();
    }

    // ===== CONSTRUCTOR =====

    constructor(address _platformController) {
        if (_platformController == address(0)) revert InvalidController();

        // 🔒 SECURITY: Verify platform controller is self-referential (not a child project controller)
        require(
            IController(_platformController).isPlatform(),
            "PlatformUniverse: Controller must be the platform controller"
        );

        PLATFORM_CONTROLLER = _platformController;

        // Register self as SmartContract in platform controller
        IController(_platformController).init(address(this), "PlatformUniverse");
    }

    // ===== CONTROLLER FACTORY MANAGEMENT =====

    /**
     * @notice Set the ControllerFactory address (one-time or updatable by platform admin)
     * @param _factory Address of ControllerFactory contract
     */
    function setControllerFactory(address _factory) external {
        if (_factory == address(0)) revert InvalidController();

        // 🔒 OFFICIAL UPDATE RULE (OR):
        // Allow setting/updating controllerFactory when EITHER:
        // A) msg.sender is a Platform Admin (TreasuryAdmin / TokenAdmin / Super), OR
        // B) msg.sender is an Official SmartContract entity in the Platform Controller
        //    AND is setting itself (_factory == msg.sender) — supports the
        //    ControllerFactory constructor → setControllerFactory(address(this)) pattern
        //    without requiring a manual post-deploy transaction.
        bool senderIsPlatformAdmin = IController(PLATFORM_CONTROLLER).isOfficialTripleEntityFast(
            KECCAK_TREASURY_ADMIN, msg.sender,
            KECCAK_TOKEN_ADMIN, msg.sender,
            KECCAK_SUPER_ADMIN, msg.sender,
            false  // OR logic
        );

        if (!senderIsPlatformAdmin) {
            bool isSetByOfficialContract = (msg.sender == _factory) &&
                IController(PLATFORM_CONTROLLER).isOfficialEntityFast(KECCAK_SMART_CONTRACT, msg.sender);
            if (!isSetByOfficialContract) revert Unauthorized();
        }

        address oldFactory = controllerFactory;
        controllerFactory = _factory;
        emit ControllerFactoryUpdated(oldFactory, _factory);
    }

    /// @notice One-way migration seal (mirrors Controller.sealMigration). False = still open.
    /// @dev AUDITOR GUARANTEE: once sealed, migrateDeployments is disabled FOREVER, so
    ///      every project this PU can ever register from then on arrives ONLY through
    ///      ControllerFactory's savePhase* path — i.e. official deployments built from
    ///      certified models with template-validated fees. Seal AFTER migration completes.
    bool public migrationSealed;

    /// @notice Permanently disable migrateDeployments (Platform Admin only, one-way).
    function sealMigration() external onlyPlatformAdmin {
        migrationSealed = true;
    }

    /// @notice Bulk-migrate complete Deployment snapshots from a previous PU instance.
    /// @dev Absolute copy-over: if the controller already exists on this PU, the existing
    ///      array slot is OVERWRITTEN in place (no duplicate entries created on re-run).
    ///      No phase-ordering, no PPAM, no event — bytecode-minimal.
    /// @dev Disabled forever once sealMigration() is called (reuses Unauthorized —
    ///      no new error selector, bytecode-minimal).
    function migrateDeployments(Deployment[] calldata deps) external onlyPlatformAdmin {
        if (migrationSealed) revert Unauthorized();
        for (uint256 i = 0; i < deps.length; i++) {
            Deployment calldata d = deps[i];
            string memory key = _buildFullDomainKey(d.domain, d.subdomain);
            DeploymentPointer storage ptr = _deploymentPointerByController[d.controller];

            if (ptr.deployer == address(0)) {
                Deployment[] storage arr = deploymentsByDeployerDomain[d.deployer][key];
                arr.push(d);
                _deploymentPointerByController[d.controller] = DeploymentPointer(d.deployer, key, arr.length - 1);
                if (!hasDeployerForFullDomain[key][d.deployer]) {
                    deployersByFullDomain[key].push(d.deployer);
                    hasDeployerForFullDomain[key][d.deployer] = true;
                }
                projectCountByFullDomainKey[key] += 1;
            } else {
                deploymentsByDeployerDomain[ptr.deployer][ptr.fullDomainKey][ptr.arrayIndex] = d;
            }

            deployerByController[d.controller] = d.deployer;

            if (d.isComplete && d.token != address(0)) {
                if (controllerByToken[d.token] == address(0)) allTokens.push(d.token);
                treasuryByToken[d.token] = d.projectRevenueTreasury;
                controllerByToken[d.token] = d.controller;
            }
        }
    }

    /// @notice Set the global white-label exclusivity cap — see maxProjectsOpenPerWhiteLabel
    ///         for full semantics (0 or >= 1_000_000 disables; 1..999_999 forces invite-only
    ///         once a white label holds that many projects).
    /// @dev    Platform TokenAdmin ONLY — deliberately narrower than onlyPlatformAdmin.
    ///         No event; read back via the public getter (bytecode-minimal).
    function restrictAllWhiteLabels(uint256 maxProjectsOpen) external {
        if (!IController(PLATFORM_CONTROLLER).isPlatformAdmin(msg.sender, KECCAK_TOKEN_ADMIN)) revert Unauthorized();
        maxProjectsOpenPerWhiteLabel = maxProjectsOpen;
    }



    // ===== PROJECT WARNING MANAGEMENT =====
    // Naming: "Project" (not "Platform") because these warnings are ABOUT a
    // specific project (controller) even though they are SET BY a platform admin.
    // Warnings apply to project *conduct* (poor behavior, disputes, sanctions
    // flags, etc.) — code-integrity concerns live under PPAM's CodeAuditor
    // attestation flow, not here.

    /**
     * @notice Set, update, or clear a per-project warning (keyed by controller).
     * @param  controller Controller address to flag.
     * @param  warning    Warning message; pass an empty string to clear.
     * @dev    Only PLATFORM_CONTROLLER's TreasuryAdmin / TokenAdmin / Super can call
     *         (see `onlyPlatformAdmin`).
     * @dev    Practical limit: ~256 characters for gas efficiency.
     * @dev    A single unified `ProjectWarningChanged` event is emitted for both
     *         set and clear transitions — clients distinguish by checking whether
     *         the emitted `warning` is empty.  This replaces the earlier
     *         `PlatformWarningSet` / `PlatformWarningCleared` pair (merged for
     *         bytecode savings).
     */
    function setProjectWarning(address controller, string calldata warning) external onlyPlatformAdmin {
        if (controller == address(0)) revert InvalidController();

        warningByController[controller] = warning;

        emit ProjectWarningChanged(controller, warning, msg.sender);
    }

    /**
     * @notice Get the current warning string for a project (empty if none).
     * @param  controller Project controller address to look up.
     * @return Warning message; empty string means no warning.
     */
    function getProjectWarning(address controller) external view returns (string memory) {
        return warningByController[controller];
    }

    /**
     * @notice Check whether a project currently has a warning set.
     * @param  controller Project controller address to check.
     * @return True if a non-empty warning exists for this project.
     * @dev    Kept as `hasWarning` (not `hasProjectWarning`) since PU has only
     *         one warning concept — the "Project" qualifier is unnecessary here
     *         and would add bytecode.  The setter/getter are `set/getProjectWarning`
     *         only because their old names (`set/getPlatformWarning`) were
     *         misleading — "Platform" wrongly implied the warning was about the
     *         platform itself, not about a project.
     */
    function hasWarning(address controller) external view returns (bool) {
        return bytes(warningByController[controller]).length > 0;
    }

    // ===== TWO-PHASE DEPLOYMENT MANAGEMENT =====

    /**
     * @notice Build full domain key for mapping (subdomain.domain or just domain)
     * @dev Internal helper to ensure consistent key construction
     */
    function _buildFullDomainKey(string memory domain, string memory subdomain) internal pure returns (string memory) {
        if (bytes(subdomain).length == 0) {
            return domain;  // No subdomain, use domain only
        }
        return string(abi.encodePacked(subdomain, ".", domain));  // subdomain.domain
    }

    /**
     * @notice Save phase 1 deployment state (called by ControllerFactory.deployAll1)
     * @dev Creates new incomplete deployment record - reverts if last deployment for this FULL domain is incomplete
     * @dev Phase 1: Controller + FeeManager
     * @dev Key = subdomain.domain (e.g., "caldwellbanker.equitymint.org")
     */
    function savePhase1Deployment(
        address deployer,
        string memory domain,
        string memory subdomain,
        string memory projectName,
        address controller,
        address feeManager,
        uint256 projectDeploymentNumber,
        uint256 deployerProjectCount
    ) external onlyAuthorizedContract {
        if (
            deployer == address(0) ||
            controller == address(0) ||
            feeManager == address(0)
        ) revert InvalidDeploymentParams();

        // Build full domain key (subdomain.domain)
        string memory fullDomainKey = _buildFullDomainKey(domain, subdomain);

        // White-label whitelist (stored/enforced via PlatformProjectsAndModels, not here).
        // Normal rule: gate only if the white label opted in (>= 1 whitelisted deployer).
        // Cap rule (restrictAllWhiteLabels): once a non-base white label already holds
        // maxProjectsOpenPerWhiteLabel projects, the deployer MUST be an explicit whitelist
        // member even if the white label never opted in (auto-enforced invite-only).
        {
            address ppam = IControllerFactoryPM(controllerFactory).platformProjectsAndModels();
            uint256 cap = maxProjectsOpenPerWhiteLabel;
            if (
                cap != 0 && cap < 1_000_000 &&
                bytes(domain).length != 0 &&
                keccak256(bytes(domain)) != keccak256(bytes(BASE_DOMAIN)) &&
                projectCountByFullDomainKey[fullDomainKey] >= cap
            ) {
                IPlatformProjectsAndModelsAuth(ppam).requireDeployerWhiteLabelWhitelisted(domain, subdomain, deployer);
            } else {
                IPlatformProjectsAndModelsAuth(ppam).requireDeployerAuthorizedForDomain(domain, subdomain, deployer);
            }
        }

        // Indexes required by public query functions:
        // - controller -> deployer lookup
        // - fullDomain -> deployers lookup
        address existingDeployer = deployerByController[controller];
        if (existingDeployer != address(0) && existingDeployer != deployer) revert ControllerAlreadyLinked();
        deployerByController[controller] = deployer;

        if (!hasDeployerForFullDomain[fullDomainKey][deployer]) {
            deployersByFullDomain[fullDomainKey].push(deployer);
            hasDeployerForFullDomain[fullDomainKey][deployer] = true;
        }

        // 🔒 GUARD: Check if last deployment for this deployer+fullDomain is incomplete
        Deployment[] storage deployments = deploymentsByDeployerDomain[deployer][fullDomainKey];
        if (deployments.length > 0) {
            Deployment storage lastDep = deployments[deployments.length - 1];
            if (!lastDep.isComplete) revert IncompleteDeploymentExists();
        }

        // Create new incomplete deployment (phase 1 only)
        Deployment memory newDep = Deployment({
            controller: controller,
            feeManager: feeManager,
            tokenContent: address(0),
            timeLockManager: address(0),
            token: address(0),
            saleManager: address(0),
            navPoolManager: address(0),
            liquidityProvider: address(0),
            distributionManager: address(0),
            projectRevenueTreasury: address(0),
            restrictedSaleManager: address(0),
            teamManager: address(0),
            releaseManager: address(0),
            batchTransferAndExtrasManager: address(0),
            governance: address(0),
            capitalCallManager: address(0),
            deployer: deployer,
            timestamp: block.timestamp,
            projectName: projectName,
            domain: domain,
            subdomain: subdomain,
            chainId: block.chainid,
            currentPhase: 1,
            isComplete: false,
            projectDeploymentNumber: projectDeploymentNumber,
            deployerProjectCount: deployerProjectCount
        });

        deployments.push(newDep);
        projectCountByFullDomainKey[fullDomainKey] += 1;

        // ✅ Store pointer to this deployment for fast controller lookup
        _deploymentPointerByController[controller] = DeploymentPointer({
            deployer: deployer,
            fullDomainKey: fullDomainKey,
            arrayIndex: deployments.length - 1
        });

        // DeploymentPhaseComplete emit disabled across ALL phases for bytecode.
        // Clients observe phase transitions via getDeployment*(...).currentPhase;
        // deploy1's block.timestamp is preserved in Deployment.timestamp.
    }

    /**
     * @notice v43108 — ABANDON the last INCOMPLETE deployment record for
     *         deployer + domain + subdomain so a fresh phase-1 START can run on the
     *         SAME full-domain key (force-restart). The orphaned contracts stay
     *         on-chain untouched (their PPAM initHash records remain valid), and
     *         CFA's per-deployer salt counter was already bumped by the orphaned
     *         attempt — the restart naturally gets fresh CREATE2 salts, so nothing
     *         collides and NO counters are reset here.
     * @dev    Gate: `onlyPlatformAdmin` = Platform TreasuryAdmin | TokenAdmin | Super
     *         (OR logic — Super always qualifies). UI additionally hides the control
     *         below sessionState 48, but THIS check is the real security boundary.
     * @dev    ABANDONED markers (deliberately NO Deployment-struct ABI change):
     *         1. isComplete=true while currentPhase stays < FINAL_PHASE — a combination
     *            a genuine completion can NEVER produce. Machine-readable flag:
     *            `isComplete && currentPhase < 8` ⇒ abandoned.
     *         2. projectName is prefixed "ABANDONED-INCOMPLETE-DO-NOT-USE: " (human trail).
     *         3. warningByController[controller] is set (same surface as
     *            setProjectWarning, emits ProjectWarningChanged) so every
     *            warning-aware UI shows it against the orphaned controller.
     * @dev    projectCountByFullDomainKey is decremented so the abandoned attempt
     *         does not consume a white-label cap slot (restrictAllWhiteLabels rule).
     */
    function abandonIncompleteDeployment(
        address deployer,
        string calldata domain,
        string calldata subdomain
    ) external onlyPlatformAdmin {
        string memory fullDomainKey = _buildFullDomainKey(domain, subdomain);
        Deployment[] storage deployments = deploymentsByDeployerDomain[deployer][fullDomainKey];
        if (deployments.length == 0) revert NoIncompleteDeploymentFound();
        Deployment storage lastDep = deployments[deployments.length - 1];
        if (lastDep.isComplete) revert DeploymentAlreadyComplete();

        lastDep.isComplete = true; // + currentPhase < 8 ⇒ the ABANDONED signature
        lastDep.projectName = string(abi.encodePacked("ABANDONED-INCOMPLETE-DO-NOT-USE: ", lastDep.projectName));

        if (projectCountByFullDomainKey[fullDomainKey] > 0) {
            projectCountByFullDomainKey[fullDomainKey] -= 1;
        }

        string memory warning = "ABANDONED-INCOMPLETE-DO-NOT-USE: phase-1..7 deployment force-abandoned; these contracts are orphaned";
        warningByController[lastDep.controller] = warning;
        emit ProjectWarningChanged(lastDep.controller, warning, msg.sender);
    }

    /**
     * @notice 🆕 UNIFIED phase saver (called by ControllerFactory.deployAll2..8).
     * @dev Replaces savePhase2Deployment..savePhase6Deployment +
     *      completePhase7Deployment: the guard preamble (fullDomainKey build,
     *      array fetch, isComplete / phase-sequence checks) was byte-identical
     *      across all six functions, so it is now written ONCE and the only
     *      per-phase difference — which Deployment fields the two/three
     *      address slots land in — is a tiny if/else ladder. This freed the
     *      bytecode room needed to add phase 8 (CapitalCallManager).
     * @dev No reflection exists in Solidity; the fixed ladder below IS the
     *      "fixed array lookup" — each branch costs only a comparison + two
     *      SSTOREs, while the struct keeps its named fields (so every getter
     *      and the migrateDeployments ABI remain unchanged apart from the new
     *      capitalCallManager field).
     * @param deployer  Original deployer (key into deploymentsByDeployerDomain)
     * @param domain    Base domain (e.g., "equitymint.org")
     * @param subdomain Subdomain — combined with domain for key lookup
     * @param phase     Phase being saved (2..FINAL_PHASE). Must equal
     *                  currentPhase + 1 (strict sequence).
     * @param a         First address slot of the phase (see ladder below)
     * @param b         Second address slot (address(0) where unused)
     * @param c         Third address slot (unused since v43107 — always address(0))
     * @return controller The project controller of the deployment
     *
     * Slot meaning per phase:
     *   2: (tokenContent, timeLockManager, -)
     *   3: (token, saleManager, -)
     *   4: (navPoolManager, liquidityProvider, -)
     *   5: (distributionManager, projectRevenueTreasury, -)
     *   6: (restrictedSaleManager, teamManager, -)
     *   7: (releaseManager, batchTransferAndExtrasManager, -)
     *   8: (governance, capitalCallManager, -) + FINALIZATION: isComplete=true and
     *      token/treasury registration for holder-fee settlement.
     */
    function savePhaseDeployment(
        address deployer,
        string memory domain,
        string memory subdomain,
        uint8 phase,
        address a,
        address b,
        address c
    ) external onlyAuthorizedContract returns (address controller) {
        if (phase < 2 || phase > FINAL_PHASE) revert InvalidPhaseSequence();

        string memory fullDomainKey = _buildFullDomainKey(domain, subdomain);
        Deployment[] storage deployments = deploymentsByDeployerDomain[deployer][fullDomainKey];

        if (deployments.length == 0) revert NoIncompleteDeploymentFound();
        Deployment storage dep = deployments[deployments.length - 1];

        if (dep.isComplete) revert NoIncompleteDeploymentFound();
        if (dep.currentPhase != phase - 1) revert InvalidPhaseSequence();

        if (phase == 2)      { dep.tokenContent = a;          dep.timeLockManager = b; }
        else if (phase == 3) { dep.token = a;                 dep.saleManager = b; }
        else if (phase == 4) { dep.navPoolManager = a;        dep.liquidityProvider = b; }
        else if (phase == 5) { dep.distributionManager = a;   dep.projectRevenueTreasury = b; }
        else if (phase == 6) { dep.restrictedSaleManager = a; dep.teamManager = b; }
        else if (phase == 7) { dep.releaseManager = a;        dep.batchTransferAndExtrasManager = b; }
        else                 { dep.governance = a;            dep.capitalCallManager = b; }  // phase 8 (FINAL_PHASE)

        dep.currentPhase = phase;

        if (phase == FINAL_PHASE) {
            dep.isComplete = true;

            // Automatically register for holder fee settlements
            if (dep.token != address(0) && dep.projectRevenueTreasury != address(0)) {
                address existingTreasury = treasuryByToken[dep.token];
                address existingController = controllerByToken[dep.token];

                // If previously registered, it must match the same controller (prevent accidental collisions).
                if (existingController != address(0) && existingController != dep.controller) revert TokenAlreadyRegistered();

                if (existingTreasury == address(0)) {
                    allTokens.push(dep.token);
                }

                treasuryByToken[dep.token] = dep.projectRevenueTreasury;
                controllerByToken[dep.token] = dep.controller;
            }
        }

        // Intermediate-phase / completion emits removed for bytecode savings
        // (see DeploymentPhaseComplete NatSpec above).
        return dep.controller;
    }

    /**
     * @notice Get the most recent incomplete deployment for a deployer+domain
     * @dev Queries LATEST deployment in array.
     * @dev If expectedPhase=0 and no deployment found, returns empty struct (currentPhase=0) instead of reverting.
     * @dev If expectedPhase>0, reverts on: no deployment, wrong phase, or deployment complete.
     * @param deployer Deployer address
     * @param domain Base domain (e.g., "equitymint.org")
     * @param subdomain Subdomain (e.g., "caldwellbanker")
     * @param expectedPhase Expected current phase (0 = no phase check, returns any incomplete or empty if none)
     * @return The deployment struct (or empty struct with currentPhase=0 if expectedPhase=0 and none found)
     */
    function getIncompleteDeployment(
        address deployer,
        string memory domain,
        string memory subdomain,
        uint8 expectedPhase
    ) external view returns (Deployment memory) {
        // Build full domain key (subdomain.domain)
        string memory fullDomainKey = _buildFullDomainKey(domain, subdomain);

        Deployment[] storage deployments = deploymentsByDeployerDomain[deployer][fullDomainKey];

        // No deployment exists
        if (deployments.length == 0) {
            if (expectedPhase == 0) {
                // Return empty struct with all fields defaulted (currentPhase=0 means "doesn't exist")
                Deployment memory empty;
                return empty;
            }
            revert NoIncompleteDeploymentFound();
        }

        // Get LATEST deployment in array
        Deployment storage dep = deployments[deployments.length - 1];

        // For expectedPhase=0, return empty struct if deployment is complete
        // (semantic: "no incomplete deployment blocking you" - same as "no deployments exist")
        if (expectedPhase == 0) {
            if (dep.isComplete) {
                Deployment memory empty;
                return empty;
            }
            // Incomplete deployment exists - return it so caller can block
            return dep;
        }

        // Check if deployment is complete
        if (dep.isComplete) {
            // If expectedPhase is provided and matches, revert with specific error
            if (dep.currentPhase == expectedPhase) {
                revert PhaseMatchButComplete(expectedPhase);
            }
            // Otherwise generic incomplete not found
            revert NoIncompleteDeploymentFound();
        }

        // Check expected phase
        if (dep.currentPhase != expectedPhase) {
            revert NotExpectedPhase(expectedPhase, dep.currentPhase);
        }

        return dep;
    }

    /**
     * @notice Get deployment count for a deployer+domain
     * @param domain Base domain (e.g., "equitymint.org")
     * @param subdomain Subdomain (e.g., "caldwellbanker")
     */
    function getDeploymentCount(
        address deployer,
        string memory domain,
        string memory subdomain
    ) external view returns (uint256) {
        string memory fullDomainKey = _buildFullDomainKey(domain, subdomain);
        return deploymentsByDeployerDomain[deployer][fullDomainKey].length;
    }

    /**
     * @notice Get a specific deployment by index
     * @param domain Base domain (e.g., "equitymint.org")
     * @param subdomain Subdomain (e.g., "caldwellbanker")
     */
    function getDeployment(
        address deployer,
        string memory domain,
        string memory subdomain,
        uint256 index
    ) external view returns (Deployment memory) {
        string memory fullDomainKey = _buildFullDomainKey(domain, subdomain);
        Deployment[] storage deployments = deploymentsByDeployerDomain[deployer][fullDomainKey];
        if (index >= deployments.length) revert IndexOutOfBounds();
        return deployments[index];
    }

    /**
     * @notice Get all deployers who have deployed to a fullDomain
     * @param domain Base domain (e.g., "equitymint.org")
     * @param subdomain Subdomain (e.g., "caldwellbanker")
     */
    function getDeployersForDomain(
        string memory domain,
        string memory subdomain,
        uint256 start,
        uint256 count
    ) external view returns (address[] memory) {
        string memory fullDomainKey = _buildFullDomainKey(domain, subdomain);
        address[] storage deployers = deployersByFullDomain[fullDomainKey];
        uint256 len = deployers.length;
        // start > len  -> REVERT (out of range). start <= len -> CLIP count to remaining.
        if (start > len) revert IndexOutOfBounds();
        uint256 remaining = len - start;
        if (count == 0 || count > remaining) count = remaining;
        address[] memory out = new address[](count);
        for (uint256 i = 0; i < count; i++) {
            out[i] = deployers[start + i];
        }
        return out;
    }

    /**
     * @notice Get deployer address from controller address
     */
    function getDeployerByController(address controller) external view returns (address) {
        return deployerByController[controller];
    }

    /**
     * @notice Get deployment struct by controller address
     * @dev Uses pointer to look up actual deployment in storage
     */
    function getDeploymentByController(address controller) external view returns (Deployment memory) {
        DeploymentPointer storage ptr = _deploymentPointerByController[controller];
        if (ptr.deployer == address(0)) {
            // Return empty struct if not found
            Deployment memory empty;
            return empty;
        }
        return deploymentsByDeployerDomain[ptr.deployer][ptr.fullDomainKey][ptr.arrayIndex];
    }

    /// @notice Phase-8 completeness only. Sidecars (CNFF, etc.) MUST use this
    ///         instead of decoding Deployment — that ABI breaks when fields are
    ///         inserted. Unknown controller → false.
    function isDeploymentComplete(address controller) external view returns (bool) {
        DeploymentPointer storage ptr = _deploymentPointerByController[controller];
        if (ptr.deployer == address(0)) return false;
        return deploymentsByDeployerDomain[ptr.deployer][ptr.fullDomainKey][ptr.arrayIndex].isComplete;
    }

    // ===== DEPLOYMENT REGISTRATION (Legacy - for single-phase deployAll) =====


    /**
     * @notice Get total number of registered tokens
     * @return count Total tokens registered for settlement
     */
    function getTokenCount() external view returns (uint256) {
        return allTokens.length;
    }

    // ===== HOLDER FEE SETTLEMENT =====



    /**
     * @notice Calculate deployment fee without collecting (for frontend to generate permit signature)
     * @param projectFeeManagerAddress Address of the FeeManager to query
     * @return totalDeployFee Total deployment fee that will be charged
     * @dev Call this BEFORE deployAll to get the fee amount for user's permit signature
     * @dev Returns 0 if no deploy fee configured
     */
    function calculateDeployFee(
        address projectFeeManagerAddress
    ) external view returns (uint256 totalDeployFee) {
        if (projectFeeManagerAddress == address(0)) revert InvalidFeeManager();

        IFeeManager projectFeeManager = IFeeManager(projectFeeManagerAddress);

        // Calculate deploy fee using hash (gas-optimized)
        (, totalDeployFee) = projectFeeManager.calculateChainedAmounts(
            0,                  // totalVal = 0 (flat fee)
            10000,              // maxPct = 100%
            KECCAK_FEE_DEPLOY   // feeTypeHash: resolved internally
        );

        return totalDeployFee;
    }

    // ===== DOMAIN FEE TEMPLATE MANAGEMENT =====

    // v43107: the legacy setSubdomainFeeTemplate(subdomain, domain, fees) setter was
    // DELETED for bytecode economy — a base template is simply the "BASE"-flavored entry,
    // written through setSubdomainFeeTemplateFlavorBatch like every other template.
    // (getSubdomainFeeTemplate still exists and reads the "BASE" flavor, so legacy
    // READERS are unaffected.)

    /// @dev One batch entry = one stored template (`subdomain#flavor`).
    struct FeeTemplateEntry {
        string subdomain;                        // empty = domain-only (base) slot
        string domain;                           // empty defaults to BASE_DOMAIN
        string flavor;                           // empty defaults to DEFAULT_FLAVOR ("BASE"); no '#'
        IFeeManager.EntityFeesWithNames[] fees;  // the template's fee entities
    }

    /**
     * @notice Set ONE or MANY titled fee templates ("flavors") in a single transaction
     *         (Platform Admin only).
     * @dev v43107: this is THE flavor write path — setting a single flavor is simply a
     *      1-element batch (there is intentionally no separate single-flavor setter, for
     *      bytecode economy). The FIRST flavor set for a subdomain both authorizes the
     *      domain/subdomain AND registers it in subdomainsByDomain; no flavor has special
     *      standing — validation accepts any. Migration UIs push ALL templates chunked
     *      through here (one wallet tx per chunk).
     * @param entries One entry per template to store.
     */
    function setSubdomainFeeTemplateFlavorBatch(FeeTemplateEntry[] calldata entries) external onlyPlatformAdmin {
        for (uint256 i = 0; i < entries.length; i++) {
            _setSubdomainFeeTemplate(entries[i].subdomain, entries[i].domain, entries[i].flavor, entries[i].fees);
        }
    }

    /// @dev Single write path — EVERY template is stored under `subdomain#flavor`.
    ///      Plain-key state: subdomainTemplateExists[domain][subdomain] means
    ///      "this subdomain has >= 1 flavor" (the deployment-authorization gate).
    function _setSubdomainFeeTemplate(
        string memory subdomain,
        string memory domain,
        string memory flavor,
        IFeeManager.EntityFeesWithNames[] memory fees
    ) internal {
        if (fees.length == 0) revert FeesArrayEmpty();

        // '#' is the reserved flavor-key separator — forbid it in both parts so a crafted
        // subdomain/flavor can never collide with another (subdomain, flavor) storage key.
        // (Reuses InvalidDeploymentParams — no new error selector, bytecode-minimal.)
        if (_containsHash(subdomain) || _containsHash(flavor)) revert InvalidDeploymentParams();

        if (bytes(flavor).length == 0) {
            flavor = DEFAULT_FLAVOR;
        }

        // Default to BASE_DOMAIN if empty
        if (bytes(domain).length == 0) {
            domain = BASE_DOMAIN;
        }

        string memory key = _flavorKey(subdomain, flavor);

        // New flavor title for this subdomain?
        if (!subdomainTemplateExists[domain][key]) {
            string[] storage flavors = flavorsBySubdomain[domain][subdomain];
            if (flavors.length == 0) {
                // FIRST flavor => subdomain becomes authorized + enumerable
                if (!isDomainTracked[domain]) {
                    allDomains.push(domain);
                    isDomainTracked[domain] = true;
                }
                subdomainsByDomain[domain].push(subdomain);
                subdomainTemplateExists[domain][subdomain] = true; // plain key = "has >= 1 flavor"
            }
            flavors.push(flavor);
        }

        // Clear existing fees
        delete subdomainFeeTemplates[domain][key];

        // Store new fees (includes name/ID for transparency, but validation ignores them)
        for (uint256 i = 0; i < fees.length; i++) {
            subdomainFeeTemplates[domain][key].push(fees[i]);
        }

        subdomainTemplateExists[domain][key] = true;
        emit SubdomainFeeTemplateSet(domain, key, fees.length);
    }

    // v43107: the legacy removeSubdomainFeeTemplate(subdomain, domain) was DELETED
    // (bytecode economy — no UI or script ever called it). All removal goes through
    // removeSubdomainFeeTemplateFlavor; removing the LAST flavor fully de-authorizes
    // the subdomain, so a flavor-by-flavor wipe achieves the old "remove template"
    // semantics.

    /**
     * @notice Remove a single flavor for a subdomain (Platform Admin only)
     * @dev Empty flavor defaults to DEFAULT_FLAVOR ("BASE"). Removing the LAST flavor
     *      de-authorizes the subdomain (clears the plain-key gate + enumeration entry).
     */
    function removeSubdomainFeeTemplateFlavor(
        string memory subdomain,
        string memory domain,
        string memory flavor
    ) external onlyPlatformAdmin {
        if (bytes(flavor).length == 0) {
            flavor = DEFAULT_FLAVOR;
        }
        if (bytes(domain).length == 0) {
            domain = BASE_DOMAIN;
        }

        string memory key = _flavorKey(subdomain, flavor);
        delete subdomainFeeTemplates[domain][key];
        subdomainTemplateExists[domain][key] = false;

        // Remove flavor name from tracking array
        string[] storage flavors = flavorsBySubdomain[domain][subdomain];
        for (uint256 i = 0; i < flavors.length; i++) {
            if (keccak256(bytes(flavors[i])) == keccak256(bytes(flavor))) {
                flavors[i] = flavors[flavors.length - 1];
                flavors.pop();
                break;
            }
        }

        // Last flavor gone => subdomain no longer authorized or enumerable
        if (flavors.length == 0) {
            subdomainTemplateExists[domain][subdomain] = false;
            _removeSubdomainFromDomainList(domain, subdomain);
        }

        emit SubdomainFeeTemplateRemoved(domain, key);
    }

    /// @dev Swap-and-pop `subdomain` out of subdomainsByDomain[domain] (no-op if absent).
    function _removeSubdomainFromDomainList(string memory domain, string memory subdomain) internal {
        string[] storage subdomains = subdomainsByDomain[domain];
        for (uint256 i = 0; i < subdomains.length; i++) {
            if (keccak256(bytes(subdomains[i])) == keccak256(bytes(subdomain))) {
                subdomains[i] = subdomains[subdomains.length - 1];
                subdomains.pop();
                break;
            }
        }
    }

    /// @dev Storage key for a flavored template: `subdomain#flavor`.
    ///      '#' is illegal in DNS labels, so flavored keys can never collide with real subdomains.
    function _flavorKey(string memory subdomain, string memory flavor) internal pure returns (string memory) {
        return string(abi.encodePacked(subdomain, "#", flavor));
    }

    /// @dev True if the string contains the reserved '#' separator.
    function _containsHash(string memory s) internal pure returns (bool) {
        bytes memory b = bytes(s);
        for (uint256 i = 0; i < b.length; i++) {
            if (b[i] == "#") return true;
        }
        return false;
    }

    /**
     * @notice Validate incoming fees exactly match ANY registered flavor for this
     *         domain/subdomain (all templates are flavors as of v43107)
     * @dev Called by ControllerFactory during deployment. The flavor used is implied by which
     *      template the fees matched — no flavor parameter and no Deployment struct change.
     * @dev Per-index revert strings were replaced by a bool matcher + FeeTemplateMismatch
     *      (bytecode economy; the UI performs its own field-level diff client-side).
     * @param incomingFees Fee structure from deployment request
     * @param domain Domain name
     * @param subdomain Subdomain name (empty string if none)
     * @return The same fees (if validation passes)
     */
    function validateFeesMatchTemplate(
        IFeeManager.EntityFeesWithNames[] memory incomingFees,
        string memory domain,
        string memory subdomain
    ) external view onlyAuthorizedContract returns (IFeeManager.EntityFeesWithNames[] memory) {
        if (incomingFees.length == 0) revert FeesArrayEmpty();

        // NOTE: no '#' check needed here (bytecode economy). A crafted subdomain like
        // "foo#X" may pass the exists-gate below (that slot is flavor X's flag), but its
        // OWN flavor list is always empty — setters forbid '#' — so the match loop does
        // zero iterations and the deployment reverts FeeTemplateMismatch regardless.

        // 🔒 SANITY: first entity must be a ROOT in the FeeManager hierarchy
        if (incomingFees[0].parent != address(0)) revert InvalidFirstFeeEntity();

        // 🔒 SECURITY: Validate first treasury is PLATFORM's PLATFORM TREASURY or TREASURER
        _validateFirstProjectFeeEntityIsPlatformTreasuryOrTreasurer(incomingFees[0].entityAddress);

        // Determine which template to validate against
        string memory validationDomain = bytes(domain).length == 0 ? BASE_DOMAIN : domain;

        // Plain-key gate: true iff the subdomain has >= 1 registered flavor
        // (zero flavors == zero templates == subdomain NOT authorized)
        if (!subdomainTemplateExists[validationDomain][subdomain]) revert FeeTemplateNotConfigured();

        // 🔒 EXACT MATCH VALIDATION against each registered flavor (incl. "BASE")
        string[] storage flavors = flavorsBySubdomain[validationDomain][subdomain];
        for (uint256 i = 0; i < flavors.length; i++) {
            if (_feesMatchTemplate(validationDomain, _flavorKey(subdomain, flavors[i]), incomingFees)) {
                return incomingFees;
            }
        }

        revert FeeTemplateMismatch();
    }

    /// @dev EXACT structural match (fee structure only, ignoring name/ID) of incoming fees
    ///      against the stored template under `key` (always `subdomain#flavor`).
    ///      Missing trailing feeValues/feeFlags slots are treated as zero on either side.
    function _feesMatchTemplate(
        string memory domain,
        string memory key,
        IFeeManager.EntityFeesWithNames[] memory incomingFees
    ) internal view returns (bool) {
        if (!subdomainTemplateExists[domain][key]) return false;

        IFeeManager.EntityFeesWithNames[] storage template = subdomainFeeTemplates[domain][key];
        if (incomingFees.length != template.length) return false;

        for (uint256 i = 0; i < incomingFees.length; i++) {
            IFeeManager.EntityFeesWithNames memory incoming = incomingFees[i];
            IFeeManager.EntityFeesWithNames memory expected = template[i];

            if (incoming.entityAddress != expected.entityAddress || incoming.parent != expected.parent) {
                return false;
            }

            uint256 maxVals = incoming.feeValues.length > expected.feeValues.length
                ? incoming.feeValues.length
                : expected.feeValues.length;
            uint256 maxFlags = incoming.feeFlags.length > expected.feeFlags.length
                ? incoming.feeFlags.length
                : expected.feeFlags.length;
            if (maxVals != maxFlags) return false;

            for (uint256 j = 0; j < maxVals; j++) {
                uint256 inVal = j < incoming.feeValues.length ? incoming.feeValues[j] : 0;
                uint256 exVal = j < expected.feeValues.length ? expected.feeValues[j] : 0;
                uint8 inFlag = j < incoming.feeFlags.length ? incoming.feeFlags[j] : 0;
                uint8 exFlag = j < expected.feeFlags.length ? expected.feeFlags[j] : 0;
                if (inVal != exVal || inFlag != exFlag) return false;
            }
        }
        return true;
    }

    /**
     * @notice Validate that the first treasury matches PLATFORM_CONTROLLER's PLATFORM_TREASURER
     * @dev Ensures all child controllers inherit the same PLATFORM_TREASURER as the platform
     */
    function _validateFirstProjectFeeEntityIsPlatformTreasuryOrTreasurer(address proposedRootFeeEntityAddress) internal view {
        // a platform smartcontract MAY not be a treasury, but it's good enough
        // becasue we later verify that treasury is matched in the template exactly.
        // so it will fail anyway if not an EXACT match.  This is just a sanity check
        // to ensure we fail that later check if the treasury template entity is not in the platform controller.
        bool isPlatformTreasurerOrTreasury = IController(PLATFORM_CONTROLLER).isOfficialDoubleEntityFast(KECCAK_TREASURY_ADMIN, proposedRootFeeEntityAddress, KECCAK_SMART_CONTRACT, proposedRootFeeEntityAddress, false);
        require(
            isPlatformTreasurerOrTreasury,
            "PlatformUniverse: First Proposed treasury must be PLATFORM Treasury or Treasurer"
        );
    }

    /**
     * @notice Get fee template for a subdomain
     * @dev v43107 LEGACY ALIAS: returns the DEFAULT_FLAVOR ("BASE") flavor's template
     *      (empty array if the subdomain has no "BASE" flavor — use getSubdomainFlavors
     *      to enumerate everything that exists).
     */
    function getSubdomainFeeTemplate(string memory subdomain, string memory domain)
        external view
        returns (IFeeManager.EntityFeesWithNames[] memory)
    {
        if (bytes(domain).length == 0) {
            domain = BASE_DOMAIN;
        }
        return subdomainFeeTemplates[domain][_flavorKey(subdomain, DEFAULT_FLAVOR)];
    }

    /**
     * @notice Get all flavor names registered for a domain/subdomain (empty array if none)
     */
    function getSubdomainFlavors(string memory subdomain, string memory domain)
        external view
        returns (string[] memory)
    {
        if (bytes(domain).length == 0) {
            domain = BASE_DOMAIN;
        }
        return flavorsBySubdomain[domain][subdomain];
    }

    /**
     * @notice Get a flavored fee template (empty flavor defaults to DEFAULT_FLAVOR "BASE")
     */
    function getSubdomainFeeTemplateFlavor(string memory subdomain, string memory domain, string memory flavor)
        external view
        returns (IFeeManager.EntityFeesWithNames[] memory)
    {
        if (bytes(domain).length == 0) {
            domain = BASE_DOMAIN;
        }
        if (bytes(flavor).length == 0) {
            flavor = DEFAULT_FLAVOR;
        }
        return subdomainFeeTemplates[domain][_flavorKey(subdomain, flavor)];
    }

    /**
     * @notice Get all registered base domains
     * @return Array of all domain strings that have been configured
     */
    function getAllDomains() external view returns (string[] memory) {
        return allDomains;
    }

    /**
     * @notice Get all subdomains for a domain
     */
    function getAllSubdomainsForDomain(string memory domain, uint256 start, uint256 count)
        external view
        returns (string[] memory)
    {
        if (bytes(domain).length == 0) {
            domain = BASE_DOMAIN;
        }
        string[] storage subs = subdomainsByDomain[domain];
        uint256 len = subs.length;
        // start > len  -> REVERT (out of range). start <= len -> CLIP count to remaining.
        if (start > len) revert IndexOutOfBounds();
        uint256 remaining = len - start;
        if (count == 0 || count > remaining) count = remaining;
        string[] memory out = new string[](count);
        for (uint256 i = 0; i < count; i++) {
            out[i] = subs[start + i];
        }
        return out;
    }

    /**
     * @notice Check if a subdomain template exists
     * @dev v43107: true iff the subdomain has >= 1 registered flavor (any title)
     */
    function hasSubdomainFeeTemplate(string memory subdomain, string memory domain)
        external view
        returns (bool)
    {
        if (bytes(domain).length == 0) {
            domain = BASE_DOMAIN;
        }
        return subdomainTemplateExists[domain][subdomain];
    }

    // ===== INTERNAL HELPERS =====
    // _uint2str removed in the flavors revision: it was only consumed by the per-index
    // revert strings in validateFeesMatchTemplate, which now uses the bool matcher
    // _feesMatchTemplate + FeeTemplateMismatch (bytecode freed pays for flavor support).
}

// Interface for IssueToken holder tracking
//interface IIssueToken {
//    function getHolderCount() external view returns (uint256);
//    function feeManager() external view returns (IFeeManager);
//    function FEE_CHAIN_TYPE() external view returns (bytes32);
//    function stableCoinAddress() external view returns (address);
//}

// Interface for ProjectRevenueTreasury settlement
//interface IProjectRevenueTreasury {
//    function settleHolderFees(address tokenAddress) external returns (uint256 _lifetimeHolderFeesPaid, uint256 feeAmount, uint256 newTotalSettled);
//}

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

@openzeppelin/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}

interfaces/IController.sol

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

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

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

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

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

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

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

    // Official Entity Functions
    function addOfficialEntity(string memory, address, string memory, string memory) external returns (bool);
    function addOfficialEntityWithValue(string memory, address, string memory, string memory, uint256) external returns (bool);
    function removeOfficialEntity(string memory, address) external returns (bool);
    function isOfficialEntity(string memory, address) external view returns (bool);
    function isOfficialEntityFast(bytes32, address) external view returns (bool);
    function isOfficialEntityPlusNotEntityFast(bytes32, address, bytes32, address, bool) external view returns (bool);
    function isOfficialDoubleEntityFast(bytes32, address, bytes32, address, bool) external view returns (bool);
    function isOfficialTripleEntityFast(bytes32, address, bytes32, address, bytes32, address, bool) external view returns (bool);
    function isOfficialQuadrupleEntityFast(bytes32, address,  bytes32, address, bytes32, address, bytes32, address, bool) external view returns (bool);
    function getOfficialEntity(string calldata, address) external view returns (OfficialEntityStruct memory);
    function getAllOfficialEntities(string calldata, bool) external view returns (OfficialEntityStruct[] memory);
    function init(address, string calldata) external;
    function openInit() external returns (bool);
    function closeInit() external returns (bool);
    function getEntityCount(bytes32) external view returns (uint256);

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

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

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

interfaces/IFeeManager.sol

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

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

    struct CalculatedEntityAmount {
        address entityAddress;
        uint256 amount;
    }

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

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

    // Per-root subtree freeze (Project Admin, after freezeDelay, reversible).
    // When set, blocks all mutations in that subtree for every caller (including platform).
    // Default chain type only — flat map, no bytes32 outer key.
    function freezeRootPath(address root, bool isFreeze) external returns (bool);
    function rootFamilyLocked(address root) external view returns (bool);
    
    // Query functions
    function isChainedEntity(string calldata chainType, address entity) external view returns (bool);
    
    function isChainedEntityFast(bytes32 hashedChainType, address entity) external view returns (bool);
    
    function getChainedEntity(string calldata chainType, address entity) external view returns (ChainedEntityStruct memory);
    
    function getActiveChainedEntities(string calldata chainType) external view returns (ChainedEntityStruct[] memory);
    
    // Fee calculation with hash (GAS-OPTIMIZED: ~200-300 gas savings vs string version)
    // Saves gas by avoiding ABI encoding overhead (96 bytes for string vs 32 bytes for hash)
    function calculateChainedAmounts(
        uint256 totalVal,
        uint256 maxPct,
        bytes32 feeTypeHash
    ) external view returns (
        CalculatedEntityAmount[] memory calculatedAmounts,
        uint256 totalAmount
    );
    
    // Fee calculation (advanced - custom chain type with uint8 feeType)
    function calculateChainedAmounts(
        bytes32 chainType,
        uint256 totalVal,
        uint256 maxPct,
        uint8 feeType
    ) external view returns (
        CalculatedEntityAmount[] memory calculatedAmounts,
        uint256 totalAmount
    );
    
    function distributeFees(
        CalculatedEntityAmount[] calldata calculatedFees,
        address payer,
        address paymentToken
    ) external returns (uint256 totalDistributed);
    
    function triggerNotify() external;
    
    // Fee type management
    function addFeeType(string calldata label) external;  // Auto-assigns next fee type
    function getAllFeeTypeLabels() external view returns (string[] memory);  // Batch getter for all labels
    function feeTypeLabels(uint8 index) external view returns (string memory);  // Query by array index 0-49!
    function feeTypeLabelToType(string calldata label) external view returns (uint8);  // Reverse mapping: label → type
    function getTypeForLabel(string calldata label) external view returns (uint8);  // Get type by label (reverts if undefined)
    function currentMaxFeeType() external view returns (uint8);  // Returns current max fee type (dynamic, starts at 7, max 50)
    function ABSOLUTE_MAX_FEE_TYPES() external view returns (uint8);  // Returns 50
    
    // 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": 400,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.