Skip to content
Verified contractExactUNLICENSED

Controller

Address0xbc33e5c36a1870da135265ea1472252d1de47372
Balance

0 ETH

 

Transactions

6

 

Compiler

solc 0.8.35

 

Same code

2 more contracts

 

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,171,891
Creation transaction
0xa61a960b68…166dbe5b63

contracts/Controller.sol

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

interface IERC20SymbolAndName {
        function symbol() external view returns (string memory);
        function name() external view returns (string memory);
}

/// @title Controller
/// @author Ken Silverman
/// @notice This contract is used to manage the official entities of all smart contract in the network.
contract Controller is Recoverable {

    uint16 public constant CONTRACT_VERSION = 43108; // v43108: + getOfficialEntity(type,label) overload + getOfficialEntityAddressFast(bytes32,label) — latest ACTIVE entity by label (dev bump; deployed BNB-first, ETH remains 43107 for now)





    // Flags are now stored per-fee in parallel feeFlags array: bit0=isPercent, bit1=isTaker

    // Custom errors (saves ~1KB vs require strings)
    error BadAddr();
    error Unauthorized();
    error BadType();
    error ValExceedsMax();
    error EntityLocked();
    error EntityPermLocked();
    error GlobalAddLocked();
    error ParentOff();
    error OnlySuper();
    error OnlyParent();
    error RootAuth();
    error ChildAuthFailed();
    error Need1stTrsy();
    error FstTrsyMustBeRoot();
    error Bad1stTrsry();
    error OnlyPT();
    error NoEntity();
    error EntityNotActive();
    error SelfRemoveOnly();
    error NotParentOrSelf();
    error InvalidEntity();
    error NotAncestor();
    error OnlySuperCanLockRoots();
    error MustWait6Months();
    error GlobalLockAlreadyActive();
    error NotAncestorOrSelf();
    error NeedsSuperEntity();
    error InvalidAdminType();
    error NoValRemove();
    error OnlyPlatformSuperOrSC();
    error OnlyProjectOfficialSC();
    error PlatformAccessAlreadyRevoked();
    error NoPlatformAccess();
    error OnlyPlatformSCOrOpenWindow();
    error MigrationIsSealed();   // v43107: migrate* called after sealMigration()
    error MigLenMismatch();      // v43107: adminTypes[] and entities[] length differ

    event UpdateOfficialEnt(
        address indexed entityAddress,
        address indexed updater,
        bytes32 indexed entityTypeHash,  // Hashed admin type (saves ABI encoding cost)
        string action,                   // Add,Remove,Reactivate,UpdateValue,Migrate,MigrateInactive (v43107: Remove swap-pops from activeList but the record persists in the map + deactivatedList)
        string fullNameOfEntityOrLabel,  // person's full name or "SC"
        string nationalIdOfEntity,       // registered to entity or SC address if entity is SC
        uint256 blockTimeStamp,          // block number of the event
        bool remainsActive,
        uint256 value  // Associated value (type(uint256).max = NO_VALUE)
    );

    event PlatformAccessPermanentlyRevoked(
        address indexed caller,
        bool byPlatformSuper,
        uint256 timestamp
    );

    // ============================================================
    // 📋 STRUCT DEFINITIONS (Duplicated in IController.sol for external use)
    // ============================================================
    // These structs are the SOURCE OF TRUTH for Controller.sol
    // They are DUPLICATED in IController.sol so other contracts can import
    // the interface without pulling in the full Controller contract.
    // IMPORTANT: Keep both definitions in sync!
    // ============================================================

    struct OfficialEntityStruct {
        string fullNameOfEntityOrLabel;
        string nationalIdOfEntity; // (if entity is a smart contract, leave empty or provide some other detail here.)
        address pubAddress;   // registered to entity or SC address if entity is SC
        uint256 blockNumber;
        uint256 blockTimestamp;
        bool active;
        uint256 value;  // Associated value (0-1,000,000 for absolute, or basis points for %, type(uint256).max = no value)
    }


    struct OfficialEntityGroup {
        mapping(address => OfficialEntityStruct) entitiesByAddress; // Maps entity address to its CURRENT details/state (O(1) auth)
        // v43107: entityList SPLIT into two DISJOINT arrays so the hot path
        // getAllOfficialEntities(type,false) is O(active) instead of O(all-ever).
        // INVARIANT: addr ∈ activeList ⟺ .active == true; addr ∈ deactivatedList
        // ⟺ .active == false. Reactivation swap-pops the addr OUT of
        // deactivatedList (O(1) via the index map), so no getter ever dedups.
        address[] activeList;                        // CURRENTLY-active addresses only (bounded, ~<=50/type; no index map needed)
        address[] deactivatedList;                   // CURRENTLY-deactivated addresses only (pruned on reactivation)
        mapping(address => uint256) deactivatedIndexPlus1; // addr -> (index in deactivatedList)+1; 0 = not present (O(1) membership + swap-pop)
        mapping(address => uint256[]) deactivationHistory; // addr -> timestamps of EVERY deactivation ever (survives reactivation; no event reliance)
    }

    // v43107: returned by getAllOfficialDeactivatedEntities — the current
    // (inactive) snapshot plus the full on-chain deactivation-timestamp history.
    struct DeactivatedEntityStruct {
        OfficialEntityStruct entity;        // snapshot from entitiesByAddress (active == false for returned rows)
        uint256[] deactivationTimestamps;   // full history of deactivation times for this address
    }


    struct AdminTypeRegistry {
       mapping(string  => bool)  isRegistered;     // internally a hash key but requires string for lookup
       mapping(bytes32 => bool)  isHashRegistered; // slightly faster pre-hahsed lookup
       string[] registeredAdminTypes;
       mapping(bytes32 => string) nameByHash;       // Reverse lookup from hash to original string
    }

    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
    }

    mapping(bytes32 => OfficialEntityGroup) private officialEntityGroupsByHash;


    // NEW structure to SUPPORT validateAdminType


     AdminTypeRegistry private adminTypeRegistry;

    // Project can lock itself by removing its super.
    // It can lock from platform for updates to SmartContract entities by permanently locking with this var
    // Platform may optionally permanently lock itself out of project as well.
    bool public platformAccessPermanentlyRevoked;
    uint256 public projectLockTimestamp;
    // address public remoteController; // Hub address for admin verification - ALWAYS "this" for now
    string public platformName;
    string public projectName;  // Project name — LATEST title (see setProjectName / getProjectNameHistory)
    string public projectId;    // Project ID (fixed at deployment)
    /// @notice Full title trail. [0] is the constructor title stamped with the deployment
    ///         time; every Super rename appends. `projectName` always mirrors the last entry.
    string[]  private _projectNameHistory;
    uint256[] private _projectNameSetAt;
    event ProjectNameUpdated(string previousName, string newName, address indexed by);
    // ⚠️ CRITICAL: deploymentTimestamp is NOT immutable to enable CREATE2 verification
    // Etherscan/BscScan verification fails for CREATE2 factory deployments when immutable values
    // (like block.timestamp) change between deployments, causing different bytecode each time.
    // Making this a regular storage variable allows deterministic bytecode for cross-chain CREATE2.
    uint256 public deploymentTimestamp; // Deployment time - used for 6-month lock delay

    /// @notice The platform controller for this project (for validating platform treasurer and factory)
    /// @dev For the platform's own controller, this points to itself. For project controllers, points to platform controller.
    address public immutable PLATFORM_CONTROLLER;

    // Entity type string constants - reused to save bytecode
    string private constant STR_TREASURY_ADMIN = "TreasuryAdmin";
    string private constant STR_SMART_CONTRACT = "SmartContract";
    string private constant STR_SUPER = "Super";
    string private constant STR_TOKEN = "TokenAdmin";
    string private constant STR_REGISTRAR = "Registrar";
    string private constant STR_LIQUIDITY_POOL = "LiquidityPool";
    string private constant STR_PLATFORM_CONTROLLER = "PLATFORM_CONTROLLER";
    string private constant STR_THIRD_PARTY_REGISTRAR = "ThirdPartyRegistrar";

    // Keccak hashes - calculated once to save bytecode
    bytes32 private constant KECCAK_TREASURY_ADMIN = keccak256(bytes(STR_TREASURY_ADMIN));
    bytes32 private constant KECCAK_SMART_CONTRACT = keccak256(bytes(STR_SMART_CONTRACT));
    bytes32 private constant KECCAK_SUPER_ADMIN = keccak256(bytes(STR_SUPER));
    bytes32 private constant KECCAK_PLATFORM_CONTROLLER = keccak256(bytes(STR_PLATFORM_CONTROLLER));

    uint256 public constant NO_VALUE = type(uint256).max;  // Sentinel value indicating "no value set"
    uint256 public constant MAX_VALUE = 1000000000000;  // Maximum allowed value: 1,000,000 USD (in USDC atomic units with 6 decimals: 1M × 1,000,000)

    // String action constants for UpdateOfficialEnt event
    string private constant ACTION_STR_ADD = "Add";
    string private constant ACTION_STR_REMOVE = "Remove";

    // Deprecated in favor of platform super tx.origin in init() for bootstrap  or
    // in addOfficialEntity() : msg.sender is existing SmartContract officialEntity, or if self platfomrm controller AND entity is SmartContract,
    // msg.sender is platform super ortherwise project super.
    //modifier onlySuper() {
    //    if (!isOfficialEntityFast(KECCAK_SUPER_ADMIN, tx.origin)) revert Unauthorized();
    //    _;
    //}


    // Warning! Any official "Super" can call addEntity directly. This is NOT a first line of defense against that.
    //  The only defense there is to make sure your official SCs have their own calls to this controller’s
    //  isOfficialEntity(“Super”) for example BEFORE calling addEntity() or removeEntity()
    //  init() LOCKS this Controller to only allowing TreasAdmins to adding official SCs to begin with.
    //  REMOTE case now allows a smartContract caller unless tx.origin is used
    //  use case of checking that the original human sender is authorized (even through non-official contract calls)
    //  may be one of the few legitimate uses of tx.origin
    // ✓ To register as official smartContract → You need to be called by an official entity
    // ✗ because you can't be an official entity smartContract → Until that smatcontract calls init() via its own constructor
    //  therefore we must USE tx.origin for initial registration of smartContracts as a bootstrap
    // Deprecated in favor of platform super or platform smart contract entities.
    //modifier onlySuperOrSCExecutives() {
    //    bool temp = isOfficialEntityFast(KECCAK_SUPER_ADMIN, tx.origin) ||
    //                isOfficialEntityFast(KECCAK_SMART_CONTRACT, msg.sender);
    //    if (!temp) revert Unauthorized();
    //    _;  // run the code block referencing this modifier
    //}


    // to meet the 24K limit, BaseTreasury is now instantiated FIRST - however its concept remains the same - as a BASE class
    // for ElasticTreasuryHUB and ElasticTreasurySPOKE  MasterHub is now an optional, later passed "controller" that must be
    // a separate instantiatedController. This will NOT be used for our needs yet.  In other words, controller is ALWAYS
    // this for now.  initialEntitys are project super entity.  NOT the same as the platform chained entity.
    constructor(
        address projectSuperAddress,
        address platformControllerAddress,
        string memory projectSuperName,
        string memory projectSuperId,
        string memory _projectName,
        string memory _projectId
    ) Recoverable(address(this)) {
        projectName = _projectName;  // latest title (renamable by Super via setProjectName)
        _projectNameHistory.push(_projectName);
        _projectNameSetAt.push(block.timestamp); // first title carries the deployment time
        projectId = _projectId;      // Store immutable
        deploymentTimestamp = block.timestamp; // Store for 6-month lock delay calculation

        // **Reject if projectSuperAddress is 0x0000**
        if (projectSuperAddress == address(0)) revert NeedsSuperEntity();

        // Bootstrap case: address(0) means "self-referential" (platform's own controller)
        // For project controllers: factory passes the platform controller address
        PLATFORM_CONTROLLER = (platformControllerAddress == address(0)) ? address(this) : platformControllerAddress;

        // Derive platformName: if self-referential, use projectName; otherwise fetch from platform controller
        if (PLATFORM_CONTROLLER == address(this)) {
            // This IS the platform controller - use projectName as platformName
            platformName = _projectName;
        } else {
            // This is a project controller - fetch platformName from the platform controller
            // Cast to Controller (not IController) since platformName is a public variable with auto-generated getter
            platformName = Controller(PLATFORM_CONTROLLER).platformName();
        }

        // Register default admin types  (not essential, self-adding, here for dynamic UX only when empty for clarity)
        string[8] memory defaultTypes = [STR_TREASURY_ADMIN, STR_SMART_CONTRACT, STR_SUPER, STR_PLATFORM_CONTROLLER, STR_TOKEN, STR_REGISTRAR, STR_THIRD_PARTY_REGISTRAR, STR_LIQUIDITY_POOL];
        for (uint256 i = 0; i < defaultTypes.length; i++) {
            addAdminType(defaultTypes[i]);
        }
        // Use passed entity name/ID or defaults if empty
        string memory superName = bytes(projectSuperName).length > 0 ? projectSuperName : "Multi-Sig Officer";
        string memory superID = bytes(projectSuperId).length > 0 ? projectSuperId : "Multi-Sig Execs";
        addOfficialEntityNow(KECCAK_SUPER_ADMIN, projectSuperAddress, superName, superID, NO_VALUE);
        addOfficialEntityNow(KECCAK_TREASURY_ADMIN, projectSuperAddress, superName, superID, NO_VALUE);

        // Register platform controller as official entity (for reference and validation)
        addOfficialEntityNow(KECCAK_PLATFORM_CONTROLLER, PLATFORM_CONTROLLER, platformName, STR_PLATFORM_CONTROLLER, NO_VALUE);

        // Fee hierarchies are now managed by FeeManager (deployed separately)
    }


    // 🆕 Init window state for constructor self-registration during factory deployAll
    bool public initWindowOpen = false;
    address public initWindowOrigin;  // tx.origin authorized during window

    /// @notice Open init window to allow constructor self-registration (factory only)
    /// @dev Window is tied to tx.origin - only contracts deployed by that EOA can register
    /// @return success True if opened, false if already open
    function openInit() external returns (bool success) {
        if (platformAccessPermanentlyRevoked) revert NoPlatformAccess();

        // Only platform SmartContract can open - REVERT if unauthorized
        if (!isPlatformAdmin(msg.sender, KECCAK_SMART_CONTRACT)) {
            revert Unauthorized();
        }

        if (initWindowOpen) return false; // Already open (benign)

        initWindowOpen = true;
        initWindowOrigin = tx.origin;  // Capture deployer's EOA
        return true;
    }

    /// @notice Close init window (callable by anyone, no checksum needed)
    /// @return success True if closed successfully, false if not open
    function closeInit() external returns (bool success) {
        if (!initWindowOpen) return false; // Not open (benign)

        initWindowOpen = false;
        initWindowOrigin = address(0);
        return true;
    }

    /// @notice Get CURRENT active entity count for a type (v43107: active-only).
    /// @dev Semantic change from pre-43107 (which counted all-ever). No on-chain
    ///      caller depends on this; it is analytics-only.
    function getEntityCount(bytes32 adminTypeHash) external view returns (uint256) {
        return officialEntityGroupsByHash[adminTypeHash].activeList.length;
    }

    /// @notice Overloaded count. includeDeactivated=false → active only;
    ///         true → active + currently-deactivated (O(1)).
    /// @dev EXACT unique-entity tally: the two lists are DISJOINT because
    ///      reactivation prunes the address out of deactivatedList.
    function getEntityCount(bytes32 adminTypeHash, bool includeDeactivated) external view returns (uint256) {
        OfficialEntityGroup storage group = officialEntityGroupsByHash[adminTypeHash];
        return includeDeactivated
            ? group.activeList.length + group.deactivatedList.length
            : group.activeList.length;
    }

    /// @notice EXACT count of CURRENTLY-deactivated entities for a type (O(1));
    ///         also the pagination bound for getAllOfficialDeactivatedEntities.
    /// @dev Per-address lifetime deactivation history remains available via the
    ///      deactivationTimestamps array returned with each paginated row.
    function getDeactivatedEntityCount(bytes32 adminTypeHash) external view returns (uint256) {
        return officialEntityGroupsByHash[adminTypeHash].deactivatedList.length;
    }

    /// @notice Register a SmartContract entity during deployment/initialization
    /// @dev 🔒 SECURITY: Three authorized paths:
    ///  A) Manual Mode: tx.origin is super ONLY if THIS is the platform controller (self-only)
    ///  B) Auto Mode: msg.sender is registered as a SmartContract in platform controller
    ///  C) Constructor Mode: init window is open (checksum on closeInit protects against exploits)
    ///      NOTE: Originally checked code.length == 0 to enforce constructor-only, but removed
    ///            because complex call chains or post-constructor init may be legitimate.
    ///            closeInit() checksum is the real security mechanism.
    /// @dev Contracts self-register via ExecutivePeerTreasury constructor calling init()
    // tx.origin usage is STRICTLY limited to platform bootstrap.
    // After Super removal / lock, (upon platform maturity) no tx.origin–based authorization remains.
    // However platform super is also used to add new features to projects.  Once removed, new existing tokens will
    // be able to receive new features, but they will be 100% sovereign at that time.
    // Regarding any EXISTING platform smartcontract to have the authority to add new entities:
    //   "Platform SmartContract compromise implies total system compromise by design."
    function init(address officialSmartContractAddress, string calldata contractName) external  {   // onlySuperOrSCExecutives
        if (platformAccessPermanentlyRevoked) revert NoPlatformAccess();
        // 🔒 SECURITY: Three authorized paths:
        // A) Manual Mode: tx.origin is super ONLY if THIS is the platform controller (self-only)
        // B) Auto Mode: msg.sender is registered as a SmartContract in platform controller
        // C) Constructor Mode: init window open (no code.length check - see docstring)

        // Check A: Is this platform controller and tx.origin a super? (manual deployment to platform only)
        bool isPlatformSuperSelf = (PLATFORM_CONTROLLER == address(this))
            && isOfficialEntityFast(KECCAK_SUPER_ADMIN, tx.origin);

        // Check B: Is msg.sender a registered Platform SmartContract? (factory deployment)
        bool isOfficialPlatformSmartContract = false;
        if (!isPlatformSuperSelf) {
            try IController(PLATFORM_CONTROLLER).isOfficialEntityFast(KECCAK_SMART_CONTRACT, msg.sender) returns (bool result) {
                isOfficialPlatformSmartContract = result;
            } catch {
                // Not registered as factory
            }
        }

        // Check C: Init window open (checksum validation happens on closeInit)
        // Removed: && officialSmartContractAddress.code.length == 0
        // Reason: May prevent legitimate post-constructor or complex call-chain scenarios
            // Check C: Init window open AND caller's tx.origin matches window origin
            // SECURITY: Only contracts deployed by the authorized origin can register during window
            bool isConstructorDuringOpenWindow = initWindowOpen && tx.origin == initWindowOrigin;

        if (!isPlatformSuperSelf && !isOfficialPlatformSmartContract && !isConstructorDuringOpenWindow) {
            revert OnlyPlatformSCOrOpenWindow();
        }

        addOfficialEntityNow(KECCAK_SMART_CONTRACT, officialSmartContractAddress, contractName, "", NO_VALUE);  // may exist, if token, symbol will be added.
    }

    /**
    * ⚠️ WARNING:
    * After this function is called:
    * - NO SmartContract enity can be added to the project
    * - NO SmartContract centity an be removed from the project
    * - YES OTHER admin entities can continue to be added, removed, or modified until the PROJECT removes its own SUPER!
    * - This action is PERMANENT and IRREVERSIBLE
    *
    * This exists to provide cryptographic finality guarantees
    * to investors, regulators, and counterparties.
    */
    function lockPlatformAccessPermanently() external {
        if (platformAccessPermanentlyRevoked) revert PlatformAccessAlreadyRevoked();
        bool isProjectSuper = isOfficialEntityFast(KECCAK_SUPER_ADMIN, msg.sender);
        bool isPlatformSuper = isPlatformAdmin(msg.sender, KECCAK_SUPER_ADMIN);
        if (!isProjectSuper && !isPlatformSuper) {
            revert Unauthorized();
        }
        platformAccessPermanentlyRevoked = true;
        projectLockTimestamp = block.timestamp;
        emit PlatformAccessPermanentlyRevoked(
            msg.sender,
            isPlatformSuper,
            block.timestamp
        );
    }




    /* NOT USED
    function remotelyManage(address _controller) external onlySuperOrSCExecutives {
        bool isRemotelyManaged = (_controller != address(0) && _controller != address(this));
        if (isRemotelyManaged) {
            remoteController = _controller;
        }
        else {
            remoteController = address(this);  // not used if isRemotelyManaged is false
        }
        changeController(remoteController);
    } */



    //function doesRemoteControllerManageAllOfficials() internal view returns (bool) {
    //    return controller != address(this);
    //}



    ///
    //   OFFICIAL ENTITIES
    //
    //



        // Inline modifier replaces validateAdminType function (saves ~150 bytes)
        modifier validAdmin(bytes32 adminHash) {
            if (!adminTypeRegistry.isHashRegistered[adminHash]) revert InvalidAdminType();
            _;
        }


        function addAdminType(string memory adminType) internal returns (bool) {
            if (!adminTypeRegistry.isRegistered[adminType]) {
                // to support remote case, let a TreasuryAdmin add too, since “SmartContract” is not sensed for remote
                // chained transaction caller:  EOA ⇒ contract A == > contract B (here) ⇒ remote controller (A not sensed)
                // require(isOfficialEntity(“SmartContract”,msg.sender),”Only official SC can add new Officl type”);
                bytes32 hash = keccak256(bytes(adminType));
                adminTypeRegistry.isRegistered[adminType] = true;
                adminTypeRegistry.isHashRegistered[hash] = true;
                adminTypeRegistry.nameByHash[hash] = adminType;
                adminTypeRegistry.registeredAdminTypes.push(adminType);
                return true;
            }
            return false;
        }


        // Retrieve all registered admin types
        function getRegisteredAdminTypes() external view returns (string[] memory) {
            return adminTypeRegistry.registeredAdminTypes;
        }

        /**
         * @notice Add an official entity (Super permission required)
         * @dev SPECIAL SECURITY: No new types can be added except by EXISTING SmartContract entities or platform super entities.
         *      Platform super cannot remove, adding by platform superis reserved for future feature updates. However no existing features may be modified.
         *      This creates a higher security tier for critical platform operations.
         * @param adminType Type of entity (e.g., "TreasuryAdmin", "Super", "SmartContract")
         * @param entityAddr Address of the entity to add
         * @param label Human-readable name
         * @param nationalIdOrSC National ID or smart contract identifier
         */
       function addOfficialEntity(string calldata adminType, address entityAddr, string calldata label,string calldata nationalIdOrSC) external returns (bool) { // onlySuper
            bytes32 adminHash = keccak256(bytes(adminType));
            // if (!adminTypeRegistry.isHashRegistered[adminHash]) revert InvalidAdminType();
            // SECURITY: PLATFORM_CONTROLLER can only be managed by existing PLATFORM_CONTROLLER super
            // (although platformController is managed outside officialentities map. It is stored here prery much unnecessarily so the check is moot except to avoid confusion)
            // 🔒 SECURITY: No SmartContract entity type can be added except by PLATFORM_CONTROLLER super or EXISTING SmartContract official entities
            // Prevents projects from adding rogue contracts that are not platform authorized or compatible and may bypass fees
            // These next conditions not relevant anymore since only EXISTING smart contract entities OR platform super entities can add new entities.
            bool spec = (adminHash == KECCAK_PLATFORM_CONTROLLER || adminHash == KECCAK_SMART_CONTRACT);
            bool isOfclSC = isOfficialEntityFast(KECCAK_SMART_CONTRACT, msg.sender);
            bool needsLord = spec && !isOfclSC; // specifically the controller factory is all that should add outside of init
            if (needsLord) {
                if (platformAccessPermanentlyRevoked) revert NoPlatformAccess();
                if (!isPlatformAdmin(msg.sender, KECCAK_SMART_CONTRACT) && !isPlatformAdmin(msg.sender, KECCAK_SUPER_ADMIN)) revert OnlyPlatformSuperOrSC();
            }
            else {
                // ✅ FIX: Allow SmartContracts OR Super Admins to add regular entities
                if (!isOfclSC && !isOfficialEntityFast(KECCAK_SUPER_ADMIN, msg.sender)) revert OnlySuper();
            }
            // ✅ auto-register new admin type if caller is authorized (per rules above)
            // only if the caller is an existing SmartContract official entity
             if (!adminTypeRegistry.isHashRegistered[adminHash]) {
                if (isOfclSC) {
                    addAdminType(adminType); // internal; will mark isHashRegistered + push into list
                }
                else {
                    revert InvalidAdminType();
                }
                // (adminHash remains correct because it's keccak256(adminType))
            }
            return addOfficialEntityNow(adminHash, entityAddr, label, nationalIdOrSC, NO_VALUE);
        }

        // Add official entity with an associated value
        function addOfficialEntityWithValue(string calldata adminType, address entityAddr, string calldata label, string calldata nationalIdOrSC, uint256 value) external  returns (bool) { // onlySuper
            bytes32 adminHash = keccak256(bytes(adminType));
            if (value > MAX_VALUE) revert ValExceedsMax();
            // if (!adminTypeRegistry.isHashRegistered[adminHash]) revert InvalidAdminType();
            // SECURITY: PLATFORM_CONTROLLER can only be managed by existing PLATFORM_CONTROLLER super
            // 🔒 SECURITY: No entity can be added except by PLATFORM_CONTROLLER super or EXISTING SmartContract official entities
            // Prevents projects from adding rogue tokens/contracts that bypass fees
            bool spec = (adminHash == KECCAK_PLATFORM_CONTROLLER || adminHash == KECCAK_SMART_CONTRACT);
            bool isOfclSC = isOfficialEntityFast(KECCAK_SMART_CONTRACT, msg.sender);
            bool needsLord = spec && !isOfclSC; // specifically the controller factory is all that should add outside of init
            if (needsLord) {
                if (platformAccessPermanentlyRevoked) revert NoPlatformAccess();
                if (!isPlatformAdmin(msg.sender, KECCAK_SMART_CONTRACT) && !isPlatformAdmin(msg.sender, KECCAK_SUPER_ADMIN)) revert OnlyPlatformSuperOrSC();
            }
            else {
                // ✅ FIX: Allow SmartContracts OR Super Admins to add regular entities
                if (!isOfclSC && !isOfficialEntityFast(KECCAK_SUPER_ADMIN, msg.sender)) revert OnlySuper();
            }
            // ✅ auto-register new admin type if caller is authorized (per rules above)
            // only if the caller is an existing SmartContract official entity
            if (!adminTypeRegistry.isHashRegistered[adminHash]) {
                if (isOfclSC) {
                    addAdminType(adminType); // internal; will mark isHashRegistered + push into list
                }
                else {
                    revert InvalidAdminType();
                }
                // (adminHash remains correct because it's keccak256(adminType))
            }
            return addOfficialEntityNow(adminHash, entityAddr, label, nationalIdOrSC, value);
        }


       function addOfficialEntityNow(bytes32 adminHash, address entityAddr, string memory label, string memory nationalIdOrSCSymbol, uint256 value) internal returns (bool) {
            //if (doesRemoteControllerManageAllOfficials()) {
            //    // For remote controller, route based on whether value is set
            //    if (value == NO_VALUE) {
            //        return Controller(controller).addOfficialEntity(adminType, entityAddr, label, nationalIdOrSCSymbol);
            //    } else {
            //        return Controller(controller).addOfficialEntityWithValue(adminType, entityAddr, label, nationalIdOrSCSymbol, value);
            //    }
            //}
            if (entityAddr == address(0)) revert BadAddr();
            if (bytes(label).length == 0) {
                if (entityAddr.code.length > 0) {
                    try IERC20SymbolAndName(entityAddr).name() returns (string memory s) {
                        label = bytes(s).length > 0 ? s : "SC not token";
                    } catch {
                        label = "SC not token";
                    }
                }
                else {
                    label = "SC not token";
                }
            }
            if (bytes(nationalIdOrSCSymbol).length == 0) {
                if (entityAddr.code.length > 0) {
                    try IERC20SymbolAndName(entityAddr).symbol() returns (string memory s) {
                        nationalIdOrSCSymbol = bytes(s).length > 0 ? s : "SC no token symbol";
                    } catch {
                        nationalIdOrSCSymbol = "SC not token";
                    }
                } else {
                    nationalIdOrSCSymbol = "wallet not SC";
                }
            }
            // Admin type already validated by caller - use hash directly
            OfficialEntityGroup storage group = officialEntityGroupsByHash[adminHash];

            // Check if entity already exists in mapping (even if inactive)
            bool entityExists = group.entitiesByAddress[entityAddr].pubAddress != address(0);

            if (entityExists) {
                // Entity exists - either active or inactive
                if (group.entitiesByAddress[entityAddr].active) {
                    // Entity is active - handle value updates
                    uint256 existingValue = group.entitiesByAddress[entityAddr].value;

                    // Prevent changing from value to NO_VALUE or vice versa
                    if ((existingValue == NO_VALUE && value != NO_VALUE) ||
                        (existingValue != NO_VALUE && value == NO_VALUE)) revert NoValRemove();

                    // Allow updating to a different value (both must be real values)
                    if (value != NO_VALUE && existingValue != value) {
                        group.entitiesByAddress[entityAddr].value = value;
                        emit UpdateOfficialEnt(entityAddr, msg.sender, adminHash, "UpdateValue", label, nationalIdOrSCSymbol, block.timestamp, true, value);
                        return true;
                    }

                    return false;  // Already exists with same value
                } else {
                    // Entity exists but is INACTIVE - reactivate. Push back onto
                    // activeList and PRUNE from deactivatedList (O(1) swap-pop via
                    // the index map, which is kept in sync). Its deactivationHistory
                    // is preserved forever in the history map.
                    group.entitiesByAddress[entityAddr].fullNameOfEntityOrLabel = label;
                    group.entitiesByAddress[entityAddr].nationalIdOfEntity = nationalIdOrSCSymbol;
                    group.entitiesByAddress[entityAddr].blockNumber = block.number;
                    group.entitiesByAddress[entityAddr].blockTimestamp = block.timestamp;
                    group.entitiesByAddress[entityAddr].active = true;
                    group.entitiesByAddress[entityAddr].value = value;
                    group.activeList.push(entityAddr);
                    _removeFromDeactivatedList(group, entityAddr);

                    emit UpdateOfficialEnt(entityAddr, msg.sender, adminHash, "Reactivate", label, nationalIdOrSCSymbol, block.timestamp, true, value);
                    return true;
                }
            }

            // Brand new entity - add to mapping AND active array
            group.entitiesByAddress[entityAddr] = OfficialEntityStruct(label, nationalIdOrSCSymbol, entityAddr, block.number, block.timestamp, true, value);
            group.activeList.push(entityAddr);

            emit UpdateOfficialEnt(entityAddr, msg.sender, adminHash, ACTION_STR_ADD, label, nationalIdOrSCSymbol, block.timestamp, true, value);
            return true;
        }

        function removeOfficialEntity(string calldata adminType, address entityAddr) external returns (bool) { // onlySuper
            bytes32 adminHash = keccak256(bytes(adminType));
            bool spec = (adminHash == KECCAK_PLATFORM_CONTROLLER || adminHash == KECCAK_SMART_CONTRACT);
            if (platformAccessPermanentlyRevoked && spec) revert NoPlatformAccess(); // or a project trying to remove a SmartContract entity
            if (entityAddr == address(0)) revert BadAddr();

            if (!adminTypeRegistry.isHashRegistered[adminHash]) revert InvalidAdminType();
             // 🔒 SECURITY: No SmartContract entity can be removed except by EXISTING SmartContract official entities
             //  UNLESS the controller is also the platform controller (self-only).
            //  this check was prevetning smartContracts from removing themselves in the 6 monthe grace perios,
            // stupid becaseu platforrm admin still can. this prevents the controllerFactory from removingh itself afer its done!!!
            // this i now fixed fro fUTTURE version.  This leniency is
            // still pre-empted by the fact that if not spec, you still gotta be a project super to remove an entuty!
            bool needsLord = spec; // REMOVED && for NEXT version x.x.x.8 && !isOfficialEntityFast(KECCAK_SMART_CONTRACT, msg.sender);
            if (needsLord) {
                // Project revamps/updates handled via platform permissions to remove old SmartContract
                // entities (which projects can revoke via permLock)
                if (!isPlatformAdmin(msg.sender, KECCAK_SMART_CONTRACT) && !isPlatformAdmin(msg.sender, KECCAK_SUPER_ADMIN)) revert OnlyPlatformSuperOrSC();
            }
            else {
                // 🔒 SECURITY: SmartContracts CANNOT remove regular entities (unlike addOfficialEntity where they can add)
                // SCs NEED add permission for bootstrap/initialization, but NEVER need remove permission
                if (!isOfficialEntityFast(KECCAK_SUPER_ADMIN, msg.sender)) revert OnlySuper();
            }

            OfficialEntityGroup storage group = officialEntityGroupsByHash[adminHash];
            if (!group.entitiesByAddress[entityAddr].active) {
                return false; // not currently active → ignore (unchanged behavior)
            }
            // v43107: mark inactive, REMOVE from activeList (swap-pop), record the
            // deactivation timestamp, and append to deactivatedList. The addr
            // cannot already be in deactivatedList (it was active ⇒ pruned on its
            // last reactivation); the index-map guard is kept as cheap insurance.
            group.entitiesByAddress[entityAddr].active = false;
            _removeFromActiveList(group, entityAddr);
            group.deactivationHistory[entityAddr].push(block.timestamp);
            if (group.deactivatedIndexPlus1[entityAddr] == 0) {
                group.deactivatedList.push(entityAddr);
                group.deactivatedIndexPlus1[entityAddr] = group.deactivatedList.length; // index+1
            }
            emit UpdateOfficialEnt(entityAddr, msg.sender, adminHash, ACTION_STR_REMOVE,group.entitiesByAddress[entityAddr].fullNameOfEntityOrLabel,group.entitiesByAddress[entityAddr].nationalIdOfEntity,block.timestamp,false,group.entitiesByAddress[entityAddr].value);
            return true;
        }

        /// @dev Swap-pop an address out of a group's activeList. O(active) scan;
        ///      activeList is bounded (~<=50/type) so no index map is needed.
        function _removeFromActiveList(OfficialEntityGroup storage group, address entityAddr) private {
            uint256 n = group.activeList.length;
            for (uint256 i = 0; i < n; i++) {
                if (group.activeList[i] == entityAddr) {
                    group.activeList[i] = group.activeList[n - 1];
                    group.activeList.pop();
                    return;
                }
            }
        }

        /// @dev O(1) swap-pop an address out of a group's deactivatedList using
        ///      the index map, re-syncing deactivatedIndexPlus1 for the element
        ///      moved into the vacated slot. No-op if not present.
        function _removeFromDeactivatedList(OfficialEntityGroup storage group, address entityAddr) private {
            uint256 idxPlus1 = group.deactivatedIndexPlus1[entityAddr];
            if (idxPlus1 == 0) return; // not present
            uint256 idx = idxPlus1 - 1;
            uint256 lastIdx = group.deactivatedList.length - 1;
            if (idx != lastIdx) {
                address moved = group.deactivatedList[lastIdx];
                group.deactivatedList[idx] = moved;
                group.deactivatedIndexPlus1[moved] = idx + 1; // keep map in sync
            }
            group.deactivatedList.pop();
            group.deactivatedIndexPlus1[entityAddr] = 0;
        }

        function isOfficialEntityFast(bytes32 hashedAdminType, address entityAddr) public view returns (bool) {
            if (entityAddr == address(0)) revert BadAddr();
             if (!adminTypeRegistry.isHashRegistered[hashedAdminType]) revert InvalidAdminType();
            return officialEntityGroupsByHash[hashedAdminType].entitiesByAddress[entityAddr].active;
        }

        function isOfficialEntity(string calldata adminType, address entityAddr) external view returns (bool) {
            if (entityAddr == address(0)) revert BadAddr();
            bytes32 adminHash = keccak256(bytes(adminType));
            if (!adminTypeRegistry.isHashRegistered[adminHash]) revert InvalidAdminType();
            return officialEntityGroupsByHash[adminHash].entitiesByAddress[entityAddr].active;
        }

        /// @notice Check if an address is a TreasuryAdmin in the platform controller
        /// @dev This is the new standard way to check platform treasurer privileges
        /// @param addr The address to check
        /// @return true if the address is a TreasuryAdmin in the platform controller
        function isPlatformAdmin(address addr, bytes32 adminHash) public view returns (bool) {
            // Bootstrap case: if we ARE the platform controller, check locally
            if (PLATFORM_CONTROLLER == address(this)) {
                return isOfficialEntityFast(adminHash, addr);
            }

            // Otherwise, check if addr is TreasuryAdmin in the platform controller
            return  IController(PLATFORM_CONTROLLER).isOfficialEntityFast(adminHash, addr);
        }

        function isPlatform() external view returns (bool) {
            return address(this) == PLATFORM_CONTROLLER;
        }

        // ========== PROJECT TITLE (Super-renamable, full trail kept) ==========

        /// @notice Rename the project (Super only). The previous title is kept in the
        ///         trail; `projectName` returns the new one. For the PLATFORM controller
        ///         `platformName` is updated too (it mirrored projectName at deploy).
        ///         No version bump: additive, no storage-layout impact on prior slots.
        function setProjectName(string calldata newName) external {
            if (!isOfficialEntityFast(KECCAK_SUPER_ADMIN, msg.sender)) revert OnlySuper();
            if (bytes(newName).length == 0) revert BadAddr();
            string memory prev = projectName;
            projectName = newName;
            if (PLATFORM_CONTROLLER == address(this)) platformName = newName;
            _projectNameHistory.push(newName);
            _projectNameSetAt.push(block.timestamp);
            emit ProjectNameUpdated(prev, newName, msg.sender);
        }

        /// @notice Title trail, oldest first. names[0] is the constructor title and
        ///         setAt[0] its deployment timestamp; the last entry == projectName.
        function getProjectNameHistory() external view returns (string[] memory names, uint256[] memory setAt) {
            return (_projectNameHistory, _projectNameSetAt);
        }

        // TODO: overload this with a boolean to allow inactive as well
        function getOfficialEntity(string calldata adminType, address entityAddr) external view returns (OfficialEntityStruct memory) {
            if (entityAddr == address(0)) revert BadAddr();
            bytes32 adminHash = keccak256(bytes(adminType));
            if (!adminTypeRegistry.isHashRegistered[adminHash]) revert InvalidAdminType();
            OfficialEntityStruct storage entity = officialEntityGroupsByHash[adminHash].entitiesByAddress[entityAddr];
            if (!entity.active) revert NoEntity();
            return entity;
        }

        /// @dev v43108: shared scan behind BOTH label-lookup externals — returns
        ///      the address of the LATEST ACTIVE entity of the type whose label
        ///      (fullNameOfEntityOrLabel) hashes to labelHash, or address(0) when
        ///      no active match. "Latest" = highest blockTimestamp among active
        ///      matches; ties resolve to the later activeList position
        ///      (reactivation both refreshes blockTimestamp and re-appends, so a
        ///      re-added label always beats an older survivor). O(active) loop —
        ///      activeList is bounded (~<=50/type), so this is a cheap view.
        function _latestActiveEntityByLabel(bytes32 adminHash, bytes32 labelHash) internal view returns (address bestAddr) {
            OfficialEntityGroup storage group = officialEntityGroupsByHash[adminHash];
            uint256 n = group.activeList.length;
            uint256 bestTs = 0;
            for (uint256 i = 0; i < n; i++) {
                OfficialEntityStruct storage e = group.entitiesByAddress[group.activeList[i]];
                if (keccak256(bytes(e.fullNameOfEntityOrLabel)) == labelHash && e.blockTimestamp >= bestTs) {
                    bestTs = e.blockTimestamp;
                    bestAddr = group.activeList[i];
                }
            }
        }

        /// @notice v43108: overload — full struct of the LATEST ACTIVE entity of
        ///         a type by exact label match. String-keyed convenience getter,
        ///         mainly for off-chain callers (JS/ethers) where strings are free.
        /// @dev Reverts NoEntity() when no ACTIVE entity carries the label
        ///      (mirrors the address-keyed overload's not-found behavior).
        ///      ABI signature for external tooling: getOfficialEntity(string,string).
        function getOfficialEntity(string calldata adminType, string calldata label) external view returns (OfficialEntityStruct memory) {
            bytes32 adminHash = keccak256(bytes(adminType));
            if (!adminTypeRegistry.isHashRegistered[adminHash]) revert InvalidAdminType();
            address a = _latestActiveEntityByLabel(adminHash, keccak256(bytes(label)));
            if (a == address(0)) revert NoEntity();
            return officialEntityGroupsByHash[adminHash].entitiesByAddress[a];
        }

        /// @notice v43108: bytecode-lean variant for ON-CHAIN callers, following
        ///         the isOfficialEntityFast(bytes32,...) convention: takes the
        ///         PRE-HASHED admin type (callers bake a bytes32 constant instead
        ///         of a string literal — smaller bytecode, no runtime hashing of
        ///         the type) and returns ONLY the address (no struct ABI-copy).
        /// @dev Returns address(0) when no ACTIVE entity carries the label — a
        ///      normal outcome, NOT a revert, exactly like isOfficialEntityFast
        ///      returning false. Revert-wanting callers pay one cheap
        ///      `if (a == address(0)) revert ...;` with THEIR OWN error;
        ///      tolerate-wanting callers avoid try/catch entirely (the costliest
        ///      pattern in caller bytecode). Only a misconfigured admin-type
        ///      constant reverts (InvalidAdminType — a programming error).
        function getOfficialEntityAddressFast(bytes32 adminTypeHash, string calldata label) external view returns (address) {
            if (!adminTypeRegistry.isHashRegistered[adminTypeHash]) revert InvalidAdminType();
            return _latestActiveEntityByLabel(adminTypeHash, keccak256(bytes(label)));
        }

        /// @notice v43107: includeInactive=false returns the activeList directly
        ///         (O(active) — the ControllerFactory hot path). includeInactive=true
        ///         concatenates active + currently-deactivated rows (the lists are
        ///         disjoint, so no address is ever returned twice). The `true` path
        ///         is O(active + deactivated) and is retained for LEGACY callers only
        ///         (e.g. TimeLock/DM SmartContract exclusion on bounded project
        ///         controllers). Prefer getAllOfficialEntities(type,false) +
        ///         getAllOfficialDeactivatedEntities(type,start,count) for anything
        ///         at platform scale, since `true` is not caller-paginated.
        function getAllOfficialEntities(string calldata adminType, bool includeInactive) external view returns (OfficialEntityStruct[] memory) {
            bytes32 adminHash = keccak256(bytes(adminType));
            if (!adminTypeRegistry.isHashRegistered[adminHash]) revert InvalidAdminType();
            OfficialEntityGroup storage group = officialEntityGroupsByHash[adminHash];

            uint256 activeCount = group.activeList.length;
            if (!includeInactive) {
                OfficialEntityStruct[] memory actives = new OfficialEntityStruct[](activeCount);
                for (uint256 i = 0; i < activeCount; i++) {
                    actives[i] = group.entitiesByAddress[group.activeList[i]];
                }
                return actives;
            }

            // includeInactive == true: active + deactivated. The lists are
            // DISJOINT (reactivation prunes deactivatedList), so this is a
            // straight concatenation — no dedup filter needed.
            uint256 deacCount = group.deactivatedList.length;
            OfficialEntityStruct[] memory all = new OfficialEntityStruct[](activeCount + deacCount);
            uint256 counter = 0;
            for (uint256 i = 0; i < activeCount; i++) {
                all[counter++] = group.entitiesByAddress[group.activeList[i]];
            }
            for (uint256 i = 0; i < deacCount; i++) {
                all[counter++] = group.entitiesByAddress[group.deactivatedList[i]];
            }
            return all;
        }

        /// @notice Paginated view of currently-DEACTIVATED entities for a type,
        ///         with each entity's full deactivation-timestamp history.
        /// @param start  Start index into deactivatedList (use
        ///               getDeactivatedEntityCount as the exact bound).
        /// @param count  Max entries to return from `start` (0 = to end).
        /// @dev deactivatedList holds ONLY currently-inactive addresses (pruned on
        ///      reactivation), so every row in the window is returned — the page
        ///      is full unless the window overruns the end of the list.
        function getAllOfficialDeactivatedEntities(string calldata adminType, uint256 start, uint256 count)
            external view returns (DeactivatedEntityStruct[] memory)
        {
            bytes32 adminHash = keccak256(bytes(adminType));
            if (!adminTypeRegistry.isHashRegistered[adminHash]) revert InvalidAdminType();
            OfficialEntityGroup storage group = officialEntityGroupsByHash[adminHash];

            uint256 len = group.deactivatedList.length;
            if (start >= len) return new DeactivatedEntityStruct[](0);
            uint256 end = (count == 0 || start + count > len) ? len : start + count;

            DeactivatedEntityStruct[] memory out = new DeactivatedEntityStruct[](end - start);
            for (uint256 i = start; i < end; i++) {
                address a = group.deactivatedList[i];
                out[i - start] = DeactivatedEntityStruct({
                    entity: group.entitiesByAddress[a],
                    deactivationTimestamps: group.deactivationHistory[a]
                });
            }
            return out;
        }

        // ============================================================
        //  v43107 MIGRATION (Platform Super ONLY, off-chain-fed batches)
        // ============================================================
        // Seeds a NEW platform Controller from an old one. The UI reads the
        // old controller off-chain (paginated on new-model sources; a single
        // getAllOfficialEntities(type,true) call on legacy sources), splits
        // rows into active/inactive, and pushes batches here. Both methods:
        //   - accept PARALLEL arrays (adminTypes[i] <-> entities[i]) so many
        //     admin types can migrate in one call;
        //   - are IDEMPOTENT (already-present addresses are skipped), so
        //     batches can be paged and safely retried;
        //   - preserve original label/id/blockNumber/blockTimestamp/value;
        //   - auto-register unseen admin types (e.g. "CodeAuditor");
        //   - are disabled forever once sealMigration() is called.
        //
        // 🔒 SOVEREIGNTY / SCOPE HARDENING:
        //   - Migration is a PLATFORM-CONTROLLER-ONLY surface: it exists to
        //     seed a NEW platform Controller. Project controllers (whose
        //     PLATFORM_CONTROLLER points elsewhere) can NEVER be migrated
        //     into — so the platform can never inject SmartContract (or any)
        //     entities into a project controller via this path, sovereign or
        //     not.
        //   - A permanent sovereign lock (platformAccessPermanentlyRevoked)
        //     also seals migration outright (belt-and-braces; on a platform
        //     controller this flag should never be set).
        //   - PLATFORM_CONTROLLER-type rows are skipped inside both migrate
        //     loops: the entity entry is decorative (authorization reads the
        //     immutable PLATFORM_CONTROLLER variable, never the entity map)
        //     and the new controller self-registers its own at deploy.

        /// @notice One-way migration seal. False = migration still allowed.
        bool public migrationSealed;

        function _requireMigrationAllowed() private view {
            if (migrationSealed) revert MigrationIsSealed();
            // Only a platform controller (self-referential PLATFORM_CONTROLLER)
            // may ever be migrated into. Project controllers: dead surface.
            if (PLATFORM_CONTROLLER != address(this)) revert NoPlatformAccess();
            if (platformAccessPermanentlyRevoked) revert NoPlatformAccess();
            if (!isPlatformAdmin(msg.sender, KECCAK_SUPER_ADMIN)) revert OnlySuper();
        }

        /// @notice Permanently disable both migrate methods (Platform Super only).
        function sealMigration() external {
            _requireMigrationAllowed();
            migrationSealed = true;
        }

        /// @notice Migrate CURRENTLY-ACTIVE entities from an old controller.
        /// @dev Skips any address already known to the target group (idempotent).
        ///      Forces active=true and pushes onto activeList.
        function migrateActiveEntities(string[] calldata adminTypes, OfficialEntityStruct[] calldata entities) external {
            _requireMigrationAllowed();
            if (adminTypes.length != entities.length) revert MigLenMismatch();
            for (uint256 i = 0; i < entities.length; i++) {
                bytes32 adminHash = keccak256(bytes(adminTypes[i]));
                if (adminHash == KECCAK_PLATFORM_CONTROLLER) continue; // self-registered at deploy; never migrated
                if (!adminTypeRegistry.isHashRegistered[adminHash]) addAdminType(adminTypes[i]);
                OfficialEntityGroup storage group = officialEntityGroupsByHash[adminHash];
                address a = entities[i].pubAddress;
                if (a == address(0)) revert BadAddr();
                if (group.entitiesByAddress[a].pubAddress != address(0)) continue; // idempotent skip
                group.entitiesByAddress[a] = OfficialEntityStruct(
                    entities[i].fullNameOfEntityOrLabel,
                    entities[i].nationalIdOfEntity,
                    a,
                    entities[i].blockNumber,      // preserved from source controller
                    entities[i].blockTimestamp,   // preserved from source controller
                    true,
                    entities[i].value
                );
                group.activeList.push(a);
                emit UpdateOfficialEnt(a, msg.sender, adminHash, "Migrate", entities[i].fullNameOfEntityOrLabel, entities[i].nationalIdOfEntity, block.timestamp, true, entities[i].value);
            }
        }

        /// @notice Migrate CURRENTLY-INACTIVE (deactivated) entities from an old
        ///         controller, including their deactivation-timestamp history.
        /// @dev Never flips an already-active address back to inactive; in that
        ///      case only its deactivation HISTORY is imported (if none recorded
        ///      yet) — it is NOT added to deactivatedList, which holds ONLY
        ///      currently-inactive addresses. Legacy sources without history:
        ///      pass a 1-element deactivationTimestamps array (the UI uses the
        ///      source row's blockTimestamp as the best-known deactivation time).
        function migrateInactiveEntities(string[] calldata adminTypes, DeactivatedEntityStruct[] calldata entities) external {
            _requireMigrationAllowed();
            if (adminTypes.length != entities.length) revert MigLenMismatch();
            for (uint256 i = 0; i < entities.length; i++) {
                bytes32 adminHash = keccak256(bytes(adminTypes[i]));
                if (adminHash == KECCAK_PLATFORM_CONTROLLER) continue; // self-registered at deploy; never migrated
                if (!adminTypeRegistry.isHashRegistered[adminHash]) addAdminType(adminTypes[i]);
                OfficialEntityGroup storage group = officialEntityGroupsByHash[adminHash];
                address a = entities[i].entity.pubAddress;
                if (a == address(0)) revert BadAddr();

                bool known = group.entitiesByAddress[a].pubAddress != address(0);
                if (!known) {
                    // Write the inactive snapshot (preserved fields, active=false).
                    group.entitiesByAddress[a] = OfficialEntityStruct(
                        entities[i].entity.fullNameOfEntityOrLabel,
                        entities[i].entity.nationalIdOfEntity,
                        a,
                        entities[i].entity.blockNumber,
                        entities[i].entity.blockTimestamp,
                        false,
                        entities[i].entity.value
                    );
                }
                if (known && group.entitiesByAddress[a].active) {
                    // Address is already ACTIVE on this controller — the lists are
                    // DISJOINT, so it must NOT enter deactivatedList. Import the
                    // source's deactivation history ONCE (idempotent: only if no
                    // history recorded here yet), then move on.
                    if (group.deactivationHistory[a].length == 0) {
                        uint256[] calldata histA = entities[i].deactivationTimestamps;
                        for (uint256 j = 0; j < histA.length; j++) {
                            group.deactivationHistory[a].push(histA[j]);
                        }
                    }
                    continue;
                }
                // Record deactivated membership + history ONCE (idempotent skip
                // if this address was already migrated/deactivated here).
                if (group.deactivatedIndexPlus1[a] == 0) {
                    group.deactivatedList.push(a);
                    group.deactivatedIndexPlus1[a] = group.deactivatedList.length; // index+1
                    uint256[] calldata hist = entities[i].deactivationTimestamps;
                    for (uint256 j = 0; j < hist.length; j++) {
                        group.deactivationHistory[a].push(hist[j]);
                    }
                    emit UpdateOfficialEnt(a, msg.sender, adminHash, "MigrateInactive", entities[i].entity.fullNameOfEntityOrLabel, entities[i].entity.nationalIdOfEntity, block.timestamp, false, entities[i].entity.value);
                }
            }
        }

        function isOfficialEntityPlusNotEntityFast(bytes32 adminType1, address entityAddr1,bytes32 adminType2, address entityAddr2, bool isAnd) external view returns (bool) {
            if (isAnd) {
                return isOfficialEntityFast(adminType1, entityAddr1) && !isOfficialEntityFast(adminType2, entityAddr2);
            } else {
                return isOfficialEntityFast(adminType1, entityAddr1) || !isOfficialEntityFast(adminType2, entityAddr2);
            }
        }


        function isOfficialDoubleEntityFast(bytes32 adminType1, address entityAddr1,bytes32 adminType2, address entityAddr2, bool isAnd) external view returns (bool) {
            if (isAnd) {
                return isOfficialEntityFast(adminType1, entityAddr1) && isOfficialEntityFast(adminType2, entityAddr2);
            } else {
                return isOfficialEntityFast(adminType1, entityAddr1) || isOfficialEntityFast(adminType2, entityAddr2);
            }
        }

        // Fast triple entity check with bytes32
        function isOfficialTripleEntityFast(bytes32 adminType1, address entityAddr1, bytes32 adminType2, address entityAddr2,
            bytes32 adminType3, address entityAddr3, bool isAnd) external view returns (bool) {
            if (isAnd) {
                return isOfficialEntityFast(adminType1, entityAddr1)
                    && isOfficialEntityFast(adminType2, entityAddr2)
                    && isOfficialEntityFast(adminType3, entityAddr3);
            } else {
                return isOfficialEntityFast(adminType1, entityAddr1)
                    || isOfficialEntityFast(adminType2, entityAddr2)
                    || isOfficialEntityFast(adminType3, entityAddr3);
            }
        }

      function isOfficialQuadrupleEntityFast(bytes32 adminType1, address entityAddr1,bytes32 adminType2, address entityAddr2,bytes32 adminType3, address entityAddr3,
            bytes32 adminType4, address entityAddr4,bool isAnd) external view returns (bool) {
            if (isAnd) {
                return isOfficialEntityFast(adminType1, entityAddr1)
                    && isOfficialEntityFast(adminType2, entityAddr2)
                    && isOfficialEntityFast(adminType3, entityAddr3)
                    && isOfficialEntityFast(adminType4, entityAddr4);
            } else {
                return isOfficialEntityFast(adminType1, entityAddr1)
                    || isOfficialEntityFast(adminType2, entityAddr2)
                    || isOfficialEntityFast(adminType3, entityAddr3)
                    || isOfficialEntityFast(adminType4, entityAddr4);
            }
        }

    //
    // END OFFICIAL ENTITIES
    //

    // ========== FEE MANAGEMENT ==========
    // All fee management (chained entities) moved to FeeManager.sol
    // Access via IFeeManager interface

        /// @notice Fee management functions removed - use FeeManager contract instead
        /// All fee calculation, distribution, and chained entity management moved to FeeManager.sol
        /// See IFeeManager interface for available functions

    // END CHAINED ENTITIES
    //




    // No receiving of accidental or unsolicited eth here
    // See below for a payable method for SALES purposes and OTHER purposes (see BELOW).
    // receive() external payable {  // <== DO NOT IMPLEMENT, LEAVE COMMENTED
    //    ethBalances[msg.sender].totalReceivedThatIsReversible += msg.value;
    //}

}

@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();
        }
    }
}

contracts/Recoverable.sol

// SPDX-License-Identifier: CLOSED LICENSE COPYRIGHT 2025
// =====================================================================
//  EquityMint.org / DataCloud OS  —  Official Sovereign Issuance Suite
//  Module: Recoverable.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", "Del Norte",
//  "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.
// =====================================================================
// OFFICAL DEL NORTE NETWORK COMPONENT
// Designed By Ken Silverman for Del Norte.  Implementation help from Tony Sparks
// Compilation help from Maleeha Naveed. May 5th, 2025

pragma solidity 0.8.35;


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


/// @title ReversibleRecoveryBase
/// @notice Base contract tracking / reversing accidental ETH/ERC20 transfers with admin authorization
abstract contract Recoverable {

    using SafeERC20 for IERC20;

    // STRUCTS


    struct ReversibleUserBalance {
        uint256 totalReceivedThatIsReversible;
        uint256 totalReversed;
        uint256 totalReversals;
    }


    // -----------------------------
    // STORAGE
    // -----------------------------


    address public controller;  // Address of the Controller contract (must implement IController)
    uint256 public ADMIN_FEE_FIXED = 10 ** 17; // 0.1 ETH
    uint256 public totalAdminFeesCollected;


    mapping(address => ReversibleUserBalance) public reversibleEthBalances;
    mapping(address => mapping(address => ReversibleUserBalance)) public reversibleTokenBalances;


    // -----------------------------
    // EVENTS
    // -----------------------------
    event TransferReversed(address indexed user, uint256 refundAmount, address tokenSC, uint256 adminFee);
    event AdminFeeUpdated(uint256 newFee);
    event ControllerChanged(address newController);


     modifier onlyBTExecutives() {
        bool temp = IController(controller).isOfficialEntity("TreasuryAdmin", msg.sender) ||
                    IController(controller).isOfficialEntity("SmartContract", msg.sender);
        require(temp, "Unauthorized access");
        _;  // run the code block referencing this modifier
    }


    // -----------------------------
    // CONSTRUCTOR
    // -----------------------------
    constructor(address _controller) {
        require(_controller != address(0), "Controller address cannot be zero");
        controller = _controller;
    }


    // -----------------------------
    // EXTERNAL METHODS
    // -----------------------------
    function manualUpdateReversibleBalanceETH(address userAddress, uint256 amount)
        external onlyBTExecutives  {
        reversibleEthBalances[userAddress].totalReceivedThatIsReversible += amount;
    }




    function manualUpdateReversibleBalanceERC20(address userAddress, uint256 amount, address tokenSC)
        external onlyBTExecutives {
        reversibleTokenBalances[tokenSC][userAddress].totalReceivedThatIsReversible += amount;
    }


    function reverseAccidentalETH() external payable  {
        require(msg.value >= ADMIN_FEE_FIXED, "Insufficient admin fee");
        require(!IController(controller).isOfficialEntity("Registrar", msg.sender),
            "Registrars/launchpads may not be allowed to reverse any amounts they send.");
        ReversibleUserBalance storage balance = reversibleEthBalances[msg.sender];
        uint256 refundAmount = balance.totalReceivedThatIsReversible - balance.totalReversed;
        require(refundAmount > 0, "Nothing to refund");
        // Update state before external call
        balance.totalReversed += refundAmount;
        balance.totalReversals += 1;
        totalAdminFeesCollected += msg.value;
        // Perform the external call
        (bool success, ) = msg.sender.call{value: refundAmount}("");
        require(success, "Ether transfer failed");
        emit TransferReversed(msg.sender, refundAmount, address(0), msg.value);
    }



    function reverseAccidentalERC20(address tokenSC) external payable {
        require(msg.value >= ADMIN_FEE_FIXED, "Insufficient admin fee");
        require(!IController(controller).isOfficialEntity("Registrar", msg.sender), "Registrars/launchpads may not reverse any amounts they send.");
        ReversibleUserBalance storage balance = reversibleTokenBalances[tokenSC][msg.sender];
        uint256 refundAmount = balance.totalReceivedThatIsReversible - balance.totalReversed;
        require(refundAmount > 0, "Nothing to refund");
        // Update state before external call
        balance.totalReversed += refundAmount;
        balance.totalReversals += 1;
        totalAdminFeesCollected += msg.value;
        // Perform the external call
        IERC20(tokenSC).safeTransfer(msg.sender, refundAmount);
        emit TransferReversed(msg.sender, refundAmount, tokenSC, msg.value);
  }


    function changeAdminFee(uint256 newFee) external onlyBTExecutives {
        ADMIN_FEE_FIXED = newFee;
        emit AdminFeeUpdated(newFee);
    }


   function changeController(address remote) internal {
        controller = remote;
        emit ControllerChanged(remote);
   }
}

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