Skip to content
Verified contractExactUNLICENSED

FeeManager

Address0xa899f66e9583d8a9136eaaabeca5b314bfa59518
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.35

 

Same code

1 more contract

 

Details

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

contracts/FeeManager.sol

// SPDX-License-Identifier: UNLICENSED
// =====================================================================
//  EquityMint.org / DataCloud OS  —  Official Sovereign Issuance Suite
//  Module: FeeManager.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.
//
// Fee Manager - Manages hierarchical fee structures (chained entities) for flexible, multi-tiered
// fee distribution across the platform. Supports 256 fee types (0-255) with type-agnostic calculation
// and distribution. Includes SEC compliance documentation for transaction vs service fees. Core component
// enabling transparent, auditable fee collection for both platform services and project treasuries.
//
// Chief Architect and CEO: Ken Silverman, US Fintech LLC
// Designed by Ken Silverman as part of the EquityMint fee architecture.
// @author Ken Silverman
//
// ⚖️  AUTHORIZED USE RESTRICTIONS:
// Only projects deploying these contracts via the EquityMint platform at equitymint.org
// which contain this preamble and Fee structures generated through EquityMint.org have
// permission to use these contracts or any derivative works thereto. Any such deployment
// must contain these words. This contract is part of a greater system. They are owned
// and licensed exclusively in writing and through US Fintech, LLC.
//
// Any breach of these terms will be investigated and pursued through all available civil
// and criminal remedies to the fullest extent permitted by applicable law. Enforcement is
// discretionary. The failure to enforce any provision shall not constitute a waiver of the
// right to enforce at any time. All projects and platform users interacting with this system
// are subject to additional terms and conditions as may be published or updated from time to
// time at https://equitymint.org and/or https://DataCloudOS.com.
pragma solidity 0.8.35;

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

// Minimal interface for ExecutivePeerTreasury receiveFee function
interface ExecutivePeerTreasury {
    function receiveFee() external payable;
}

/// @title FeeManager
/// @author Ken Silverman
/// @notice Manages hierarchical fee structures (chained entities) for the platform
/// @dev Standalone contract that accepts Controller for authorization checks
/**
 * ===============================================================================
 * FEE TYPE CLASSIFICATION & SEC COMPLIANCE NOTICE
 * ===============================================================================
 *
 * This contract supports flexible fee types (1-255). Fee types are categorized as:
 *
 * 🚀 FEE_TYPE_DEPLOY (1) - Platform deployment fees
 * 🟢 NON-TRANSACTION (Platform Services - Safe for Platform Collection)
 * 📍 DISTRIBUTION: PlatformUniverse calls distributeFees()
 *    User must approve FeeManager in advance (via permit in PlatformUniverse before calling distributeFees())
 *    FeeManager pulls from user → distributes to entities
 *
 * ⚡ FEE_TYPE_ACTIVATION (2) - Token activation (making tokens tradeable)
 * 🔴 TRANSACTION-RELATED (Securities Activity - SEC Regulated)
 * 📍 DISTRIBUTION: IssueToken calls distributeFees()
 *    User must approve FeeManager in advance (via permit in IssueToken before calling distributeFees())
 *    FeeManager pulls from user → distributes to entities
 *
 * 📝 FEE_TYPE_SALESREG (3) - Primary market sales registration/KYC services
 * 🟢 NON-TRANSACTION (Platform Services - Safe for Platform Collection)
 * 📍 DISTRIBUTION: IssueTokenContentManager calls distributeFees()
 *    User must approve FeeManager in advance (via permit in UI before calling registerUser())
 *    FeeManager pulls from user → distributes to entities
 *
 * 🛒 FEE_TYPE_PURCHASE (4) - Primary market token purchases/sales
 * 🔴 TRANSACTION-RELATED (Securities Activity - SEC Regulated)
 * 📍 DISTRIBUTION: IssueTokenSaleManager distributes directly via safeTransfer (does NOT use distributeFees())
 *    Buyer approves SalesManager → SalesManager receives USDC → distributes to entities
 *    NOTE: SalesManager.transfer() to buyer triggers TRANSFER fees (type 6). UX must calculate:
 *          totalApproval = purchasePrice + purchaseFees + transferFees (SalesManager needs balance)
 *
 * 👥 FEE_TYPE_HOLDER (5) - Periodic holder maintenance fees (registry upkeep)
 * 🟢 NON-TRANSACTION (Platform Services - Safe for Platform Collection)
 * 📍 DISTRIBUTION: ProjectRevenueTreasury distributes directly via safeTransfer (does NOT use distributeFees())
 *    Treasury already owns USDC → distributes to entities (no approval needed)
 *
 * 🔄 FEE_TYPE_TRANSFER (6) - Secondary market token transfers
 * 🔴 TRANSACTION-RELATED (Securities Activity - SEC Regulated)
 * 📍 DISTRIBUTION: IssueToken distributes directly via safeTransferFrom (does NOT use distributeFees())
 *    Sender approves IssueToken → IssueToken pulls from sender → distributes to entities
 *    NOTE: Direct distribution saves ~2,000 gas vs. using FeeManager (same UX: 1 signature + 1 tx)
 *    IMPORTANT: When SalesManager transfers tokens to buyer, it must have USDC balance to cover
 *               transfer fees. UX calculates: purchasePrice + purchaseFees + transferFees = total
 *
 * 🏭 FEE_TYPE_TOKENPURCHASE (7) - Reserved token purchase service fee (non-transaction SaaS label)
 * 🟢 NON-TRANSACTION (Platform Services - Safe for Platform Collection)
 * 📍 DISTRIBUTION: Future implementation (reserved.
 *    See transferFee percent-type with peg set only to get stable fee based on token transfer amount)
 *
 * 📦 FEE_TYPE_PRODUCTNFTTRANSFER (8) - Secondary movement of product NFTs (post-purchase transfers)
 * 🟢 NON-TRANSACTION (Platform Services)
 * 📍 DISTRIBUTION: Future — charged when product NFTs are transferred between wallets (if allowed)
 *
 * 🛍️ FEE_TYPE_PRODUCTNFTMINT (9) - Product NFT primary purchase (minting via ProductSaleManager)
 * 🔴 TRANSACTION-RELATED (Commerce Activity)
 * 📍 DISTRIBUTION: ProductSaleManager charges during primary mint-to-buyer purchase
 *    CONVENTION: "Mint" = primary purchase (first sale / initial creation)
 *
 * 🛒 FEE_TYPE_PRODUCTNFTPURCHASE (10) - Escrow-based secondary product sales
 * 🔴 TRANSACTION-RELATED (Commerce Activity)
 * 📍 DISTRIBUTION: ProductNFTTransferManager charges during escrow-based product resale
 *    CONVENTION: "Purchase" = secondary purchase (escrow-based resale)
 *
 * 🏛️ FEE_TYPE_PROPERTYNFTMINT (11) - Property NFT primary registration (government minting)
 * 🟢 NON-TRANSACTION (Government Services)
 * 📍 DISTRIBUTION: PropertyNFTTransferManager charges when minting property title to approved owner
 *    CONVENTION: "Mint" = primary purchase (first sale / initial creation)
 *
 * 🔄 FEE_TYPE_PROPERTYNFTTRANSFER (12) - Non-sale property NFT transfers
 * 🟢 NON-TRANSACTION (Government Services)
 * 📍 DISTRIBUTION: PropertyNFTTransferManager charges on non-sale, non-mint movements
 *
 * 🏠 FEE_TYPE_PROPERTYNFTPURCHASE (13) - Escrow-based secondary property sales
 * 🔴 TRANSACTION-RELATED (Real Estate Commerce)
 * 📍 DISTRIBUTION: PropertyNFTTransferManager charges during escrow-based resale completion
 *    CONVENTION: "Purchase" = secondary purchase (escrow-based resale)
 *
 * ⚠️  REGULATORY WARNING (Transaction-Related Fees: 4, 6, 9, 10, 13):
 * ----------------------------------------------------------------------------
 * These fees are associated with the PURCHASE, SALE, or TRANSFER of securities.
 * Collection of these fees by a platform may constitute broker-dealer activity
 * requiring SEC registration under Section 15(a) of the Securities Exchange Act
 * of 1934 and compliance with SEC Rule 15a-1.
 *
 * US Fintech LLC and platform operators MUST NOT collect these fees unless:
 * 1. Registered as a broker-dealer with SEC and FINRA, OR
 * 2. Operating under a valid exemption (e.g., Regulation ATS for alternative
 *    trading systems, or other applicable exemptions)
 *
 * These fee types are designed for PROJECT TREASURIES to collect fees from
 * their own token holders, NOT for platform-level collection.
 *
 * ✅ SAFE FOR PLATFORM COLLECTION (Non-Transaction Fees: 1, 3, 5, 7):
 * ----------------------------------------------------------------------------
 * These fees are for administrative and technology services unrelated to
 * securities transactions. Platform collection is permissible as they represent:
 * - Software-as-a-Service (SaaS) fees (Deploy, Registration, Holder maintenance, TokenPurchase)
 * - Data management and storage fees
 * - Identity verification and compliance services
 * - Registry maintenance and record-keeping
 *
 * 📋 FEE COLLECTION PATTERNS:
 * ----------------------------------------------------------------------------
 * DEPLOY FEE (1):          User approves FeeManager → PlatformUniverse calls distributeFees() → FeeManager pulls & distributes
 * ACTIVATION FEE (2):      User approves FeeManager → IssueToken calls distributeFees() → FeeManager pulls & distributes
 * SALESREG FEE (3):        User approves FeeManager → ContentManager calls distributeFees() → FeeManager pulls & distributes
 * PURCHASE FEE (4):        Buyer approves SalesManager → SalesManager distributes directly (safeTransfer)
 * HOLDER FEE (5):          Treasury already owns funds → Treasury distributes directly (safeTransfer)
 * TRANSFER FEE (6):        Sender approves IssueToken → IssueToken distributes directly (safeTransferFrom)
 * TOKENPURCHASE FEE (7):  Reserved for future implementation
 *
 * 🔑 KEY INSIGHT - When distributeFees() is used:
 * ----------------------------------------------------------------------------
 * Fee types 1 (Deploy), 2 (Activation), and 3 (SalesReg) use FeeManager.distributeFees().
 * For these types, the payer MUST approve FeeManager in advance because
 * distributeFees() calls safeTransferFrom(payer, entity, amount).
 *
 * Other fee types distribute directly from the calling contract using
 * safeTransfer (if contract owns funds) or safeTransferFrom (if contract
 * has approval), so they do NOT need to approve FeeManager.
 *
 * 📌 IMPLEMENTATION NOTES:
 * ----------------------------------------------------------------------------
 * - Fee types are NOT pre-registered; any uint8 (0-255) is valid
 * - Projects define their own fee structures via Controller
 * - FeeManager is TYPE-AGNOSTIC; it only calculates and distributes
 * - Legal compliance is the responsibility of fee collectors, not this contract
 * - Types 7-255 reserved for future use
 *
 * ⚖️  LEGAL DISCLAIMER:
 * This software is provided for fee calculation and distribution only.
 * US Fintech LLC makes no representations regarding the legality of any
 * particular fee collection arrangement. Users must consult legal counsel
 * to ensure compliance with applicable securities laws.
 *
 * ===============================================================================
 */
 /**
 * ===============================================================================
 * FEE MANAGER AUTHORIZATION & SOVEREIGNTY MODEL
 * ===============================================================================
 *
 * OVERVIEW
 * ------------------------------------------------------------------------------
 * FeeManager maintains a hierarchical (tree-based) fee entity structure used
 * solely for fee calculation and distribution. Each entity may be an EOA or
 * SmartContract and may have zero or more child entities.
 *
 * This contract enforces a strict, non-escalating authorization model designed
 * to support:
 *   • Sovereign project treasuries
 *   • Delegation via official SmartContracts
 *   • Immutable root ownership guarantees
 *   • Safe, auditable hierarchy control
 *
 * ------------------------------------------------------------------------------
 * IDENTITY RESOLUTION (CRITICAL INVARIANT)
 * ------------------------------------------------------------------------------
 *
 * FeeManager uses a SINGLE identity resolution rule across all state-changing
 * operations:
 *
 *   effectiveCaller =
 *       tx.origin  IF msg.sender is an OFFICIAL SmartContract
 *       msg.sender OTHERWISE
 *
 * This rule guarantees:
 *   • Delegation through official contracts behaves identically to direct EOA calls
 *   • SmartContracts NEVER gain independent authority
 *   • No privilege escalation via tx.origin
 *
 * All permission checks (admin, ancestor, parent, self) are evaluated ONLY
 * against effectiveCaller.
 *
 * ------------------------------------------------------------------------------
 * ENTITY TYPES
 * ------------------------------------------------------------------------------
 *
 * ROOT ENTITY
 *   • parent == address(0)
 *   • Represents a sovereign fee domain (e.g. Project / Platform Treasury)
 *   • Cannot be removed or overridden by admins
 *
 * CHILD ENTITY
 *   • parent != address(0)
 *   • Fully governed by parent / ancestor rules
 *
 * ------------------------------------------------------------------------------
 * PERMISSION MATRIX (WHO CAN DO WHAT)
 * ------------------------------------------------------------------------------
 *
 * ROLE DEFINITIONS USED BELOW
 *   • Project Admin  = any of {Super, TreasuryAdmin, TokenAdmin} registered in the
 *                      project Controller.  Resolved by `_isProjectAdmin(addr)` via
 *                      `controller.isOfficialTripleEntityFast(...)`.  Used by the
 *                      `onlyProjectAdmin` modifier (formerly `onlySuper`).
 *   • Platform TokenAdmin = `TokenAdmin` registered in the PLATFORM Controller,
 *                      resolved by `controller.isPlatformAdmin(addr, KECCAK_TOKEN_ADMIN)`.
 *                      Distinct from the project-side TokenAdmin above.
 *
 * ADD ENTITY
 * ------------------------------------------------------------------------------
 * • Add ROOT:
 *     - Project Admin
 *
 * • Add CHILD:
 *     - Parent entity
 *     - Any ancestor of parent
 *
 * UPDATE ENTITY (TIERED SOVEREIGNTY, same parent only)
 * ------------------------------------------------------------------------------
 * • Update CONSTRUCTOR ROOT (blockTimestamp <= deploymentTimestamp):
 *     - Platform TokenAdmin (ignores lock)
 *     - SELF (blocked if locked)
 * • Update PROJECT-ADDED ROOT (blockTimestamp > deploymentTimestamp):
 *     - Project Admin (ignores lock)
 *     - SELF (blocked if locked)
 *
 * • Update CHILD:
 *     - SELF (if not locked)
 *     - Parent or any ancestor (locked ancestor CANNOT edit — consistency with HOLE 3)
 *
 * REMOVE ENTITY (TIERED SOVEREIGNTY — tier always uses the ROOT's timestamp)
 * ------------------------------------------------------------------------------
 * • Remove CONSTRUCTOR-ROOT subtree (root.blockTimestamp <= deploymentTimestamp):
 *     - Platform TokenAdmin (ignores lock — key-loss recovery)
 *     - For children: SELF or Parent (subject to lock semantics)
 *     - Project Admin CANNOT remove anything in this subtree
 * • Remove PROJECT-ROOT subtree (root.blockTimestamp > deploymentTimestamp):
 *     - Project Admin (ignores lock — key-loss recovery)
 *     - For children: SELF or Parent (subject to lock semantics)
 *     - Platform TokenAdmin CANNOT remove anything in this subtree
 *
 * NOTE: REMOVE now mirrors UPDATE — both use the ROOT's timestamp for the tier
 * check.  The platform fully owns its subtree (add / edit / remove); the project
 * fully owns its own.  The project's only post-delay recourse against a platform
 * subtree is freezeRootPath() or globalFreezeLock.
 *
 * LOCK / UNLOCK ENTITY (TIERED SOVEREIGNTY)
 * ------------------------------------------------------------------------------
 * • Lock / Unlock CONSTRUCTOR entity (blockTimestamp <= deploymentTimestamp):
 *     - Platform TokenAdmin (ignores own lock status)
 *     - Any ancestor (locked ancestor cannot unlock — HOLE 3 fix)
 * • Lock / Unlock NON-CONSTRUCTOR entity (blockTimestamp > deploymentTimestamp):
 *     - Project Admin (ignores own lock status)
 *     - Any ancestor (locked ancestor cannot unlock — HOLE 3 fix)
 * • permanentlyLocked entities CANNOT be unlocked by anyone (set via permLockRoot)
 * • SELF-LOCK is allowed for any entity (root or non-root) via the subtree-lock primitive
 *   (lockAllMyChildren(self, includeSelf=true, isLock=true)) — a voluntary act of self-restraint.
 * • SELF-UNLOCK is forbidden for any entity (root or non-root) — releasing a lock requires an outside party.
 *   A platform/project tiered admin who coincides with a root entity unlocks via Path A
 *   (setChainedEntityLock) using the ADMIN role, not the self relationship.
 *
 * • permLockRoot (per-root IRREVERSIBLE lock):
 *     - Tiered admin only (Platform TokenAdmin for constructor, Project Admin for project-added)
 *     - Sets permanentlyLocked=true + locked=true on root, recursively locks all children
 *     - IRREVERSIBLE — no time restriction, no undo, not even via PROJECTUNLOCK
 *
 * • PROJECTLOCK (globalFreezeLock):
 *     - Project Admin (via onlyProjectAdmin), after freezeDelay (default 180 days)
 *     - Freezes ALL entities: no edits, no adds, no unlocks, no removals
 *     - Except: changeRoot() payout override (platform recovery)
 *     - Reversible via same function with isFreezeLock=false
 *
 * GLOBAL RESTRICTIONS
 * ------------------------------------------------------------------------------
 * • globalAddLock:
 *     - Prevents NEW entity additions
 *     - Does NOT affect updates, removals, or fee calculations
 *
 * • globalFreezeLock (PROJECTLOCKED):
 *     - Freezes entire fee tree — no entity can be edited, removed, locked, or unlocked
 *     - Only changeRoot() payout override remains operational
 *     - Applies to all callers, including admins
 *
 * • rootFamilyLocked[root]  (PER-ROOT FREEZE — surgical PROJECTLOCK, default chain only)
 *     - Project Admin only (via onlyProjectAdmin), after freezeDelay
 *     - Freezes the entire subtree below `root`: blocks adds, edits, removes, and
 *       per-entity lock/unlock for every node whose root-walk lands on `root`
 *     - Applies to ALL callers in that subtree, including the platform TokenAdmin
 *     - Does NOT block changeRoot() payout override (key-recovery survives)
 *     - Does NOT block peg / feed setters (platform tree-wide controls)
 *     - Reversible by project via freezeRootPath(root, false)
 *     - Composes independently with globalFreezeLock and globalAddLock
 *     - Operates on the DEFAULT chain type only (flat map, no bytes32 outer key)
 *
 * ------------------------------------------------------------------------------
 * DESIGN GUARANTEES
 * ------------------------------------------------------------------------------
 *
 * ✔ No admin can seize or delete a root entity
 * ✔ No SmartContract can act without an authorized EOA behind it
 * ✔ Delegation never changes authority semantics
 * ✔ Tree ancestry is the ONLY non-admin control mechanism
 * ✔ All authorization rules are explicit, symmetric, and auditable
 *
 * This contract intentionally prioritizes sovereignty, predictability,
 * and regulatory safety over administrative convenience.
 *
 * ===============================================================================
 */

/// @notice Interface for ProjectRevenueTreasury notification hook
interface IProjectRevenueTreasury {
    function onTransferFeeDistributed() external;
}

/// @notice Minimal Chainlink AggregatorV3 surface — only `latestRoundData` is needed for the
///         transfer-fee peg override. Inlined (not imported) to avoid a new dependency for a
///         single getter, mirroring the same pattern already used by IssueTokenTimeLock.
interface AggregatorV3Interface {
    function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

// PROXY BUILD: EIP-1167 clone variant — deployed once per chain as an inert MODEL;
// projects receive a clone configured via initialize(). NOTE: OZ ReentrancyGuard's
// constructor (sets _status=1) never runs for clones, but its zero initial state
// behaves identically to NOT_ENTERED, so it is clone-safe without changes.
contract FeeManager is TreasuryConstants, ReentrancyGuard, CloneInitializable {
    using SafeERC20 for IERC20;

    // version control ensures verifier matches THIS contract on otherwise duplicate deployments.
    uint16 public constant CONTRACT_VERSION = 43109; // v43109: _labelTable seeds type 16 "CapTableExport" (DM payCapTableExportFee) — template-carried types MUST be seeded (see FeeManagerInitializer.initialize). Prior (43108): stableScale — fee configs stay canonical 6-dec, calculateChainedAmounts outputs scale ×10**(stableDecimals-6) to the official stable's real atomics (18-dec BNB-peg USDT/USDC support). Types 7/14 (token-denominated) excluded. Prior (43107): freezeRootPath + REMOVE-uses-root-tier + onlySuper→onlyProjectAdmin rename + private helper consolidation.
    // Fee action constants
    uint8 public constant ACTION_ADD = 1;
    uint8 public constant ACTION_UPDATE = 2;
    uint8 public constant ACTION_REMOVE = 3;
    uint8 public constant ACTION_LOCK = 4;
    uint8 public constant ACTION_UNLOCK = 5;
    uint8 public constant ACTION_REACTIVATE = 6;


    // Fee calculation constant
    uint256 public constant BASIS_POINTS_DIVISOR = 10000; // 100% = 10000 basis points
    uint256 public constant MAX_VALUE = 1000000000000;  // Maximum allowed value: 1,000,000 USD (in USDC atomic units with 6 decimals)

    // Keccak256 hashes for authorization checks (matching Controller.sol)
    bytes32 private constant KECCAK_SUPER_ADMIN = keccak256(bytes("Super"));
    // KECCAK_TREASURY_ADMIN and KECCAK_SMART_CONTRACT inherited from TreasuryConstants

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

    struct EntityFeesWithNames {
        address entityAddress;           // Entity receiving fees
        address parent;                  // Parent entity in hierarchy (0x0 = ROOT)
        uint256[] feeValues;             // DYNAMIC: Fee amounts (length = currentMaxFeeType)
                                         //   ⚠️ ALL FEE VALUES ARE DENOMINATED IN 6-DECIMAL STABLECOIN UNITS
                                         //   Example: $10 fee = 10,000,000 (10 * 10^6)
                                         //   Applies to: USDC, EURO stablecoin, YEN stablecoin, etc.
                                         //   All platform stablecoins use 6 decimals for consistency
                                         //
                                         //   FEE TYPE → ARRAY INDEX MAPPING:
                                         //   Type 1 (Activation) → Index 0
                                         //   Type 2 (SalesReg)   → Index 1
                                         //   Type 3 (Purchase)   → Index 2
                                         //   Type 4 (Holder)     → Index 3
                                         //   Type 5 (Transfer)   → Index 4
                                         //   Types 6+ (Future)   → Indices 5+
        uint8[] feeFlags;                // DYNAMIC: Fee flags (same length as feeValues) - CHANGED TO uint8
                                         //   bit0=isPercent(0=Value,1=Percent)
                                         //   bit1=isTaker(0=GetsFromParent,1=TakesFromParent)
        bool permanentlyLocked;          // Per-root IRREVERSIBLE lock (set via permLockRoot). Blocks all unlocks.
        bool locked;                     // Temporary lock (can be unlocked by parent/admin)
        string entityName;               // Human-readable name (e.g., "ProjectTreasury")
        string entityID;                 // Optional ID (e.g., EIN, wallet tag)
    }

    struct ChainedEntityStruct {        // Storage version (includes metadata)
        address entityAddress;
        address parent;
        uint256[] feeValues;            // DYNAMIC array of fee values
                                        // ⚠️ STORED IN CANONICAL 6-DEC UNITS ON EVERY CHAIN (v43108)
                                        // Example: $10 fee = 10,000,000 (10 * 10^6) regardless of the
                                        // stablecoin's real decimals — templates stay chain-agnostic.
                                        // calculateChainedAmounts() scales OUTPUTS ×stableScale to real
                                        // atomics (1e12 on 18-dec BNB-peg chains); types 7/14 unscaled.
        uint8[] feeFlags;               // DYNAMIC array of fee flags - CHANGED TO uint8
        bool active;                    // Is entity active? (soft delete)
        bool locked;
        bool permanentlyLocked;         // Per-root IRREVERSIBLE lock (set via permLockRoot). Blocks all unlocks.
        uint256 blockNumber;            // When created/updated
        uint256 blockTimestamp;         // When created/updated
        string entityName;
        string entityID;
    }

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

    // ===============================================================================
    // EVENTS (NOT duplicated in IFeeManager.sol - events are implementation details)
    // ===============================================================================
    // Events are emitted by FeeManager for off-chain monitoring/indexing.
    // External contracts don't need these - they only need structs and function signatures.
    // ===============================================================================

    event ChEntyUpdate(
        address indexed entityAddress,
        address indexed parent,
        address indexed updater,
        uint8 action,
        uint8 numFees,
        bool active,
        uint256 timestamp
    );

    event ChEntyLocked(
        address indexed entity,
        bytes32 indexed chainHash,
        address indexed locker,
        uint256 blockTimestamp
    );

    event ChEntyUnlocked(
        address indexed entity,
        bytes32 indexed chainHash,
        address indexed unlocker,
        uint256 blockTimestamp
    );

    event ChainEntPermLocked(
        address indexed entity,
        bytes32 indexed chainHash,
        uint256 blockTimestamp,
        bool permanentlyLocked
    );

    event GlobalChainLock(
        address indexed activator,
        uint256 blockTimestamp
    );

    /// @notice Emitted when the platform-set tokens-per-stablecoin peg is updated.
    /// @dev See `tokensPerStableCoinPegX1e6` storage docblock for full semantics.
    event TokensPerStableCoinPegUpdated(uint256 oldPegX1e6, uint256 newPegX1e6, address indexed setter);

    /// @notice Emitted when the two Chainlink feeds used by the transfer-fee peg override
    ///         are updated atomically.
    /// @dev Both feeds are always set together to prevent partial-config states (one feed
    ///      set, the other stale/missing → silent fallback to static peg without explicit
    ///      operator intent). Pass address(0) for either slot to disable that side.
    event TransferFeePegFeedsUpdated(
        address oldTokenFeed,
        address newTokenFeed,
        address oldStableFeed,
        address newStableFeed,
        address indexed setter
    );

    event FeeTypeAdded (
        uint8 indexed feeType,
        string label,
        uint256 timestamp
    );

    // Custom errors
    error BadAddr();
    error Unauthorized();
    error BadType();
    error ValExceedsMax();
    /// @dev v43108: official stablecoin decimals must be within [6, 18].
    error StableDecimalsOutOfRange();
    error EntityLocked();
    error EntityPermLocked();
    error EntityRootFamilyLocked();
    error GlobalAddLocked();
    error ParentNotActive();
    error OnlySuper();
    error OnlyParent();
    error EntityNotActive();
    error SelfRemoveOnly();
    error NotParentOrSelf();
    error InvalidEntity();
    error NotAncestor();
    error OnlySuperCanLockRoots();
    error MustWait6Months();
    error GlobalLockAlreadyActive();
    error NotAncestorOrSelf();
    error InvalidChainType();
    error CumulativePercentageExceedsMaximum();
    error ArrayLengthMismatch();
    error CannotRemoveLocked();
    error MustBeAncestor();
    error FeeTypeInUse();
    error FeeTypeNotLast();
    error FeeArraysExceedMax();
    error LabelNotDefined();
    error OnlyPlatformTreasurerOrProjectSC();
    error FeeTypeRange();
    error LabelEmpty();
    error MustFillPriorSlots();
    error FeeTypeOutOfRange();
    error FeeTypeNotDefined();
    error AlreadySet();
    error FeeTypeAlreadyDefined();
    error FeeTypeLabelAlreadyUsed();
    error FeeArrayLengthMustNotExceedCurrentMaxFeeType();

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

    // State variables
    // PROXY BUILD: were `immutable` in the full-deployment build — clones share one
    // runtime bytecode, so per-project values live in storage, set in initialize().
    IController public controller;
    uint256 public deploymentTimestamp;

    /// @dev PROXY BUILD: this model's initializer AND cold-path sidecar (holds the
    ///      former constructor body — label table, config seeding — plus, since
    ///      v43109, the bodies of addChainedEntity / addFeeType / syncStableCoin,
    ///      reached through _fwd(); see FeeManagerInitializer at the end of this
    ///      file). Same delegatecall pattern as the other oversized models.
    ///      Deployed by the model's own constructor; immutable = lives in the
    ///      model RUNTIME (shared by every clone), occupies NO storage slot.
    address private immutable INIT_SIDECAR;
    bool public globalAddLock;
    uint256 public globalAddLockTimestamp;
    bool public globalFreezeLock;              // PROJECTLOCKED — freezes entire fee tree (all entities)

    /// @notice Cool-down before PROJECTLOCK and globalAddLock become available to project admins.
    /// @dev Default 180 days.  Platform TokenAdmin may LOWER this value at any time via
    ///      `reduceFreezeDelay`.  It is monotonically decreasing — once reduced, it can never be
    ///      raised again.  This lets the platform shorten the wait for projects that need earlier
    ///      access to project-wide controls without ever extending it for anyone.
    // PROXY BUILD: default assigned in initialize() (inline initializers run in
    // creation code only, which clones never execute — a clone would get 0).
    uint256 public freezeDelay; // 180 days default, set in initialize()

    address public projectRevenueTreasury;

    /// @notice TOKENS_PER_STABLECOIN peg (×1e6) for percent-based TRANSFER fees.
    /// @dev    Scaled by 1e6 so fractional pegs are expressible:
    ///           - 4_000_000  → 4 IssueTokens per $1 stablecoin
    ///           - 250_000    → 0.25 IssueTokens per $1 stablecoin (i.e. each token ≈ $4)
    ///           - 0 (default) → peg UNSET → percent TRANSFER fees evaluate to 0,
    ///                           which preserves the historical "no percent transfer fees"
    ///                           behavior. Absolute (value) transfer fees are unaffected.
    ///         Only consulted when feeType == 6 ("Transfer") AND totalVal > 0.
    ///         All other fee types ignore this storage slot entirely.
    ///         Decimal contract assumed: IssueTokens 1e18, OfficialStablecoins 1e6.
    ///
    ///         ⚠️ PLATFORM-CONTROLLED, NOT PROJECT-CONTROLLED:
    ///         Setter is Platform-TokenAdmin only and is NOT gated by `globalFreezeLock`,
    ///         project permLock, or any project-side authority. Foreign-currency-denominated
    ///         token programs (e.g., a food-stamp token pegged to a destabilizing FX) must
    ///         remain platform-correctable on demand — annual, monthly, or emergency. A
    ///         project locking platform access must NOT be able to freeze a stale peg in
    ///         place and starve the platform's USDC fee stream.
    uint256 public tokensPerStableCoinPegX1e6;

    // -------------------------------------------------------------------------
    // FEED OVERRIDE (revert-able) — Chainlink dual-feed live peg.
    // -------------------------------------------------------------------------
    // If BOTH `tokenUsdFeed` AND `stableUsdFeed` are set AND BOTH return a fresh,
    // positive price, the conversion uses the live ratio (token_usd / stable_usd)
    // instead of the static `tokensPerStableCoinPegX1e6`. If either feed is unset
    // OR either returns 0 (stale / negative / missing), we fall back to the static
    // peg. If the static peg is ALSO 0, percent transfer fees evaluate to 0
    // (current default behavior).
    //
    // RATIONALE: Foreign-currency stablecoin programs may need a live FX peg that
    // moves with the underlying currency. When such feeds exist on the deploy
    // chain, the platform sets both and the project's percent transfer fees stay
    // accurate without monthly/yearly manual repegs. When feeds don't exist for an
    // exotic currency pair (e.g. Honduran Lempira), platform falls back to manual
    // peg updates.
    //
    // BYTECODE NOTE: If post-compile we are over FeeManager's bytecode budget, the
    // feed override is the cleanest revert target — delete this block (the two
    // address storage slots + their auto-getters), `setTokenUsdAndStableUsdFeeds`,
    // `getPegFeedPrice`, the dual-feed branch inside `calculateChainedAmounts`,
    // the dual-feed branch inside `getEffectivePegX1e6` (collapses to just the
    // static-or-disabled return), and the `AggregatorV3Interface` declaration.
    // Static peg remains and project keeps working.
    address public tokenUsdFeed;
    address public stableUsdFeed;

    /// @dev Optional payout override for ROOT entities only.
    ///      If `payoutAddressByRoot[chainHash][root]` is non-zero, fee distribution pays that address instead of the root key.
    ///      This does NOT change tree permissions or parent/child keys; it only changes payout destination.
    mapping(bytes32 => mapping(address => address)) private payoutAddressByRoot;

    /// @notice Per-root subtree freeze. See `freezeRootPath` and the GLOBAL RESTRICTIONS
    ///         docblock at the top of this file for the full semantics.
    /// @dev    `rootFamilyLocked[rootAddr] == true` blocks adds, edits, removes and
    ///         per-entity lock/unlock anywhere in `rootAddr`'s subtree, for every caller
    ///         (including the platform TokenAdmin).  `changeRoot()` and peg/feed setters
    ///         are intentionally NOT gated by this map.  Public so off-chain monitors can
    ///         query subtree freeze state directly.
    /// @dev    ⚠️ DEFAULT CHAIN TYPE ONLY.  The map is flat (not keyed by chainHash) to
    ///         save bytecode.  In practice only `DEFAULT_FEE_CHAIN_TYPE` is used; if a
    ///         deployment ever activates a non-default chain type, the freeze applies
    ///         across chain types for any root address listed in this map.  If full
    ///         per-chain isolation is ever needed, re-introduce the bytes32 outer key.
    mapping(address => bool) public rootFamilyLocked;

    // Storage for chained entity groups by chain type hash
    mapping(bytes32 => ChainedEntityGroup) private chainedEntityGroupsByHash;

    /// @notice Default chain type for fee entities (encapsulated - callers don't need to know)
    /// @dev Each FeeManager instance manages ONE project, so one chain type is sufficient
    bytes32 private constant DEFAULT_FEE_CHAIN_TYPE = keccak256("PLATFORM_FEE_CHAINED_ENTITY");

    /// @notice Fee type labels for UI lookups and validation
    /// @dev Maps fee type (1-50) to human-readable label (e.g., 1 => "Deploy")
    mapping(uint8 => string) public feeTypeLabels;

    /// @notice Reverse mapping: label string to fee type number
    /// @dev Maps label (e.g., "Transfer") to fee type (e.g., 6)
    ///      Used by contracts to resolve fee types by name at deployment time
    mapping(string => uint8) public feeTypeLabelToType;

    /// @notice Hash-based reverse mapping for gas-optimized lookups
    /// @dev Maps keccak256(label) to fee type number
    ///      Used by internal contracts for gas-efficient fee calculations
    mapping(bytes32 => uint8) public feeTypeHashToType;

    /// @notice Current highest fee type with a label (starts at 13, expandable dynamically)
    /// @dev Arrays passed to addChainedEntity() must match this length
    uint8 public currentMaxFeeType; // 13 default, set in initialize() (clone-safe; see freezeDelay note)

    /// @notice v43108 — Multiplier from canonical 6-dec fee units to the official stablecoin's
    ///         REAL atomic units: `10**(stableDecimals - 6)`.
    /// @dev    WHY: fee configs/templates stay chain-agnostic in canonical 6-dec "USD-like"
    ///         units ($10 = 10_000_000 on EVERY chain), but stablecoins are NOT uniformly
    ///         6-dec across chains (ETH USDC/USDT = 6-dec → scale 1; BNB Binance-Peg
    ///         USDT/USDC = 18-dec → scale 1e12). calculateChainedAmounts() multiplies its
    ///         OUTPUTS by this scale (stable-denominated fee types only — token-denominated
    ///         types 7/14 are excluded) so every consumer that permits/pulls the returned
    ///         amounts as ERC-20 atomics is correct on any chain with NO caller changes.
    ///         Set once in initialize() from the official stablecoin's decimals().
    ///         0 (uninitialized pre-v43108 clone) is treated as 1 (6-dec behavior).
    uint256 public stableScale; // slot 18 — APPEND-ONLY (mirrored in FeeManagerInitializer)

    /// @notice Absolute maximum fee types to prevent unbounded growth (gas safety)
    uint8 public constant ABSOLUTE_MAX_FEE_TYPES = 50;

    // ===== PROXY BUILD: MODEL CONSTRUCTOR =====
    // No arguments; permanently locks the model. Clones never execute this.
    // Deploys this model's initializer sidecar (constructor/init code is NOT
    // subject to EIP-170, so the embedded sidecar costs the model no runtime
    // bytes — only a one-time deposit at model deployment).
    constructor() {
        INIT_SIDECAR = address(new FeeManagerInitializer());
        _disableInitializers();
    }

    /// @notice Clone constructor-equivalent — STUB (proxy build).
    /// @dev The former constructor body (label table, scalar defaults,
    ///      Controller registration, platform-treasury config seeding) lives in
    ///      FeeManagerInitializer.initialize() — the delegatecall sidecar at the
    ///      end of this file — exactly like the other oversized models.
    ///      Params are intentionally UNNAMED so this stub never abi-decodes the
    ///      struct array: `_delegateInit` forwards raw msg.data and the SIDECAR
    ///      decodes + executes against THIS clone's storage. One-shot is
    ///      enforced HERE by `initializer` before delegating.
    // v43108: third param = official stablecoin address; the SIDECAR reads its
    // decimals() and derives `stableScale` (see that field's docblock).
    function initialize(IController, EntityFeesWithNames[] calldata, address) external initializer {
        _delegateInit(INIT_SIDECAR);
    }

    /// @dev COLD-PATH TRAMPOLINE (v43109): forward the ENTIRE calldata to INIT_SIDECAR and bubble
    ///      its return / revert data verbatim. Same contract as the initializer sidecar — it
    ///      mirrors this model's storage layout, so cold setters run against THIS clone's state
    ///      exactly as if their bodies lived here. Context: clone → model → sidecar, all
    ///      delegatecall, so msg.sender / tx.origin / address(this) are unchanged.
    function _fwd() private {
        address s = INIT_SIDECAR;
        assembly ("memory-safe") {
            let p := mload(0x40)
            calldatacopy(p, 0, calldatasize())
            let ok := delegatecall(gas(), s, p, calldatasize(), 0, 0)
            returndatacopy(p, 0, returndatasize())
            switch ok
            case 0 { revert(p, returndatasize()) }
            default { return(p, returndatasize()) }
        }
    }

    /// @notice v43108 — Re-sync `stableScale` after the project rotates to an official stablecoin
    ///         with DIFFERENT decimals. COLD PATH: full NatSpec + body in FeeManagerInitializer.syncStableCoin;
    ///         this stub forwards calldata. Trustless/permissionless (label is prefix-guarded and must
    ///         resolve to an ACTIVE SmartContract on THIS clone's controller).
    function syncStableCoin(string calldata) external { _fwd(); }

    // ========== MODIFIERS ==========

    /// @dev Authorises `tx.origin` if it is any of the three project-admin roles
    ///      (Super OR TreasuryAdmin OR TokenAdmin).  All three are peers for
    ///      project-side governance — see `_isProjectAdmin` for rationale.
    ///      Pre-v4.3.2.0 this was `onlySuper` and accepted only Super OR TreasuryAdmin.
    modifier onlyProjectAdmin() {
        if (!_isProjectAdmin(tx.origin)) revert Unauthorized();
        _;
    }

    modifier onlyRegisteredContract() {
        if (!_isMsgSenderSC()) revert Unauthorized();
        _;
    }

    /**
     * @notice Resolve effective caller - use tx.origin only if msg.sender is official SmartContract
     * @dev This is the ONLY way to resolve caller identity across all operations
     * @return Effective caller address (tx.origin if SmartContract, else msg.sender)
     */
    function _effectiveCaller() internal view returns (address) {
        return _isMsgSenderSC() ? tx.origin : msg.sender;
    }

    /// @dev Tiered sovereignty admin check — single source of truth.
    /// Constructor entities (blockTimestamp <= deploymentTimestamp): platform TokenAdmin only.
    /// Non-constructor entities: Project Admin (Super, TreasuryAdmin, OR TokenAdmin).
    function _isTieredAdmin(address caller, uint256 entityTimestamp) internal view returns (bool) {
        return entityTimestamp <= deploymentTimestamp
            ? controller.isPlatformAdmin(caller, KECCAK_TOKEN_ADMIN)
            : _isProjectAdmin(caller);
    }

    /// @dev Project-side admin authority — true if `who` is registered as Super,
    ///      TreasuryAdmin, OR TokenAdmin in the project Controller.  All three roles
    ///      together constitute the "project admin" set in v4.3.2.0+; `_isTieredAdmin`,
    ///      `onlyProjectAdmin`, and the root-add branch of `_addChainedEntity` all
    ///      resolve via this helper so the project-admin set is consistent everywhere.
    /// @dev TokenAdmin is included because FeeManager extends TreasuryConstants, which
    ///      already declares `KECCAK_TOKEN_ADMIN`.  No additional storage / constants
    ///      are introduced here — this is a permissions widening, not a new role.
    function _isProjectAdmin(address who) private view returns (bool) {
        return controller.isOfficialTripleEntityFast(
            KECCAK_SUPER_ADMIN, who,
            KECCAK_TREASURY_ADMIN, who,
            KECCAK_TOKEN_ADMIN, who,
            false  // OR logic — any of the three roles is sufficient
        );
    }

    /// @dev Bytecode-saving consolidation of the
    ///      `address caller = _effectiveCaller(); if (!controller.isPlatformAdmin(caller, KECCAK_TOKEN_ADMIN)) revert Unauthorized();`
    ///      pattern.  Returns `caller` so the caller can be reused for event emits.
    ///      Used by `reduceFreezeDelay`, `setTokensPerStableCoinPegX1e6`, and
    ///      `setTokenUsdAndStableUsdFeeds`.
    function _requirePlatformTokenAdmin() private view returns (address caller) {
        caller = _effectiveCaller();
        if (!controller.isPlatformAdmin(caller, KECCAK_TOKEN_ADMIN)) revert Unauthorized();
    }

    /// @dev Bytecode-saving consolidation of the
    ///      `controller.isOfficialEntityFast(KECCAK_SMART_CONTRACT, msg.sender)` pattern.
    ///      Used by `onlyRegisteredContract`, `_effectiveCaller`, and `addFeeType`.
    ///      `setProjectRevenueTreasury` reaches the same check via the modifier.
    function _isMsgSenderSC() private view returns (bool) {
        return controller.isOfficialEntityFast(KECCAK_SMART_CONTRACT, msg.sender);
    }

    // ========== CHAINED ENTITY MANAGEMENT ==========

    // COLD PATH (v43109 EIP-170 relief): the ADD/UPDATE engine — isTaker tiered gate,
    // _addChainedEntityInternal, _updateExistingEntity, _addChainedEntity — now lives ONLY in
    // FeeManagerInitializer (it already carried a verbatim copy for initialize-time seeding;
    // the model copy was pure duplication). Both overloads forward their raw calldata via
    // _fwd(); the sidecar executes against THIS clone's storage and its ABI-encoded bool is
    // bubbled back. Params are intentionally UNNAMED so the stub never decodes the struct.

    /// @notice Add a chained entity to the fee hierarchy (simplified - uses default chain type)
    function addChainedEntity(EntityFeesWithNames calldata) external returns (bool) { _fwd(); }

    /// @notice Add a chained entity to the fee hierarchy (advanced - custom chain type)
    /// @dev ISTAKER GATE and tier rules: see FeeManagerInitializer.addChainedEntity.
    function addChainedEntity(bytes32, EntityFeesWithNames calldata) external returns (bool) { _fwd(); }

    /// @notice Remove a chained entity
    /// @notice Remove a chained entity (simplified - uses default chain type)
    // DEATIVATES ALL CHILDREN TOO!!!  rename to removeChainedEntityLegacy
    // MUST deactivate all legacy for readability
    // because calculate fee STOPS at first deactivated child.
    function removeChainedEntity(address entity, bool includeSelf) external returns (bool) {
        return removeChainedEntity(DEFAULT_FEE_CHAIN_TYPE, entity, includeSelf);
    }

    /// @notice Remove a chained entity (advanced - custom chain type)
    // DEATIVATES ALL CHILDREN TOO!!!  rename to removeChainedEntityLegacy
    // MUST deactivate all legacy for readability
    // because calculate fee STOPS at first deactivated child.
    function removeChainedEntity(bytes32 chainHash, address entity, bool includeSelf) public returns (bool) {
        if (entity == address(0)) revert InvalidEntity();

        address caller = _effectiveCaller();

        ChainedEntityGroup storage group = chainedEntityGroupsByHash[chainHash];
        ChainedEntityStruct storage entityStruct = group.entitiesByAddress[entity];

        if (!entityStruct.active) revert EntityNotActive();
        if (globalFreezeLock) revert EntityPermLocked();

        // Single walk-up serves TWO purposes:
        //   (a) PER-ROOT FREEZE guard — `rootFamilyLocked[rootAddr]` blocks every caller,
        //       including the platform TokenAdmin.
        //   (b) TIER CHECK below now uses the ROOT's timestamp (NOT entity-own), which
        //       mirrors UPDATE semantics: the tier that owns the root owns the entire
        //       subtree's structure.  A Project Admin therefore CANNOT remove children
        //       of a constructor-tier (platform) root; their post-delay recourse is
        //       freezeRootPath() / globalFreezeLock.
        address rootAddr = _walkUp(group, entity, address(0));
        if (rootFamilyLocked[rootAddr]) revert EntityRootFamilyLocked();

        bool isRootNode = (entityStruct.parent == address(0));
        bool isSelfRemoving = (entity == caller);
        bool isAdmin = _isTieredAdmin(caller, group.entitiesByAddress[rootAddr].blockTimestamp);

        // TIERED SOVEREIGNTY: admin checks FIRST (ignore lock), self-removal LAST (respects lock).
        if (isRootNode) {
            if (isAdmin) {
                // Tiered admin deactivating root (key-loss recovery). Lock ignored.
            } else if (isSelfRemoving) {
                if (entityStruct.locked && includeSelf) revert CannotRemoveLocked();
            } else {
                revert SelfRemoveOnly();
            }
        } else {
            bool isParent = (caller == entityStruct.parent);
            if (!isAdmin && !isParent && !isSelfRemoving) {
                revert NotParentOrSelf();
            }
            if (entityStruct.locked && includeSelf && isSelfRemoving) revert CannotRemoveLocked();
        }
        // removes ALL legacy children too!!!
        _deactivateChainedEntityLegacy(chainHash, entity, includeSelf);
        return true;
    }

    // Duplicate of setChainedEntityLock(string,address,bool) — kept for backward compatibility
    // with older clients that hard-coded the lockChild() name.  New callers should prefer
    // setChainedEntityLock().  Both routes share the same implementation (_lockEntityInternal),
    // so authorization, lock semantics, and events are identical.
    function lockChild(string calldata chainType, address child, bool isLock) external returns (bool) {
        return _lockEntityInternal(keccak256(bytes(chainType)), child, isLock);
    }

    /// @notice Lock or unlock a fee entity (simplified - uses default chain type)
    function setChainedEntityLock(address entity, bool shouldLock) external returns (bool) {
        return _lockEntityInternal(DEFAULT_FEE_CHAIN_TYPE, entity, shouldLock);
    }

    /// @notice Lock or unlock a fee entity (advanced - custom chain type)
    function setChainedEntityLock(string calldata chainType, address entity, bool shouldLock) external returns (bool) {
        return _lockEntityInternal(keccak256(bytes(chainType)), entity, shouldLock);
    }

    /// @notice Override payout address for a ROOT entity (key-loss recovery).
    /// @dev Auth: tiered sovereignty — platform TokenAdmin for constructor roots, project admin for project-added roots.
    /// @dev Allowed even if PROJECTLOCKED (globalFreezeLock == true), since this only changes payout destination.
    /// @dev Only applies to root entities (parent == address(0)).
    function changeRoot(string calldata chainType, address root, address newPayout) external returns (bool) {
        if (root == address(0) || newPayout == address(0)) revert BadAddr();

        address caller = _effectiveCaller();
        bytes32 chainHash = keccak256(bytes(chainType));
        ChainedEntityStruct storage e = chainedEntityGroupsByHash[chainHash].entitiesByAddress[root];
        if (e.entityAddress == address(0)) revert InvalidEntity();
        if (e.parent != address(0)) revert Unauthorized();
        if (!_isTieredAdmin(caller, e.blockTimestamp)) revert Unauthorized();

        payoutAddressByRoot[chainHash][root] = newPayout;
        return true;
    }

    /// @notice Read the payout-address override for a ROOT entity.
    /// @dev    Returns address(0) if no override has been set via changeRoot();
    ///         in that case the root's own `entityAddress` is the effective payee.
    /// @param  chainType The chain type string (typically "PLATFORM_FEE_CHAINED_ENTITY")
    /// @param  root      The root entity address (tree key)
    /// @return payout    The override payout address, or address(0) if none.
    function getRootPayoutAddress(string calldata chainType, address root) external view returns (address payout) {
        return payoutAddressByRoot[keccak256(bytes(chainType))][root];
    }

    /// @dev Consolidated lock/unlock implementation (replaces _setChainedEntityLockInternal + lockChild).
    /// Auth (TIERED SOVEREIGNTY):
    ///   Constructor fee entities: platform TokenAdmin can lock/unlock. Project admins CANNOT.
    ///   Non-constructor fee entities: Project Admin (Super/TreasuryAdmin/TokenAdmin) can lock/unlock. Platform CANNOT.
    ///   Ancestor: can lock/unlock descendants (HOLE 3 fix: locked ancestor cannot unlock).
    ///   permanentlyLocked: forward-compat dead code on freshly deployed instances — `permLockRoot`
    ///   is deprecated and no current path sets the flag. PROJECTLOCK (globalFreezeLock) is the freeze
    ///   mechanism. The runtime guard below is preserved so any future re-introduction of an entity-
    ///   level permanent lock keeps the same unlock-block semantics.
    /// Idempotent: no-ops if entity is already in desired state.
    function _lockEntityInternal(bytes32 chainHash, address entity, bool isLock) private returns (bool) {
        if (entity == address(0)) revert InvalidEntity();
        if (!isLock && globalFreezeLock) revert EntityPermLocked();

        ChainedEntityGroup storage group = chainedEntityGroupsByHash[chainHash];
        ChainedEntityStruct storage c = group.entitiesByAddress[entity];
        if (!c.active) revert EntityNotActive();
        if (!isLock && c.permanentlyLocked) revert EntityPermLocked();
        // PER-ROOT FREEZE: subtree is frozen → no per-entity lock/unlock either.
        // Applies to every caller, including tiered admins.
        if (rootFamilyLocked[_walkUp(group, entity, address(0))]) revert EntityRootFamilyLocked();

        address caller = _effectiveCaller();

        // Tier check uses entity's OWN blockTimestamp (NOT the root's) by design — locking
        // is a NON-destructive request (reversible by any ancestor or tiered admin), so
        // entity-tier here costs nothing: a Project Admin can lock a child inside a
        // platform subtree, but the platform TokenAdmin can immediately unlock it.
        // Contrast with REMOVE / UPDATE (root-tier as of v4.3.2.0), which are structural.
        // The PROJECT's irreversible recourse over a platform subtree is freezeRootPath()
        // (surgical, project-only, blocks even tiered admins).
        if (!_isTieredAdmin(caller, c.blockTimestamp)) {
            // Ancestor path — walk parent chain via the shared _walkUp helper.
            if (!_isAncestor(group, c.parent, caller)) revert MustBeAncestor();
            // A deactivated ancestor must not retain authority over its descendants.
            // The parent pointer survives deactivation (so the chain still walks), but
            // the ancestor's voice does not — they must reactivate themselves first.
            if (!group.entitiesByAddress[caller].active) revert EntityNotActive();
            // HOLE 3 fix: locked ancestor cannot unlock children
            if (!isLock && group.entitiesByAddress[caller].locked) revert EntityLocked();
        }

        // Idempotent
        if (isLock && !c.locked) {
            c.locked = true;
            emit ChEntyLocked(entity, chainHash, msg.sender, block.timestamp);
        } else if (!isLock && c.locked) {
            c.locked = false;
            emit ChEntyUnlocked(entity, chainHash, msg.sender, block.timestamp);
        }
        return true;
    }

    /// @notice DEPRECATED — entity-level permanent locks are no longer supported.
    /// @dev    Project-wide PROJECTLOCK (permLockAllRootChainedEntities / globalFreezeLock)
    ///         is the freeze mechanism. Body kept ABI-compatible so older clients fail loudly.
    function permLockRoot(string calldata /*chainType*/, address /*root*/) external pure returns (uint256) {
        revert("deprecated; use PROJECTLOCK");
        // ------------------------------------------------------------------
        // ORIGINAL BODY — preserved for reference only. To revive: restore
        // the parameter names above (chainType / root), drop `pure`, and
        // uncomment the block below (also remove the revert line above).
        // ------------------------------------------------------------------
        // if (root == address(0)) revert InvalidEntity();
        // bytes32 chainHash = keccak256(bytes(chainType));
        // ChainedEntityGroup storage group = chainedEntityGroupsByHash[chainHash];
        // ChainedEntityStruct storage c = group.entitiesByAddress[root];
        // if (!c.active) revert EntityNotActive();
        // if (c.parent != address(0)) revert OnlySuperCanLockRoots();
        // if (c.permanentlyLocked) return 0;
        // if (!_isTieredAdmin(_effectiveCaller(), c.blockTimestamp)) revert Unauthorized();
        //
        // c.permanentlyLocked = true;
        // c.locked = true;
        // emit ChainEntPermLocked(root, chainHash, block.timestamp, true);
        // lockedCount = 1 + _lockRecursive(group, chainHash, root, false);
    }

    /// @notice PROJECTLOCK: freeze or unfreeze the entire fee tree after 6 months.
    /// @dev Sets globalFreezeLock. When locking, also recursively sets locked=true on all entities (belt-and-suspenders).
    /// @param chainType The chain type (used only for recursive lock on activation)
    /// @param isFreezeLock True to PROJECTLOCK, false to remove PROJECTLOCK
    /// @dev Only callable by Super after 6 months. Idempotent.
    function permLockAllRootChainedEntities(string calldata chainType, bool /*includeSelf*/, bool isFreezeLock) external onlyProjectAdmin returns (uint256 lockedCount) {
        if (block.timestamp < deploymentTimestamp + freezeDelay) revert MustWait6Months();
        if (globalFreezeLock == isFreezeLock) return 0;

        globalFreezeLock = isFreezeLock;

        if (isFreezeLock) {
            bytes32 chainHash = keccak256(bytes(chainType));
            ChainedEntityGroup storage group = chainedEntityGroupsByHash[chainHash];
            for (uint256 i = 0; i < group.rootNodes.length; i++) {
                lockedCount += _lockRecursive(group, chainHash, group.rootNodes[i], true);
            }
        }

        emit ChainEntPermLocked(address(0), keccak256(bytes(chainType)), block.timestamp, isFreezeLock);
        return lockedCount;
    }

    /// @notice PER-ROOT FREEZE: surgically freeze (or thaw) one root's entire subtree
    ///         under the DEFAULT chain type (the only chain type in production use).
    /// @dev Project Admin only (Super, TreasuryAdmin, OR TokenAdmin), after `freezeDelay`.
    ///      Reversible by same caller via `isFreeze=false`.  When frozen, every mutation in the subtree
    ///      (add child, edit values, remove, per-entity lock/unlock) reverts with
    ///      `EntityPermLocked` for ALL callers, including the platform TokenAdmin —
    ///      so the project can ratchet the platform out of its own subtree without
    ///      engaging the global `permLockAllRootChainedEntities` PROJECTLOCK that also
    ///      freezes the project's own subtree.
    /// @dev Does NOT block `changeRoot()` payout override (key-recovery survives) and
    ///      does NOT block peg / feed setters (platform tree-wide controls).
    /// @dev `root` must be an existing root entity (parent == address(0)) in the DEFAULT
    ///      chain type.  Idempotent: returns false if already in the requested state.
    /// @dev Auth uses the `onlyProjectAdmin` modifier (Super, TreasuryAdmin, OR
    ///      TokenAdmin via tx.origin).
    /// @param root       Tree root whose subtree should be frozen/thawed.
    /// @param isFreeze   true = freeze the subtree, false = thaw it.
    function freezeRootPath(address root, bool isFreeze) external onlyProjectAdmin returns (bool) {
        if (block.timestamp < deploymentTimestamp + freezeDelay) revert MustWait6Months();
        ChainedEntityStruct storage e = chainedEntityGroupsByHash[DEFAULT_FEE_CHAIN_TYPE].entitiesByAddress[root];
        if (e.entityAddress == address(0) || e.parent != address(0)) revert InvalidEntity();
        if (rootFamilyLocked[root] == isFreeze) return false;
        rootFamilyLocked[root] = isFreeze;
        return true;
    }

    /// @notice Toggle lock on NEW entity additions after 6 months.
    /// @param shouldLock true = block new adds, false = re-enable adds
    function lockNewRootEntityAdds(bool shouldLock) external onlyProjectAdmin returns (bool) {
        if (block.timestamp < deploymentTimestamp + freezeDelay) revert MustWait6Months();
        if (globalAddLock == shouldLock) return false;

        globalAddLock = shouldLock;
        if (shouldLock) globalAddLockTimestamp = block.timestamp;

        emit GlobalChainLock(msg.sender, block.timestamp);
        return true;
    }

    /// @notice Lower the freeze cool-down (PROJECTLOCK / globalAddLock gate).
    /// @dev Platform TokenAdmin only.  Monotonically decreasing — `newDelay` MUST be strictly
    ///      less than the current `freezeDelay`.  Once reduced, the value can never be raised
    ///      again (each successful call ratchets it down further).  No event, no custom error —
    ///      reuses `Unauthorized` and `ValExceedsMax` to keep bytecode flat.
    function reduceFreezeDelay(uint256 newDelay) external {
        _requirePlatformTokenAdmin();
        if (newDelay >= freezeDelay) revert ValExceedsMax();
        freezeDelay = newDelay;
    }

    /// @notice Update the tokens-per-stablecoin peg used to convert IssueToken transfer
    ///         amounts into stablecoin units for PERCENT-based TRANSFER-fee calculations.
    /// @param  newPegX1e6 Peg scaled by 1e6 — e.g. 4_000_000 for "4 tokens per $1",
    ///         250_000 for "0.25 tokens per $1". Pass 0 to DISABLE percent transfer fees
    ///         (reverts the project to pre-peg behavior — absolute transfer fees still apply).
    /// @dev    Platform TokenAdmin only. Intentionally NOT gated by `globalFreezeLock`,
    ///         project permLock, or any other project-side gate — see the storage docblock
    ///         on `tokensPerStableCoinPegX1e6` for the threat-model rationale. The platform
    ///         must be able to re-peg foreign-currency token programs on demand even after
    ///         a project has revoked further platform write access.
    ///         No `ValExceedsMax` guard: a very-high peg only makes percent fees vanishingly
    ///         small (which fails-safe to "no fee"), and a very-low peg makes percent fees
    ///         large but is still bounded by the per-call `maxPct` ceiling enforced inside
    ///         calculateChainedAmounts (CumulativePercentageExceedsMaximum).
    function setTokensPerStableCoinPegX1e6(uint256 newPegX1e6) external {
        // _requirePlatformTokenAdmin() resolves the effective caller AND enforces auth in one
        // call; its return value is reused for the event emit so the controller is touched
        // only once per invocation.  Same pattern in setTokenUsdAndStableUsdFeeds.
        address caller = _requirePlatformTokenAdmin();
        // F4 hardening: cap the peg at 1e24, which accommodates the worst plausible exchange
        // rate (1 token = $1e-18 → 1e18 tokens per stable, ×1e6 scale = 1e24). Above this,
        // `pegX1e6 * 1e6` inside calculateChainedAmounts can come uncomfortably close to
        // uint256 overflow domains for adversarial inputs; capping here keeps the calc safe.
        // ValExceedsMax is reused (no new error → no new bytecode for the error selector).
        if (newPegX1e6 > 1e24) revert ValExceedsMax();
        uint256 oldPeg = tokensPerStableCoinPegX1e6;
        tokensPerStableCoinPegX1e6 = newPegX1e6;
        emit TokensPerStableCoinPegUpdated(oldPeg, newPegX1e6, caller);
    }

    // -------------------------------------------------------------------------
    // FEED OVERRIDE setter — revert-able as a block if bytecode is tight.
    // -------------------------------------------------------------------------
    /// @notice Atomically set BOTH Chainlink feeds used by the transfer-fee peg override.
    /// @param newTokenFeed   Token-USD aggregator address. Pass address(0) to disable.
    /// @param newStableFeed  Stable-USD aggregator address. Pass address(0) to disable.
    /// @dev Platform TokenAdmin only. Not gated by globalFreezeLock / project permLock —
    ///      same rationale as the static peg setter (platform must retain corrective control).
    /// @dev Atomic by design: both feeds must be passed together. Setting only one would
    ///      leave the override in an "always-falls-back" state (the dual-feed branch in
    ///      calculateChainedAmounts only activates when BOTH are set), masking operator
    ///      intent and making misconfiguration silent. With this combined setter, every
    ///      successful tx represents a complete, intentional configuration change.
    ///      To disable the override entirely, pass (address(0), address(0)).
    function setTokenUsdAndStableUsdFeeds(address newTokenFeed, address newStableFeed) external {
        // _requirePlatformTokenAdmin() resolves the caller AND enforces auth in one call —
        // see setTokensPerStableCoinPegX1e6 docblock for rationale.
        address caller = _requirePlatformTokenAdmin();
        address oldTokenFeed  = tokenUsdFeed;
        address oldStableFeed = stableUsdFeed;
        tokenUsdFeed  = newTokenFeed;
        stableUsdFeed = newStableFeed;
        emit TransferFeePegFeedsUpdated(
            oldTokenFeed,  newTokenFeed,
            oldStableFeed, newStableFeed,
            caller
        );
    }

    /// @notice Read a Chainlink feed's latest price (or 0 if unset / stale / negative).
    /// @dev Public so anyone can probe a configured (or proposed) feed's health from off-chain
    ///      diagnostics or a Sale Admin sanity-check button. Mirrors the IssueTokenTimeLock
    ///      pattern: 1-hour staleness ceiling, round-complete check, positive-answer check, and
    ///      try/catch so a misconfigured feed cannot brick the fee calc. Returns 0 → caller (or
    ///      operator) treats as "feed unavailable" and falls back.
    /// @dev Public visibility does NOT add an external-call cost when this contract calls itself
    ///      via `getPegFeedPrice(addr)` inside calculateChainedAmounts — Solidity routes that as
    ///      an internal JUMP (no selector lookup, no new call frame).
    function getPegFeedPrice(address feed) public view returns (uint256) {
        if (feed == address(0)) return 0;
        try AggregatorV3Interface(feed).latestRoundData() returns (
            uint80 roundId,
            int256 answer,
            uint256 /* startedAt */,
            uint256 updatedAt,
            uint80 answeredInRound
        ) {
            if (block.timestamp - updatedAt > 3600) return 0;
            if (answeredInRound < roundId) return 0;
            if (answer <= 0) return 0;
            return uint256(answer);
        } catch {
            return 0;
        }
    }

    /// @notice Diagnostic getter — returns the peg actually used at THIS block for percent
    ///         TRANSFER-fee calculations, plus a tag describing where it came from.
    /// @return effectivePegX1e6 The peg currently in effect (0 if percent transfer fees are off).
    /// @return source 0 = DUAL FEED live (feeds set AND both fresh+positive),
    ///                1 = STATIC fallback (feeds set but one or both unhealthy → static peg used),
    ///                2 = STATIC only (no feeds configured, static peg used),
    ///                3 = DISABLED (no feeds AND no static peg → percent transfer fees are 0).
    /// @dev View-only; safe to call from any UI / monitoring tool. Mirrors the priority order
    ///      and math used inside calculateChainedAmounts so operators see the exact peg the
    ///      next transfer-fee calc will use. If `source == 1`, the UI should surface that as
    ///      "feeds configured but degraded" and prompt the operator to investigate.
    function getEffectivePegX1e6() public view returns (uint256 effectivePegX1e6, uint8 source) {
        address _tFeed = tokenUsdFeed;
        address _sFeed = stableUsdFeed;
        bool feedsConfigured = (_tFeed != address(0) && _sFeed != address(0));

        if (feedsConfigured) {
            uint256 tokenUsd  = getPegFeedPrice(_tFeed);
            uint256 stableUsd = getPegFeedPrice(_sFeed);
            if (tokenUsd > 0 && stableUsd > 0) {
                return ((stableUsd * 1e6) / tokenUsd, 0); // dual-feed live
            }
        }

        uint256 staticPeg = tokensPerStableCoinPegX1e6;
        if (staticPeg > 0) {
            // feeds configured but at least one degraded → "static fallback"
            // feeds NOT configured                       → "static only"
            return (staticPeg, feedsConfigured ? 1 : 2);
        }
        return (0, 3); // fully disabled
    }

    /**
     * @notice Get fee type number from label string
     * @param label Fee type label (e.g., "Transfer", "Purchase", "Holder")
     * @return feeType Fee type number (1-50), reverts if not defined
     * @dev Use this in contract constructors to ensure fee types are correctly resolved
     *      This guarantees type-safe fee resolution and prevents misalignment errors
     */
    function getTypeForLabel(string calldata label) external view returns (uint8 feeType) {
        feeType = feeTypeLabelToType[label];
        if (feeType == 0) revert LabelNotDefined();
        return feeType;
    }

    /**
     * @notice Register the ProjectRevenueTreasury for post-fee notifications
     * @param treasury Address of ProjectRevenueTreasury contract
     *
     * @dev INTEGRATED SYSTEM DESIGN (NOT A STANDALONE CONTRACT):
     *      FeeManager is part of a tightly-coupled platform ecosystem deployed as a unit.
     *      This is NOT a general-purpose fee contract - it's designed for the EquityMint platform.
     *
     *      DEPLOYMENT FLOW:
     *      1. Platform Controller is deployed and bootstrapped
     *      2. FeeManager is deployed and registered as official SmartContract
     *      3. ProjectRevenueTreasury is deployed and registered as official SmartContract
     *      4. PRT constructor calls this function during deployment (near-atomic)
     *
     *      SECURITY MODEL:
     *      - Only OFFICIAL SmartContract entities (registered in Controller) may call
     *      - Typiclly one-time binding (like IssueTokenTimeLock.setLifetimeTokenAddress)
     *      - But can be reset to a new PRT if needed for testing.  NO security hole here.
     *      - If PRT is misconfigured/rogue, the ENTIRE PLATFORM FAILS by design
     *      - This is acceptable because all official SCs are platform-controlled and audited
     *      - There is no "unknown/untrusted" SC that can call this
     *
     *      WHY THIS IS SAFE:
     *      - Official SC registration requires platform admin authorization
     *      - All platform contracts are deployed together in controlled sequence
     *      - PRT must implement receiveFee() and onTransferFeeDistributed() or system breaks
     *      - System integrity depends on ALL components being correct (all-or-nothing)
     */
    function setProjectRevenueTreasury(address treasury) external onlyRegisteredContract {
        // Allow any reset.  Only trusted smartcontract can do it anyway.
        projectRevenueTreasury = treasury;
    }

    /**
     * @notice Notify ProjectRevenueTreasury that fees were distributed
     * @dev Best-effort notification, never reverts distribution
     *      Called AFTER fee distribution completes (any fee type)
     */
    function _notifyProjectRevenueTreasury() internal {
        address prt = projectRevenueTreasury;
        if (prt == address(0)) return;

        // best-effort, never revert distribution
        try IProjectRevenueTreasury(prt).onTransferFeeDistributed() {} catch {}
    }

    // ========== FEE TYPE MANAGEMENT ==========

    /// @notice Add a new fee type label (ADD-ONLY — cannot update or remove). COLD PATH: body in
    ///         FeeManagerInitializer.addFeeType (delegatecall sidecar); this stub forwards calldata.
    /// @dev Auto-increments the type id (currentMaxFeeType + 1). Authorized callers: registered
    ///      SmartContract (msg.sender) or platform TreasuryAdmin (via _effectiveCaller()).
    function addFeeType(string calldata) external { _fwd(); }

    /**
     * @notice Get all fee type labels in a single call (gas-optimized for UI)
     * @return labels Array of fee type labels (indices 0 to currentMaxFeeType-1)
     * @dev Returns all defined labels in one call to avoid multiple RPC requests
     */
    function getAllFeeTypeLabels() external view returns (string[] memory labels) {
        labels = new string[](currentMaxFeeType);
        for (uint8 i = 0; i < currentMaxFeeType; i++) {
            labels[i] = feeTypeLabels[i];
        }
        return labels;
    }

    // Lock or unlock a subtree.  isLock=true locks, isLock=false unlocks.
    //
    // Auth model (mirrors _lockEntityInternal / Path A):
    //   • TIERED ADMIN of subtreeRoot   — can lock/unlock the subtree.
    //   • ANCESTOR of subtreeRoot       — can lock/unlock the subtree (if not locked themselves on unlock).
    //   • subtreeRoot itself (SELF)     — can LOCK its own subtree (voluntary self-restraint, root or non-root).
    //                                     Cannot UNLOCK itself — release of a constraint requires an outside party
    //                                     (tiered admin or ancestor).  Symmetric for roots and non-roots.
    //
    // Unlock additionally reverts if globalFreezeLock — the project-wide PROJECTLOCK is a hard floor for everyone,
    // including tiered admins.
    //
    // @param subtreeRoot         The entity whose subtree we're operating on.  Must be the caller itself
    //                            or a descendant of the caller (equivalently: caller must be self-or-ancestor
    //                            of subtreeRoot).  Tiered admins are admitted regardless of tree position.
    //                            NOTE: the storage slot variable below is named `s` (not `p`) since this is
    //                            the SUBTREE ROOT, not a parent of anything caller-related.
    // @param includeSubtreeRoot  If true, subtreeRoot itself is locked/unlocked along with its descendants.
    //                            If false, only descendants are touched.  ("Subtree root" here means the
    //                            entity passed in — NOT the caller.)
    function lockAllMyChildren(string calldata chainType, address subtreeRoot, bool includeSubtreeRoot, bool isLock) external returns (uint256) {
        if (!isLock && globalFreezeLock) revert EntityPermLocked();
        bytes32 chainHash = keccak256(bytes(chainType));
        ChainedEntityGroup storage group = chainedEntityGroupsByHash[chainHash];
        ChainedEntityStruct storage s = group.entitiesByAddress[subtreeRoot];
        if (!s.active) revert ParentNotActive();
        // PER-ROOT FREEZE: subtree is frozen → no subtree lock/unlock either, even
        // for tiered admins.  Walks up from `subtreeRoot` to find its tree root.
        if (rootFamilyLocked[_walkUp(group, subtreeRoot, address(0))]) revert EntityRootFamilyLocked();

        address caller = _effectiveCaller();

        // Authorization gate.  Tiered admins pass through unconditionally — the admin role
        // (platform TokenAdmin for constructor entities, Project Admin for project-added
        // entities) is the legitimate "outside party" that may release locks
        // and operate on any subtree at its tier, including its own.
        //
        // For non-admin callers:
        //   • SELF-UNLOCK is forbidden — entities cannot release their own constraints.
        //     Symmetric for roots and non-roots.
        //   • Otherwise caller must be subtreeRoot itself (self-LOCK only) OR a non-locked
        //     ancestor of subtreeRoot.
        // Tier check uses entity's OWN blockTimestamp (NOT the root's) by design — locking
        // is a NON-destructive request (reversible by any ancestor or tiered admin), so
        // entity-tier here costs nothing: a Project Admin can lock a child inside a
        // platform subtree, but the platform TokenAdmin can immediately unlock it.
        // Contrast with REMOVE / UPDATE (root-tier as of v4.3.2.0), which are structural.
        // The PROJECT's irreversible recourse over a platform subtree is freezeRootPath()
        // (surgical, project-only, blocks even tiered admins).
        if (!_isTieredAdmin(caller, s.blockTimestamp)) {
            if (!isLock && caller == subtreeRoot && includeSubtreeRoot) revert EntityLocked();

            if (caller != subtreeRoot) {
                // Walk parent chain via the shared _walkUp helper (target-finding mode).
                if (!_isAncestor(group, s.parent, caller)) revert NotAncestorOrSelf();
                // A deactivated ancestor must not retain authority over its descendants
                // (mirror of the active-check in _lockEntityInternal).
                if (!group.entitiesByAddress[caller].active) revert EntityNotActive();
                // HOLE 3 consistency: a locked ancestor cannot unlock descendants.
                if (!isLock && group.entitiesByAddress[caller].locked) revert EntityLocked();
            }
        }

        return isLock
            ? _lockRecursive(group, chainHash, subtreeRoot, includeSubtreeRoot)
            : _unlockRecursive(group, chainHash, subtreeRoot, includeSubtreeRoot);
    }

    // ========== INTERNAL HELPER FUNCTIONS ==========

    function _lockRecursive(
        ChainedEntityGroup storage group,
        bytes32 chainHash,
        address entity,
        bool lockSelf
    ) private returns (uint256 count) {
        ChainedEntityStruct storage e = group.entitiesByAddress[entity];
        if (!e.active) return 0;

        if (lockSelf && !e.locked) {
            e.locked = true;
            emit ChEntyLocked(entity, chainHash, msg.sender, block.timestamp);
            count++;
        }

        address[] storage children = group.childrenByParent[entity];
        for (uint256 i = 0; i < children.length; i++) {
            count += _lockRecursive(group, chainHash, children[i], true);
        }
    }

    function _unlockRecursive(
        ChainedEntityGroup storage group,
        bytes32 chainHash,
        address entity,
        bool unlockSelf
    ) private returns (uint256 count) {
        ChainedEntityStruct storage e = group.entitiesByAddress[entity];
        if (!e.active) return 0;

        if (unlockSelf && e.locked) {
            e.locked = false;
            emit ChEntyUnlocked(entity, chainHash, msg.sender, block.timestamp);
            count++;
        }

        address[] storage children = group.childrenByParent[entity];
        for (uint256 i = 0; i < children.length; i++) {
            count += _unlockRecursive(group, chainHash, children[i], true);
        }
    }

    // WARNING! deativates all children too!!!
    // TODO RENAME this to deactivateHeirarchy
    // If you just want to deactivate yourself use addChainedEntity and set active to false.
    // but that is a BAD idea because:
    // MUST deactivate all legacy for readability
    // because calculate fee STOPS at first deactivated child anyway.
    function _deactivateChainedEntityLegacy(
        bytes32 chainHash,
        address entity,
        bool deactivateSelf
    ) private {
        ChainedEntityGroup storage group = chainedEntityGroupsByHash[chainHash];
        ChainedEntityStruct storage entityStruct = group.entitiesByAddress[entity];

        if (!entityStruct.active) return;

        if (deactivateSelf) {
            entityStruct.active = false;
            emit ChEntyUpdate(
                entity,
                entityStruct.parent,
                msg.sender,
                ACTION_REMOVE,
                uint8(entityStruct.feeValues.length),
                false,
                block.timestamp
            );
        }

        address[] storage children = group.childrenByParent[entity];
        for (uint256 i = 0; i < children.length; i++) {
            _deactivateChainedEntityLegacy(chainHash, children[i], true);
        }
    }

    /// @dev Unified parent-chain walker used by every "is X reachable upward from Y?" query.
    ///
    ///   • If `targetAncestor != address(0)` (target-finding mode):
    ///       Walks up from `startEntity` and returns the first entity address whose value
    ///       equals `targetAncestor`.  Returns address(0) if not found within the cycle guard.
    ///
    ///   • If `targetAncestor == address(0)` (root-finding mode):
    ///       Walks up from `startEntity` and returns the address of the ROOT entity
    ///       (the one whose `parent == address(0)`).  Returns address(0) if startEntity is
    ///       itself address(0), if the chain runs into a deleted entity, or if the chain
    ///       exceeds the cycle-guard limit.
    ///
    /// Callers that only need a boolean "is this an ancestor?" answer should use the
    /// `_isAncestor` wrapper below.  Callers that need the root entity's metadata
    /// (e.g. its `blockTimestamp` for tiered-admin checks) call this directly with
    /// `targetAncestor == address(0)`.
    function _walkUp(
        ChainedEntityGroup storage group,
        address startEntity,
        address targetAncestor
    ) internal view returns (address) {
        address current = startEntity;
        for (uint256 i = 0; i < 100 && current != address(0); i++) {
            if (targetAncestor != address(0)) {
                // TARGET-FINDING: stop when we hit the named target.
                if (current == targetAncestor) return current;
            } else {
                // ROOT-FINDING: stop when we find an entity whose parent is the zero address.
                if (group.entitiesByAddress[current].parent == address(0)) return current;
            }
            current = group.entitiesByAddress[current].parent;
        }
        return address(0);
    }

    /// @dev Convenience wrapper — returns true if `target` lies on the parent chain of
    ///      `startEntity` (inclusive of `startEntity` itself).  Equivalent to
    ///      `_walkUp(group, startEntity, target) != address(0)`.
    function _isAncestor(ChainedEntityGroup storage group, address startEntity, address target) internal view returns (bool) {
        return _walkUp(group, startEntity, target) != address(0);
    }

    // ========== QUERY FUNCTIONS ==========

    function isChainedEntity(string calldata chainType, address entity) external view returns (bool) {
        bytes32 chainHash = keccak256(bytes(chainType));
        return chainedEntityGroupsByHash[chainHash].entitiesByAddress[entity].active;
    }

    function isChainedEntityFast(bytes32 hashedChainType, address entity) external view returns (bool) {
        return chainedEntityGroupsByHash[hashedChainType].entitiesByAddress[entity].active;
    }

    function getChainedEntity(string calldata chainType, address entity) external view returns (ChainedEntityStruct memory) {
        bytes32 chainHash = keccak256(bytes(chainType));
        ChainedEntityStruct storage entityStruct = chainedEntityGroupsByHash[chainHash].entitiesByAddress[entity];
        if (!entityStruct.active) revert EntityNotActive();
        return entityStruct;
    }

    function getActiveChainedEntities(string calldata chainType) external view returns (ChainedEntityStruct[] memory) {
        bytes32 chainHash = keccak256(bytes(chainType));
        ChainedEntityGroup storage group = chainedEntityGroupsByHash[chainHash];

        uint256 count = 0;
        for (uint256 i = 0; i < group.rootNodes.length; i++) {
            count += _countActiveDescendants(group, group.rootNodes[i]);
        }

        ChainedEntityStruct[] memory entities = new ChainedEntityStruct[](count);

        uint256 index = 0;
        for (uint256 i = 0; i < group.rootNodes.length; i++) {
            index = _collectActiveDescendants(group, group.rootNodes[i], entities, index);
        }

        return entities;
    }

    function _countActiveDescendants(
        ChainedEntityGroup storage group,
        address entity
    ) internal view returns (uint256) {
        ChainedEntityStruct storage entityStruct = group.entitiesByAddress[entity];

        if (!entityStruct.active) return 0;

        uint256 count = 1;

        address[] storage children = group.childrenByParent[entity];
        for (uint256 i = 0; i < children.length; i++) {
            count += _countActiveDescendants(group, children[i]);
        }

        return count;
    }

    function _collectActiveDescendants(
        ChainedEntityGroup storage group,
        address entity,
        ChainedEntityStruct[] memory entities,
        uint256 index
    ) internal view returns (uint256) {
        ChainedEntityStruct storage entityStruct = group.entitiesByAddress[entity];

        if (!entityStruct.active) return index;

        entities[index] = entityStruct;
        index++;

        address[] storage children = group.childrenByParent[entity];
        for (uint256 i = 0; i < children.length; i++) {
            index = _collectActiveDescendants(group, children[i], entities, index);
        }

        return index;
    }

    function _getActiveEntityAddresses(
        ChainedEntityGroup storage group
    ) private view returns (address[] memory) {
        uint256 count = 0;
        for (uint256 i = 0; i < group.rootNodes.length; i++) {
            count += _countActiveDescendants(group, group.rootNodes[i]);
        }

        address[] memory addresses = new address[](count);
        uint256 index = 0;
        for (uint256 i = 0; i < group.rootNodes.length; i++) {
            index = _collectActiveAddressesRecursive(group, group.rootNodes[i], addresses, index);
        }

        return addresses;
    }

    function _collectActiveAddressesRecursive(
        ChainedEntityGroup storage group,
        address entity,
        address[] memory addresses,
        uint256 index
    ) private view returns (uint256) {
        ChainedEntityStruct storage entityStruct = group.entitiesByAddress[entity];

        if (!entityStruct.active) return index;

        addresses[index] = entity;
        index++;

        address[] storage children = group.childrenByParent[entity];
        for (uint256 i = 0; i < children.length; i++) {
            index = _collectActiveAddressesRecursive(group, children[i], addresses, index);
        }

        return index;
    }

    function _findParentIndexInAddresses(
        address[] memory addresses,
        address parentAddr,
        uint256 currentIndex
    ) private pure returns (uint256) {
        for (uint256 j = 0; j < currentIndex; j++) {
            if (addresses[j] == parentAddr) {
                return j;
            }
        }
        return addresses.length;
    }

    // ========== FEE CALCULATION AND DISTRIBUTION ==========
    // v43108: the old TODO/_scale6ToDecimals dead helper is GONE — output scaling to
    // official-stable atomics now happens inside calculateChainedAmounts via stableScale.

    /**
     * @notice Calculate chained amounts for hierarchical entities
     * @dev ⚠️  COMPLIANCE REMINDER: Caller is responsible for ensuring fee collection
     *      complies with applicable securities laws. See contract header for details.
     *      Transaction-related fees (types 0-2) may require broker-dealer registration.
     *
     * @param chainType The chain type hash
     * @param totalVal Base value (0 = NO_VALUE, meaning only absolute values apply)
     * @param maxPct Maximum cumulative percentage allowed in basis points (5000 = 50%, 10000 = 100%)
     * @param feeType Which fee type to calculate (0-255)
     *        - Types 0-2: Transaction-related (⚠️  SEC regulated for platform collection)
     *        - Types 3-4: Service fees (✅ Safe for platform collection)
     *        - Types 5-255: Reserved for future use
     * @return calculatedAmounts Array of calculated amounts per entity
     * @return totalAmount Sum of all amounts for the requested feeType
     */
    /// @notice Calculate chained fee amounts using hash (GAS-OPTIMIZED: ~200-300 gas savings)
    /// @dev Saves gas by avoiding ABI encoding overhead (96 bytes for string vs 32 bytes for hash)
    /// @param totalVal Transaction value for percentage calculations
    /// @param maxPct Maximum percentage (basis points) to cap total fees
    /// @param feeTypeHash Keccak256 hash of fee type label (e.g., keccak256("Transfer"))
    /// @return calculatedAmounts Array of calculated amounts per entity
    /// @return totalAmount Total fee amount across all entities
    function calculateChainedAmounts(
        uint256 totalVal,
        uint256 maxPct,
        bytes32 feeTypeHash
    ) external view returns (
        CalculatedEntityAmount[] memory calculatedAmounts,
        uint256 totalAmount
    ) {
        uint8 feeType = feeTypeHashToType[feeTypeHash];
        if (feeType == 0) revert FeeTypeNotDefined();
        // `this.X(...)` (external self-CALL) is intentional. Calling the explicit
        // overload directly would require it to be `public` (or to extract its body
        // into an `internal` worker that both overloads wrap). Both approaches add
        // ~1KB of bytecode because Solidity duplicates the ABI-encoder for this
        // complex memory return tuple (CalculatedEntityAmount[], uint256) per
        // external entry. The `this.X(...)` pattern piggybacks on RETURNDATACOPY,
        // avoiding a second encoder. Costs ~2,550 gas/tx but saves ~1KB of code.
        // Already tested both alternatives — DO NOT repeat. Keep `external`.
        return this.calculateChainedAmounts(DEFAULT_FEE_CHAIN_TYPE, totalVal, maxPct, feeType);
    }

    /// @notice Calculate chained fee amounts (advanced - custom chain type)
    /// @dev ⚠️ CRITICAL DECIMAL CONVENTION (v43108):
    ///      • ALL fees are STORED in storage as canonical 6-dec units (chain-agnostic;
    ///        $10 = 10_000_000 on every chain — templates never change per chain)
    ///      • totalVal MUST be passed in canonical 6-dec units
    ///      • Internal math (percent, maxPct cap) runs entirely in canonical 6-dec
    ///      • OUTPUTS (amounts + totalAmount) are scaled ×stableScale to the official
    ///        stablecoin's REAL atomic units (×1 on 6-dec chains, ×1e12 on 18-dec BNB-peg)
    ///        — EXCEPT token-denominated fee types 7/14 which are returned unscaled
    ///      • Consumers that pull the official stable can therefore permit/transfer the
    ///        returned amounts AS-IS on any chain
    ///      • SaleManager's abstract-fiat Purchase path divides outputs back by stableScale()
    function calculateChainedAmounts(
        bytes32 chainType,
        uint256 totalVal,
        uint256 maxPct,
        uint8 feeType
    ) external view returns (
        CalculatedEntityAmount[] memory calculatedAmounts,
        uint256 totalAmount
    ) {
        // ⚠️ DEVELOPER CHECK: Fee type must have a label (catches design errors early!)
        if (feeType == 0 || feeType > ABSOLUTE_MAX_FEE_TYPES) revert FeeTypeOutOfRange();
        uint8 labelIndex = feeType - 1;  // Type 1-50 → Index 0-49
        if (bytes(feeTypeLabels[labelIndex]).length == 0) revert FeeTypeNotDefined();

        // -------------------------------------------------------------------------
        // PEG: token-18-dec → stable-6-dec conversion for percent TRANSFER fees only.
        //
        // IssueToken.transfer() is the only legitimate caller passing `totalVal > 0`
        // into a Transfer-fee calculation (feeType == 6); it passes the raw token
        // amount in 18-dec units. Every OTHER fee path (Activation, SalesReg, Purchase,
        // Holder, Product/Property-NFT transfers, …) is already stablecoin-denominated
        // upstream and passes `totalVal` in 6-dec or `0` for absolute-only flows.
        //
        // We therefore guard the conversion narrowly to (feeType == 6 && totalVal > 0).
        // For NFT transfer fee types and all non-transfer types the input is left
        // untouched — percent NFT transfer fees have no meaningful peg semantics.
        //
        // Peg unset (0): zero out `totalVal` so percent transfer fees evaluate to 0,
        // exactly preserving the historical default. Absolute (value) transfer fees
        // are unaffected — the value-fee branch below does not read `totalVal`.
        //
        // EXEC WITHDRAW NOTE: ExecutivePeerTreasury.executiveWithdrawTokens still passes
        // `0` for IssueToken executive withdrawals (intentional — exec withdrawals are
        // SmartContract→User and remain percent-fee-exempt). The peg does not engage
        // there, so this change is invisible to EPT.
        // -------------------------------------------------------------------------
        if (feeType == 6 && totalVal > 0) {
            // Priority:
            //   1) DUAL FEED override (live): if both feeds set AND both return fresh
            //      positive prices, derive the peg from token_usd / stable_usd directly.
            //   2) STATIC peg fallback: use `tokensPerStableCoinPegX1e6` if set.
            //   3) Neither set → totalVal = 0 → percent transfer fees evaluate to 0
            //      (preserves historical default).
            //
            // Feed math (both Chainlink prices are 8-dec by convention; if mismatched
            // decimals are ever introduced, both setters can be re-deployed in tandem):
            //   tokens_per_stable_X1e6 = (stable_usd * 1e6) / token_usd
            // then conversion is the same as the static path:
            //   stable_6 = totalVal_18 / (peg_x1e6 * 1e6)
            uint256 pegX1e6 = 0;

            // --- FEED OVERRIDE (revert-able block) -----------------------------
            address _tFeed = tokenUsdFeed;
            address _sFeed = stableUsdFeed;
            if (_tFeed != address(0) && _sFeed != address(0)) {
                uint256 tokenUsd  = getPegFeedPrice(_tFeed);
                uint256 stableUsd = getPegFeedPrice(_sFeed);
                if (tokenUsd > 0 && stableUsd > 0) {
                    // Decimal-agnostic: both prices are same Chainlink decimals so cancel.
                    pegX1e6 = (stableUsd * 1e6) / tokenUsd;
                }
            }
            // --- END FEED OVERRIDE ---------------------------------------------

            if (pegX1e6 == 0) pegX1e6 = tokensPerStableCoinPegX1e6;
            totalVal = (pegX1e6 == 0) ? 0 : (totalVal / (pegX1e6 * 1e6));
        }

        ChainedEntityGroup storage group = chainedEntityGroupsByHash[chainType];

        address[] memory entityAddresses = _getActiveEntityAddresses(group);

        uint256[] memory amounts = new uint256[](entityAddresses.length);
        uint256[] memory parentVals = new uint256[](entityAddresses.length);

        totalAmount = 0;

        for (uint256 i = 0; i < entityAddresses.length; i++) {
            ChainedEntityStruct storage entity = group.entitiesByAddress[entityAddresses[i]];

            uint256 feeAmount = 0;
            uint8 feeFlags = 0;
            bool found = false;

            // Direct array access: feeType 1-50 maps to index 0-49
            // Only access if within the entity's array bounds (dynamic sizing)
            if (feeType >= 1 && feeType <= entity.feeValues.length) {
                uint256 feeIndex = feeType - 1;
                feeAmount = entity.feeValues[feeIndex];
                feeFlags = uint8(entity.feeFlags[feeIndex]);  // Convert bytes1 to uint8
                found = (feeAmount > 0);
            }

            if (!found) {
                amounts[i] = 0;
                parentVals[i] = 0;
                continue;
            }

            uint256 amount = 0;
            bool isPercent = (feeFlags & 0x01) != 0;
            bool isTaker = (feeFlags & 0x02) != 0;

            if (!isPercent) {
                // VALUE FEE: feeAmount is already stored in 6-decimal stablecoin units
                // Return as-is (no conversion needed)
                amount = feeAmount;

                if (isTaker && entity.parent != address(0)) {
                    uint256 parentIdx = _findParentIndexInAddresses(entityAddresses, entity.parent, i);
                    if (parentIdx < entityAddresses.length) {
                        uint256 parentVal = parentVals[parentIdx];

                        if (amount > (parentVal / 2)) {
                            amount = 0;
                        } else {
                            parentVals[parentIdx] = parentVal - amount;
                        }
                    }
                }
            } else {
                // PERCENT FEE: compute directly in 6-dec stablecoin units
                // feeAmount is basis points (e.g., 250 = 2.5%)
                // totalVal MUST be in 6-decimal stablecoin units (matching USDC)
                // Final output is in 6-decimal stablecoin units
                if (entity.parent == address(0)) {
                    if (totalVal > 0) {
                        amount = (totalVal * feeAmount) / BASIS_POINTS_DIVISOR;  // 6-dec throughout
                    }
                } else {
                    uint256 parentIdx = _findParentIndexInAddresses(entityAddresses, entity.parent, i);
                    uint256 parentVal = parentVals[parentIdx];

                    if (isTaker) {
                        // parentVal is already in 6-dec units, compute directly without 18-dec conversion
                        amount = (parentVal * feeAmount) / BASIS_POINTS_DIVISOR;  // 6-dec result

                        if (amount > (parentVal / 2)) {
                            amount = 0;
                        } else {
                            parentVals[parentIdx] = parentVal - amount;
                        }
                    } else {
                        if (totalVal > 0) {
                            amount = (totalVal * feeAmount) / BASIS_POINTS_DIVISOR;  // 6-dec throughout
                        }
                    }
                }
            }

            amounts[i] = amount;
            parentVals[i] = amount;
            totalAmount += amount;
        }

        // Validate total doesn't exceed maxPct of totalVal
        // totalAmount is in 6-dec stable units, totalVal is also in 6-dec now
        if (totalVal > 0 && maxPct > 0) {
            uint256 maxAllowed = (totalVal * maxPct) / BASIS_POINTS_DIVISOR;  // 6-dec throughout
            if (totalAmount > maxAllowed) revert CumulativePercentageExceedsMaximum();
        }

        // --- v43108 OUTPUT SCALING: canonical 6-dec → official-stable ATOMICS ---
        // Storage/templates/internal math above stay canonical 6-dec (chain-agnostic).
        // Outputs are multiplied by `stableScale` (10**(stableDecimals-6); 1 on 6-dec
        // chains, 1e12 on 18-dec BNB-peg chains) so that EVERY consumer that permits/
        // pulls these amounts as ERC-20 atomics (CFPH/CF deploy fee, IssueToken
        // activation + transfer fees, EPT exec-withdraw, NFT transfer managers,
        // ProductSaleManager, RestrictedSaleManager) is correct with NO caller change.
        //
        // EXCLUDED: token-denominated fee types — 7 "TokenPurchase" and 14
        // "TemplateControllerTokenPurchaseAndTransfer" (PCRW-TTF). Those values are
        // IssueToken MICRO-units by convention (callers lift them ×1e12 to token wei);
        // stable decimals are irrelevant to them.
        //
        // SaleManager "Purchase" (type 4) is the one ABSTRACT-fiat consumer: it divides
        // outputs back by stableScale() before its oracle conversion (see ITSM v43108).
        uint256 outScale = (feeType == 7 || feeType == 14) ? 1 : (stableScale == 0 ? 1 : stableScale);

        // Build result array
        calculatedAmounts = new CalculatedEntityAmount[](entityAddresses.length);
        for (uint256 i = 0; i < entityAddresses.length; i++) {
            address key = entityAddresses[i];
            address payee = key;
            ChainedEntityStruct storage ent = group.entitiesByAddress[key];
            if (ent.parent == address(0)) {
                address p = payoutAddressByRoot[chainType][key];
                if (p != address(0)) payee = p;
            }
            calculatedAmounts[i] = CalculatedEntityAmount({
                entityAddress: payee,
                amount: amounts[i] * outScale
            });
        }

        return (calculatedAmounts, totalAmount * outScale);
    }

    /**
     * @notice Manually trigger treasury notification for buyback checks
     * @dev Called by contracts after custom fee distribution (e.g., SaleManager purchase fees)
     * @dev Does NOT trigger for holder fees (to prevent recursion)
     */
    function triggerNotify() external onlyRegisteredContract {
        _notifyProjectRevenueTreasury();
    }

    /**
     * @notice Distribute fees to entities
     * @dev ⚠️  COMPLIANCE REMINDER: This function executes fee transfers but does NOT
     *      validate regulatory compliance. Calling contract must ensure that:
     *      - Transaction-related fees (types 0-2) are only collected by broker-dealers
     *        or under valid exemptions
     *      - Platform-level collection of securities transaction fees requires SEC registration
     *      - Service fees (types 3-4) are permissible for platform collection
     *
     * @dev ⚠️ DECIMAL HANDLING (v43108):
     *      • calculateChainedAmounts() now returns stable-denominated fees ALREADY
     *        scaled to the official stablecoin's atomic units (×stableScale)
     *      • Callers paying in the OFFICIAL STABLE pass those amounts through AS-IS
     *      • Callers paying in a DIFFERENT asset (ETH, other payment tokens) must
     *        still convert: divide by stableScale() to recover canonical 6-dec, then
     *        convert to the payment asset (SaleManager purchase path does this)
     *      • Token-denominated types 7/14 arrive unscaled (IssueToken micro-units);
     *        their callers lift them ×1e12 to token wei exactly as before
     *      • This function directly transfers calculatedFees[i].amount without conversion
     *
     * @param calculatedFees Array with amounts in paymentToken decimals
     * @param payer Address paying fees (user for types 0-3, treasury for type 4)
     * @param paymentToken Token address (address(0) for ETH)
     * @return totalDistributed Total amount distributed in paymentToken decimals
     */
    function distributeFees(
        CalculatedEntityAmount[] calldata calculatedFees,
        address payer,
        address paymentToken
    ) external payable onlyRegisteredContract nonReentrant returns (uint256 totalDistributed) {
        if (payer == address(0)) revert BadAddr();

        if (paymentToken == address(0)) {
            // ETH: distribute from msg.value
            for (uint256 i = 0; i < calculatedFees.length; i++) {
                if (calculatedFees[i].amount == 0) continue;
                if (calculatedFees[i].entityAddress == address(0)) continue;

                // Optimize for ProjectRevenueTreasury
                if (calculatedFees[i].entityAddress == projectRevenueTreasury) {
                    ExecutivePeerTreasury(calculatedFees[i].entityAddress).receiveFee{value: calculatedFees[i].amount}();
                } else {
                    (bool success, ) = calculatedFees[i].entityAddress.call{value: calculatedFees[i].amount}("");
                    if (!success) revert BadType();
                }

                totalDistributed += calculatedFees[i].amount;
            }

            if (msg.value != totalDistributed) revert BadType();
        } else {
            // ERC20: validate and distribute
            try IERC20(paymentToken).totalSupply() returns (uint256) {
                // Token is valid
            } catch {
                revert BadType();
            }

            for (uint256 i = 0; i < calculatedFees.length; i++) {
                if (calculatedFees[i].amount == 0) continue;
                if (calculatedFees[i].entityAddress == address(0)) continue;

                IERC20(paymentToken).safeTransferFrom(
                    payer,
                    calculatedFees[i].entityAddress,
                    calculatedFees[i].amount
                );

                totalDistributed += calculatedFees[i].amount;
            }
        }

        _notifyProjectRevenueTreasury();
        return totalDistributed;
    }



}

// ============================================================================
//  FeeManagerInitializer — INITIALIZER + COLD-PATH SIDECAR (PROXY BUILD, delegatecall)
// ============================================================================
//  Same pattern as the other oversized models: the model's initialize() is a
//  stub that delegatecalls into this contract, which holds the ENTIRE former
//  constructor body — the fee-type label table (16 string literals × 3
//  mappings), the scalar defaults, the Controller registration, and the
//  platform-treasury config seeding — plus the ADD/UPDATE engine
//  (_addChainedEntityInternal and its full closure) that seeding calls.
//
//  v43109: this contract is ALSO the model's cold-path sidecar. Three cold
//  setters moved here outright (model keeps only _fwd() stubs):
//    • addChainedEntity (both overloads) — the ADD/UPDATE engine used to be
//      duplicated in model AND sidecar; now it exists ONLY here.
//    • addFeeType
//    • syncStableCoin
//  Everything executes against the CLONE's storage via delegatecall with an
//  unchanged msg.sender / tx.origin, so auth and behavior are byte-for-byte
//  what they were in the model. The model keeps the HOT path (calculate /
//  distribute / exemption views) and the remaining admin setters (remove,
//  locks, changeRoot, peg/feeds, PRT) in its own runtime.
//
//  STORAGE LAYOUT: same base list as the model (TreasuryConstants,
//  ReentrancyGuard, CloneInitializable) + the model's own declarations
//  re-declared below in EXACT order (the model's INIT_SIDECAR immutable
//  occupies no slot). Verified by diffing the compiled storageLayout of this
//  contract against the model's prefix.
//  Deployed by the model's own constructor (`new` in FeeManager's
//  constructor), so its address is an immutable inside the model and NO
//  factory / PPAM / UI change is required.

/// @dev v43108: minimal decimals() surface for the official stablecoin (sidecar init).
interface IStableDecimalsFM { function decimals() external view returns (uint8); }
interface IStableCoinProviderFM { function stableCoinAddress() external view returns (address); }

contract FeeManagerInitializer is TreasuryConstants, ReentrancyGuard, CloneInitializable {

    /* ===== constants (copies of the parent's — values MUST match) ===== */
    uint8 private constant ACTION_ADD = 1;
    uint8 private constant ACTION_UPDATE = 2;
    uint8 private constant ACTION_REACTIVATE = 6;
    uint256 private constant MAX_VALUE = 1000000000000;
    uint8 private constant ABSOLUTE_MAX_FEE_TYPES = 50;
    bytes32 private constant KECCAK_SUPER_ADMIN = keccak256(bytes("Super"));
    bytes32 private constant DEFAULT_FEE_CHAIN_TYPE = keccak256("PLATFORM_FEE_CHAINED_ENTITY");

    /* ===== struct copies (identical field order = identical ABI/layout) ===== */
    struct EntityFeesWithNames {
        address entityAddress;
        address parent;
        uint256[] feeValues;
        uint8[] feeFlags;
        bool permanentlyLocked;
        bool locked;
        string entityName;
        string entityID;
    }

    struct ChainedEntityStruct {
        address entityAddress;
        address parent;
        uint256[] feeValues;
        uint8[] feeFlags;
        bool active;
        bool locked;
        bool permanentlyLocked;
        uint256 blockNumber;
        uint256 blockTimestamp;
        string entityName;
        string entityID;
    }

    struct ChainedEntityGroup {
        mapping(address => ChainedEntityStruct) entitiesByAddress;
        mapping(address => address[]) childrenByParent;
        address[] rootNodes;
    }

    /// @dev Same signature as the parent's event — identical topic0.
    event ChEntyUpdate(
        address indexed entityAddress,
        address indexed parent,
        address indexed updater,
        uint8 action,
        uint8 numFees,
        bool active,
        uint256 timestamp
    );

    /// @dev Same signatures as the parent's errors — identical 4-byte selectors.
    error BadAddr();
    error Unauthorized();
    error ValExceedsMax();
    error EntityLocked();
    error EntityPermLocked();
    error EntityRootFamilyLocked();
    error GlobalAddLocked();
    error ParentNotActive();
    error OnlySuper();
    error OnlyParent();
    error ArrayLengthMismatch();
    error FeeArraysExceedMax();
    error FeeArrayLengthMustNotExceedCurrentMaxFeeType();
    /// @dev v43108: official stablecoin decimals must be within [6, 18].
    error StableDecimalsOutOfRange();
    /// @dev v43109 cold-path (addFeeType) — same signatures as the model's errors / event.
    error OnlyPlatformTreasurerOrProjectSC();
    error FeeTypeRange();
    error LabelEmpty();
    error FeeTypeAlreadyDefined();
    error FeeTypeLabelAlreadyUsed();
    event FeeTypeAdded (
        uint8 indexed feeType,
        string label,
        uint256 timestamp
    );

    /* ===== storage prefix (mirror of the model's own slots after bases) ===== */
    IController public controller;                 // slot 1 offset 1 (packs after _initState)
    uint256 public deploymentTimestamp;            // slot 2
    bool public globalAddLock;                     // slot 3
    uint256 public globalAddLockTimestamp;         // slot 4
    bool public globalFreezeLock;                  // slot 5
    uint256 public freezeDelay;                    // slot 6
    address public projectRevenueTreasury;         // slot 7
    uint256 public tokensPerStableCoinPegX1e6;     // slot 8
    address public tokenUsdFeed;                   // slot 9
    address public stableUsdFeed;                  // slot 10
    mapping(bytes32 => mapping(address => address)) private payoutAddressByRoot;      // slot 11
    mapping(address => bool) public rootFamilyLocked;                                 // slot 12
    mapping(bytes32 => ChainedEntityGroup) private chainedEntityGroupsByHash;         // slot 13
    mapping(uint8 => string) public feeTypeLabels;                                    // slot 14
    mapping(string => uint8) public feeTypeLabelToType;                               // slot 15
    mapping(bytes32 => uint8) public feeTypeHashToType;                               // slot 16
    uint8 public currentMaxFeeType;                                                   // slot 17
    uint256 public stableScale;                                                       // slot 18 (v43108 — MUST mirror the model)

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

    /// @dev v43109: every cold-path entry point is reachable ONLY through the model's _fwd()
    ///      delegatecall (clone → model → sidecar). A direct call would run against this
    ///      sidecar's own (empty) storage — refuse it.
    modifier notDirect() {
        if (address(this) == __SELF) revert DirectCallForbidden();
        _;
    }

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

    // ===== CLONE CONSTRUCTOR-EQUIVALENT (former constructor, verbatim) =====
    // Reached ONLY via the model stub's delegatecall (one-shot: the stub's
    // `initializer` modifier runs before delegating, so NO `initializer`
    // modifier here — it would read the wrong flag on a direct call anyway).
    function initialize(IController _controller, EntityFeesWithNames[] memory platformTreasuryConfigs, address _officialStable) external {
        if (address(this) == __SELF) revert DirectCallForbidden();
        if (address(_controller) == address(0)) revert BadAddr();
        controller = _controller;
        deploymentTimestamp = block.timestamp;
        freezeDelay = 180 days; // ex-inline initializer (see model's declaration)

        // v43108: derive the canonical-6-dec → stable-atomics output multiplier from the
        // official stablecoin's REAL decimals (ETH USDC/USDT = 6 → scale 1; BNB-peg
        // USDT/USDC = 18 → scale 1e12). Fee configs/templates stay canonical 6-dec;
        // calculateChainedAmounts() scales OUTPUTS only. See model's stableScale docblock.
        if (_officialStable == address(0)) revert BadAddr();
        uint8 _sd = IStableDecimalsFM(_officialStable).decimals();
        if (_sd < 6 || _sd > 18) revert StableDecimalsOutOfRange();
        stableScale = 10 ** uint256(_sd - 6);

        // Register FeeManager as official SmartContract (like IssueToken does)
        // This allows FeeManager to call distributeFees() and other protected functions.
        // Under delegatecall address(this) is the CLONE — exactly what must register.
        _controller.init(address(this), "FeeManager");

        // Initialize fee type labels (UI can query by ARRAY INDEX 0-12!)
        // Fee Type → Array Index → Label Key
        // Type 1 → Index 0 → feeTypeLabels[0]
        // Type 2 → Index 1 → feeTypeLabels[1] ... etc
        //
        // CONVENTION: "Mint" = primary purchase (first sale / initial creation)
        //             "Purchase" = secondary purchase (escrow-based resale)
        //             "Transfer" = non-sale movement (wallet-to-wallet)
        //
        // NOTE (future expansion, not currently enforced/collected):
        // Planned labels for token-denominated fee collection (in IssueToken units) are:
        //  - "TokenTransfer"
        // These should remain unset (and templates should keep those slots at 0) until the
        // token-type xfer collection/distribution path implemented - near-zero use cases.
        //
        // Type 14 "TemplateControllerTokenPurchaseAndTransfer" (PCRW-TTF) IS collected:
        // ONE fixed fee, denominated in the CURATION controller's own token, covering
        // BOTH activity kinds of a project deployed under a CURATED white-label key:
        //   • regular transfers between non-official-SC parties — charged by IssueToken
        //     (its transfer path, inside the shouldCollectFees policy), and
        //   • purchases — charged by IssueTokenSaleManager in _completePurchase (the
        //     ITSM→buyer token transfer itself is official-SC-exempt, so ITSM collects).
        // Both are pulled from the INITIATING party (sender/buyer), who must approve
        // the parent token to THIS FeeManager. The asset is resolved via
        // WLC.resolveTemplateFeeTokenFor and cached in the child IssueToken
        // (templateFeeToken — the single arming switch for both charge sites).
        // AMOUNTS/RECIPIENTS live HERE like every other fee — mirrored from the PU
        // domain template at deploy. FIXED-ONLY by construction: callers pass
        // totalVal = 0, so percent slots always evaluate to 0. Seeded here for NEW
        // FeeManagers; EXISTING instances (e.g. the platform's own, which the
        // template-authoring UI reads labels from) gain it via one
        // addFeeType("TemplateControllerTokenPurchaseAndTransfer") admin tx.
        //
        // ⚠️ WHY A NEW FEE TYPE STILL NEEDS A MODEL RESEED (v43109 lesson): addFeeType() does
        // let any EXISTING FeeManager grow post-deploy, but the PU fee TEMPLATE is applied
        // right here in initialize() — BEFORE anyone can call addFeeType() on the new clone.
        // _addChainedEntityInternal reverts FeeArrayLengthMustNotExceedCurrentMaxFeeType when a
        // template row carries more slots than currentMaxFeeType, so a template widened to a
        // type this table does not seed bricks EVERY new project deployment in phase 1. Hence
        // every template-carried fee type must be in _labelTable (width == currentMaxFeeType).
        string[16] memory labels = _labelTable();
        for (uint256 i = 0; i < 16; i++) {
            string memory label = labels[i];
            uint8 feeType = uint8(i + 1);
            feeTypeLabels[uint8(i)] = label;
            feeTypeLabelToType[label] = feeType;
            feeTypeHashToType[keccak256(bytes(label))] = feeType;
        }

        currentMaxFeeType = 16;  // Platform-initialized types (1-16)
        // Indices 16-49 reserved for future types 17-50

        // Process platform treasury configs (default fee entities)
        // This replaces the old Controller's treasury config processing
        for (uint256 i = 0; i < platformTreasuryConfigs.length; i++) {
            EntityFeesWithNames memory config = platformTreasuryConfigs[i];

            // Validate address
            if (config.entityAddress == address(0)) revert BadAddr();

            // Add to fee hierarchy using default chain type
            // First config is typically the ROOT (PLATFORM_TREASURER)
            _addChainedEntityInternal(DEFAULT_FEE_CHAIN_TYPE, config);
        }
    }

    /// @notice The 16 platform fee-type labels, index i = fee type i+1.
    function _labelTable() private pure returns (string[16] memory t) {
        t[0]  = "Deploy";                  // Type 1
        t[1]  = "Activation";              // Type 2
        t[2]  = "SalesReg";                // Type 3
        t[3]  = "Purchase";                // Type 4
        t[4]  = "Holder";                  // Type 5
        t[5]  = "Transfer";                // Type 6
        t[6]  = "TokenPurchase";           // Type 7
        t[7]  = "ProductNFTTransfer";      // Type 8  - Non-sale movement of product NFTs
        t[8]  = "ProductNFTMint";          // Type 9  - Primary purchase (minting via ProductSaleManager)
        t[9]  = "ProductNFTPurchase";      // Type 10 - Secondary escrow-based product sales
        t[10] = "PropertyNFTMint";         // Type 11 - Primary registration (government minting)
        t[11] = "PropertyNFTTransfer";     // Type 12 - Non-sale property NFT transfers
        t[12] = "PropertyNFTPurchase";     // Type 13 - Secondary escrow-based property sales
        t[13] = "TemplateControllerTokenPurchaseAndTransfer"; // Type 14 - PCRW-TTF: fixed fee in the curation controller's token (purchases + transfers)
        t[14] = "ListingFee";              // Type 15 - RestrictedSaleManager: seller-side fee on createListing / createOracleListing
                                           //           (absolute-only: RSM calls calculateChainedAmounts(0, …) so percent slots yield 0).
                                           //           EXISTING FeeManagers gain it via one addFeeType("ListingFee") admin tx;
                                           //           RSM try/catches FeeTypeNotDefined → "no listing fee" on legacy instances.
        t[15] = "CapTableExport";          // Type 16 - v43109 IssueTokenDistributionManager.payCapTableExportFee(): TransferAgent /
                                           //           TokenAdmin pays it to open a timed window of full registrant-roster exports on
                                           //           the registrar (absolute-only: DM calls calculateChainedAmounts(0, …)).
                                           //           EXISTING FeeManagers gain it via one addFeeType("CapTableExport") admin tx;
                                           //           DM.getCapTableExportFee() try/catches FeeTypeNotDefined → "no fee" on legacy instances.
    }

    // ========================================================================
    //  v43109 COLD-PATH SETTERS (moved here from the model — EIP-170 relief).
    //  Reached via FeeManager._fwd() (raw calldata delegatecall); bodies are
    //  the model's former ones, verbatim. They run against the CLONE's storage
    //  (layout mirrored above) with msg.sender / tx.origin unchanged, so every
    //  auth check is byte-identical to when they lived in the model.
    //  ABI of the model is unchanged: the stubs keep the same selectors and
    //  bubble the ABI-encoded return value produced here.
    // ========================================================================

    /// @notice Add a chained entity to the fee hierarchy (simplified - uses default chain type)
    function addChainedEntity(EntityFeesWithNames memory entity) external notDirect returns (bool) {
        return _addChainedEntityGated(DEFAULT_FEE_CHAIN_TYPE, entity);
    }

    /// @notice Add a chained entity to the fee hierarchy (advanced - custom chain type)
    function addChainedEntity(bytes32 chainType, EntityFeesWithNames memory entity) external notDirect returns (bool) {
        return _addChainedEntityGated(chainType, entity);
    }

    // ISTAKER GATE — three-step authorization for entities that carry any isTaker flag:
    //   (1) Cheap pre-scan: any bit1 set in entity.feeFlags?  If none, gate is skipped entirely.
    //   (2) Discover the ROOT of the subtree this entity sits in (or will sit in) and read
    //       its blockTimestamp.  The ROOT — not the entity itself — determines which admin
    //       tier may authorize "take from parent" semantics.  This stops a project admin from
    //       grafting a taker entity beneath a platform-owned constructor root and siphoning
    //       fee flow.
    //   (3) Require _isTieredAdmin(caller, rootBlockTimestamp).  Constructor-tier root →
    //       Platform TokenAdmin only; project-tier root → Project Admin.
    //
    // initialize() calls _addChainedEntityInternal directly, bypassing this gate intentionally —
    // initial isTaker entities are seeded at deploy time before any caller exists.
    function _addChainedEntityGated(bytes32 chainType, EntityFeesWithNames memory entity) private returns (bool) {
        // (1) Cheap pre-scan: any isTaker flag at all?
        bool hasTaker = false;
        for (uint256 i = 0; i < entity.feeFlags.length; i++) {
            if ((entity.feeFlags[i] & 0x02) != 0) { hasTaker = true; break; }
        }

        if (hasTaker) {
            // (2) Find the ROOT this entity belongs to and pull its blockTimestamp.
            ChainedEntityGroup storage group = chainedEntityGroupsByHash[chainType];
            uint256 rootBlockTimestamp;

            ChainedEntityStruct storage existing = group.entitiesByAddress[entity.entityAddress];
            if (existing.entityAddress != address(0)) {
                // UPDATE path — entity is already in the tree.  Walk up from the entity itself.
                address root = _walkUp(group, entity.entityAddress, address(0));
                if (root == address(0)) revert Unauthorized();
                rootBlockTimestamp = group.entitiesByAddress[root].blockTimestamp;
            } else if (entity.parent == address(0)) {
                // ADD path, NEW ROOT — the entity is its own root.  Its blockTimestamp will be
                // block.timestamp (set inside _addChainedEntity), which is post-deployment by
                // definition → project tier.  Downstream _isTieredAdmin will demand a
                // Project Admin (Super, TreasuryAdmin, OR TokenAdmin).
                rootBlockTimestamp = block.timestamp;
            } else {
                // ADD path, NEW CHILD — walk up from the declared parent to find the existing root.
                address root = _walkUp(group, entity.parent, address(0));
                if (root == address(0)) revert Unauthorized();
                rootBlockTimestamp = group.entitiesByAddress[root].blockTimestamp;
            }

            // (3) Tiered-admin check against the ROOT's tier.  _isTieredAdmin already resolves
            //     SmartContract callers via _effectiveCaller / tx.origin — so a factory contract
            //     calling on behalf of a Platform TokenAdmin (constructor tier) or a Project
            //     Admin (project tier) still passes.
            if (!_isTieredAdmin(_effectiveCaller(), rootBlockTimestamp)) {
                revert Unauthorized();
            }
        }

        return _addChainedEntityInternal(chainType, entity);
    }

    /**
     * @notice Add a new fee type label (ADD-ONLY - cannot update or remove)
     * @param label Human-readable label (e.g., "Activation", "SalesReg")
     * @dev ⚠️ AUTO-INCREMENT: Fee type number is automatically assigned (currentMaxFeeType + 1)
     * @dev ⚠️ IMMUTABLE: Once added, fee type labels CANNOT be changed or removed
     * @dev Authorized callers: registered SmartContract (msg.sender direct),
     *      or platform TreasuryAdmin (via _effectiveCaller())
     */
    function addFeeType(string calldata label) external notDirect {
        if (!_isMsgSenderSC()) {
            if (!controller.isPlatformAdmin(_effectiveCaller(), KECCAK_TREASURY_ADMIN)) {
                revert OnlyPlatformTreasurerOrProjectSC();
            }
        }

        uint8 feeType = currentMaxFeeType + 1;

        // Validate fee type range (1 to absolute max)
        if (feeType == 0 || feeType > ABSOLUTE_MAX_FEE_TYPES) {
            revert FeeTypeRange();
        }

        // Validate label not empty
        if (bytes(label).length == 0) {
            revert LabelEmpty();
        }

        // Store label at ARRAY INDEX (feeType - 1): Type 1 → Index 0, Type 2 → Index 1, etc.
        uint8 labelIndex = feeType - 1;

        // ⚠️ ADD-ONLY: Prevent updates to existing fee types (immutability for safety)
        if (bytes(feeTypeLabels[labelIndex]).length > 0) {
            revert FeeTypeAlreadyDefined();
        }
        // Prevent label reuse: would silently overwrite the reverse maps
        // (feeTypeLabelToType / feeTypeHashToType) and re-route every hash-based
        // caller from the original feeType to this new (empty) slot.
        if (feeTypeLabelToType[label] != 0) {
            revert FeeTypeLabelAlreadyUsed();
        }

        // Store forward mapping (type → label)
        feeTypeLabels[labelIndex] = label;

        // Store reverse mappings
        feeTypeLabelToType[label] = feeType;
        feeTypeHashToType[keccak256(bytes(label))] = feeType;

        // Track the highest defined fee TYPE (not index)
        if (feeType > currentMaxFeeType) {
            currentMaxFeeType = feeType;
        }

        emit FeeTypeAdded(feeType, label, block.timestamp);
    }

    /// @notice v43108 — Re-sync `stableScale` after the project rotates to an official
    ///         stablecoin with DIFFERENT decimals (e.g. 6-dec ETH USDC → 18-dec BNB-peg USDT).
    /// @dev    TRUSTLESS + PERMISSIONLESS by design: trusts NO caller. The label argument
    ///         is prefix-guarded and must resolve to an ACTIVE SmartContract entity on
    ///         THIS clone's OWN controller (v43108 exact-label getter); the stablecoin is
    ///         then read from THAT IssueToken's live stableCoinAddress(). Every input is
    ///         validated against authoritative on-chain state, so anyone may call: the
    ///         recompute is idempotent and can only move `stableScale` TO the value implied
    ///         by the project's live stablecoin — there is nothing a hostile caller can inject.
    ///         Stable rotation lives in EPT/IssueToken setStableCoinAddress; if a rotation
    ///         changes decimals, call this immediately after — until then every
    ///         stable-denominated fee amount is off by 10**|Δdecimals|.
    /// @param  itLabel The IssueToken's REGISTERED label, e.g. "IssueToken_DNTV". Needed
    ///         because Controller's v43108 label lookup is an EXACT match and the label
    ///         embeds the token symbol, which this clone cannot know (FeeManager is
    ///         initialized in phase 1, BEFORE the IssueToken exists). The label is NOT
    ///         trusted: (1) it must carry the strict "IssueToken_" prefix — blocks the
    ///         sibling family (IssueTokenSaleManager, IssueTokenTimeLock, ...) whose
    ///         stable-ish getters could otherwise skew the scale; (2) it must resolve to
    ///         an ACTIVE SmartContract entity on OUR OWN controller; (3) the stablecoin
    ///         is read from THAT entity's live stableCoinAddress(). Wrong labels revert.
    function syncStableCoin(string calldata itLabel) external notDirect {
        // (1) strict prefix guard — first 11 bytes must be "IssueToken_"
        bytes memory b = bytes(itLabel);
        if (b.length < 12) revert BadAddr(); // needs at least one symbol char after the prefix
        bytes11 head;
        assembly { head := mload(add(b, 32)) }
        if (head != bytes11("IssueToken_")) revert BadAddr();
        // (2) exact-label lookup on OUR controller (v43108 getter; address(0) = no active match)
        address it = controller.getOfficialEntityAddressFast(KECCAK_SMART_CONTRACT, itLabel);
        if (it == address(0)) revert BadAddr();
        // (3) live stablecoin from the resolved IssueToken
        address sc = IStableCoinProviderFM(it).stableCoinAddress();
        if (sc == address(0)) revert BadAddr();
        uint8 _sd = IStableDecimalsFM(sc).decimals();
        if (_sd < 6 || _sd > 18) revert StableDecimalsOutOfRange();
        stableScale = 10 ** uint256(_sd - 6);
    }

    // ========================================================================
    //  ADD/UPDATE ENGINE + auth helpers — SOLE HOME since v43109 (formerly
    //  verbatim copies of the model's private helpers; the model copies were
    //  removed when addChainedEntity moved here). Used by both initialize()
    //  seeding (ADD branch on a fresh clone) and the post-deploy
    //  addChainedEntity cold path (ADD or UPDATE).
    // ========================================================================

    function _effectiveCaller() internal view returns (address) {
        return _isMsgSenderSC() ? tx.origin : msg.sender;
    }

    function _isTieredAdmin(address caller, uint256 entityTimestamp) internal view returns (bool) {
        return entityTimestamp <= deploymentTimestamp
            ? controller.isPlatformAdmin(caller, KECCAK_TOKEN_ADMIN)
            : _isProjectAdmin(caller);
    }

    function _isProjectAdmin(address who) private view returns (bool) {
        return controller.isOfficialTripleEntityFast(
            KECCAK_SUPER_ADMIN, who,
            KECCAK_TREASURY_ADMIN, who,
            KECCAK_TOKEN_ADMIN, who,
            false  // OR logic — any of the three roles is sufficient
        );
    }

    function _isMsgSenderSC() private view returns (bool) {
        return controller.isOfficialEntityFast(KECCAK_SMART_CONTRACT, msg.sender);
    }

    function _walkUp(
        ChainedEntityGroup storage group,
        address startEntity,
        address targetAncestor
    ) internal view returns (address) {
        address current = startEntity;
        for (uint256 i = 0; i < 100 && current != address(0); i++) {
            if (targetAncestor != address(0)) {
                if (current == targetAncestor) return current;
            } else {
                if (group.entitiesByAddress[current].parent == address(0)) return current;
            }
            current = group.entitiesByAddress[current].parent;
        }
        return address(0);
    }

    function _isAncestor(ChainedEntityGroup storage group, address startEntity, address target) internal view returns (bool) {
        return _walkUp(group, startEntity, target) != address(0);
    }

    function _addChainedEntityInternal(bytes32 chainType, EntityFeesWithNames memory entity) private returns (bool) {
        if (entity.entityAddress == address(0)) revert BadAddr();

        if (entity.feeValues.length > ABSOLUTE_MAX_FEE_TYPES || entity.feeFlags.length > ABSOLUTE_MAX_FEE_TYPES) {
            revert FeeArraysExceedMax();
        }

        if (entity.feeValues.length != entity.feeFlags.length) {
            revert ArrayLengthMismatch();
        }

        uint8 arrayLength = uint8(entity.feeValues.length);
        if (arrayLength > currentMaxFeeType) {
            revert FeeArrayLengthMustNotExceedCurrentMaxFeeType();
        }

        for (uint256 i = 0; i < entity.feeValues.length; i++) {
            if (entity.feeValues[i] > MAX_VALUE) revert ValExceedsMax();
        }

        ChainedEntityGroup storage group = chainedEntityGroupsByHash[chainType];

        if (group.entitiesByAddress[entity.entityAddress].entityAddress != address(0)) {
            return _updateExistingEntity(group, entity);
        }

        return _addChainedEntity(group, entity);
    }

    function _updateExistingEntity(
        ChainedEntityGroup storage group,
        EntityFeesWithNames memory entity
    ) private returns (bool) {
        ChainedEntityStruct storage existing = group.entitiesByAddress[entity.entityAddress];

        if (globalFreezeLock) revert EntityPermLocked();
        if (rootFamilyLocked[_walkUp(group, entity.entityAddress, address(0))]) revert EntityRootFamilyLocked();
        if (globalAddLock && !existing.active) revert GlobalAddLocked();

        address caller = _effectiveCaller();
        bool isRootNode = (existing.parent == address(0));
        bool isSelfEditing = (entity.entityAddress == caller);

        if (isRootNode && entity.parent == address(0)) {
            if (!_isTieredAdmin(caller, existing.blockTimestamp)) {
                if (!isSelfEditing) return false;
                if (existing.locked) revert EntityLocked();
            }
        } else if (existing.parent != address(0) && existing.parent == entity.parent) {
            address rootAddr = _walkUp(group, existing.entityAddress, address(0));
            if (rootAddr == address(0)) revert Unauthorized();
            uint256 rootTimestamp = group.entitiesByAddress[rootAddr].blockTimestamp;

            if (!_isTieredAdmin(caller, rootTimestamp)) {
                if (!isSelfEditing && !_isAncestor(group, existing.parent, caller)) {
                    revert Unauthorized();
                }
                if (isSelfEditing && existing.locked) revert EntityLocked();
                if (!isSelfEditing && group.entitiesByAddress[caller].locked) revert EntityLocked();
            }
        } else {
            return false;
        }

        uint8 action;
        if (!existing.active) {
            existing.active = true;
            action = ACTION_REACTIVATE;
        } else {
            action = ACTION_UPDATE;
        }
        existing.feeValues = entity.feeValues;
        existing.feeFlags = entity.feeFlags;
        existing.entityName = entity.entityName;
        existing.entityID = entity.entityID;
        if (existing.blockTimestamp > deploymentTimestamp) {
            existing.blockTimestamp = block.timestamp;
        }

        emit ChEntyUpdate(entity.entityAddress, entity.parent, msg.sender, action, uint8(entity.feeValues.length), true, block.timestamp);
        return true;
    }

    function _addChainedEntity(
        ChainedEntityGroup storage group,
        EntityFeesWithNames memory entity
    ) internal returns (bool) {
        if (globalFreezeLock) revert EntityPermLocked();
        if (globalAddLock) revert GlobalAddLocked();

        if (entity.parent == address(0)) {
            // ROOT ENTITY: only Project Admin may add new roots.
            // `OnlySuper` error retained for ABI / selector parity with the model.
            if (!_isProjectAdmin(_effectiveCaller())) revert OnlySuper();
        } else {
            address effectiveCaller = _effectiveCaller();

            address rootAddr = _walkUp(group, entity.parent, address(0));
            if (rootAddr == address(0)) revert ParentNotActive();
            if (rootFamilyLocked[rootAddr]) revert EntityRootFamilyLocked();
            uint256 rootTimestamp = group.entitiesByAddress[rootAddr].blockTimestamp;

            if (!_isTieredAdmin(effectiveCaller, rootTimestamp)) {
                ChainedEntityStruct storage callerEntity = group.entitiesByAddress[effectiveCaller];
                if (callerEntity.entityAddress != address(0)) {
                    if (!callerEntity.active) revert Unauthorized();
                    if (callerEntity.locked) revert EntityLocked();
                }

                if (entity.parent != effectiveCaller && !_isAncestor(group, entity.parent, effectiveCaller)) {
                    revert OnlyParent();
                }
            }

            if (!group.entitiesByAddress[entity.parent].active) revert ParentNotActive();
        }

        if (entity.parent == address(0)) {
            group.rootNodes.push(entity.entityAddress);
        } else {
            group.childrenByParent[entity.parent].push(entity.entityAddress);
        }

        group.entitiesByAddress[entity.entityAddress] = ChainedEntityStruct({
            entityAddress: entity.entityAddress,
            parent: entity.parent,
            feeValues: entity.feeValues,
            feeFlags: entity.feeFlags,
            active: true,
            locked: entity.locked,
            permanentlyLocked: false,
            blockNumber: block.number,
            blockTimestamp: block.timestamp,
            entityName: entity.entityName,
            entityID: entity.entityID
        });

        emit ChEntyUpdate(entity.entityAddress, entity.parent, msg.sender, ACTION_ADD, uint8(entity.feeValues.length), true, block.timestamp);
        return true;
    }
}

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

@openzeppelin/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

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

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

    uint256 private _status;

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

    constructor() {
        _status = NOT_ENTERED;
    }

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

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

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

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

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

contracts/CloneInitializable.sol

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

pragma solidity 0.8.35;

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

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

    error AlreadyInitialized();

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

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

    error InitDelegateFailed();

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

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

contracts/TreasuryConstants.sol

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

pragma solidity 0.8.35;

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

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

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

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

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

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

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

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

interfaces/IController.sol

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

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

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

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

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

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

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

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

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

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

    // Constants
    function BASIS_POINTS_DIVISOR() external view returns (uint256);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs",
    "useLiteralContent": true
  },
  "optimizer": {
    "runs": 10000,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.