Skip to content
Verified contractExactUNLICENSED

CapitalCallManager

Address0x17f629e412efd2fc0f76b7e87d4e15f584026dee
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 700 runs
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,353,631
Creation transaction
0xbb62bba67b…4daddcb524

contracts/CapitalCallManager.sol

// SPDX-License-Identifier: UNLICENSED
// =====================================================================
//  EquityMint.org / DataCloud OS  —  Official Sovereign Issuance Suite
//  Module: CapitalCallManager.sol
//  (c) 2025-2026 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.
//
//  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.
//
//  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.
//
//  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).
// =====================================================================
// Copyright 2025-2026 US Fintech LLC, a New York company.
//
// OFFICIAL US FINTECH LLC COMPONENT
// EquityMint CapitalCallManager — admin-proposed, escrowed capital events for
// tokens issued via the EquityMint Sovereign Issuance Suite, PLUS the
// PublicMessageCerts service.
//
// TWO KINDS (v43110):
//   KIND_RAISE   — all-or-nothing capital raise ("CapitalRaise" / SubRaise):
//                  every eligible participant contributes stablecoin toward a
//                  goal; goal reached → funds kept, reward distributed pro-rata;
//                  expired under goal → every contribution refunded.
//   KIND_AUCTION — single-winner auction: bidders escrow stablecoin; each new
//                  bid must be STRICTLY higher than the current highest (so two
//                  equal bids can never both exist — the tie rule is enforced by
//                  construction); at expiry the unique highest bid is kept and
//                  the lot (if any) goes to the winner; every other bidder is
//                  refunded in the same pass.
//
// REWARD LEG (universal): a raise is "rewarded" in exactly one of three ways,
// selected by (rewardToken, stablePricePerToken):
//   • IssueToken      — rewardToken == project IssueToken, price > 0  (classic capital raise)
//   • other ERC-20    — rewardToken == any other token this treasury holds, price > 0
//   • off-chain       — rewardToken == address(0), price == 0 (terms live in `description`)
// An auction's lot is (lotAsset, lotAmount) with the same three readings. Reward
// inventory is PRE-ESCROWED at propose time: the proposal reverts unless this
// contract already holds the amount beyond what other open raises reserve.
//
// AUDIENCE (universal, both kinds):
//   • minTokenBalance — 0 = public; else IssueToken.balanceOf(participant) must be
//                       >= minTokenBalance (balance READ only — tokens are NEVER pulled)
//   • requireWhitelist — IssueToken.getUserRegistrationStatus(participant,false) != 0
//   • implicit        — whenever the reward/lot asset IS the project IssueToken, the
//                       project SaleManager's own purchase-eligibility gate ALSO applies,
//                       so a raise can never succeed with a participant the token itself
//                       would refuse to deliver to.
//
// FEES (v43110, FeeManager label-hash lookups; a FeeManager that pre-dates a
// label, or a zero amount, means "no fee"):
//   PER-ACTION, ABSOLUTE-ONLY, NON-REFUNDABLE — deducted from the gross the participant
//   sends (one permit / approve): the contract pulls the gross, pushes the fee shares to
//   the chained fee entities from its own balance, and escrows the NET. The NET is what
//   counts toward the goal / bid, what earns reward, and what a refund returns.
//   • CapitalCallPropose          — paid by the proposing TokenAdmin
//   • CapitalCallContribute       — EVERY contribution and EVERY bid (first or re-bid)
//   • CapitalCallAuctionEntrance  — a bidder's FIRST bid on an auction, in addition
//   SUCCESS-ONLY, ABSOLUTE AND/OR PERCENT — quoted on the TOTAL RAISED (successful raise)
//   or the WINNING BID (settled auction) and pushed to the fee entities FROM THE PROCEEDS
//   at settlement, push-with-fallback. Refunded raises and losing bids never pay it, so
//   nothing has to be tracked or unwound: a participant's escrow is always returned whole.
//   • CapitalCallSuccess            — reward/lot asset is the IssueToken and the
//                                     SaleManager's projectFlags bit 21 (NON-SECURITY) is OFF
//   • CapitalCallNonSecuritySuccess — used INSTEAD when there is no IssueToken leg or bit 21 is ON
//
// LOCKED FUNDS: the inherited ExecutivePeerTreasury withdrawal paths are overridden so
// an admin can never move escrowed stablecoin of OPEN events, reward/lot inventory
// reserved by OPEN events, or balances parked for claim(); only settled proceeds and
// unreserved inventory are withdrawable.
//
// WHY THIS IS NOT GOVERNANCE: a "vote" that requires the voter to attach
// stablecoin is not a vote — it is an escrowed subscription (a capital call in
// SPV/fund terms). It therefore lives in its own ExecutivePeerTreasury (this
// contract HOLDS funds between contribution and settlement), while Governance
// holds no funds at all.
//
// @author Ken Silverman
pragma solidity 0.8.35;

import "./ExecutivePeerTreasury.sol";
import "./CloneInitializable.sol";
import "../interfaces/IController.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

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

error CCM_SaleManagerNotFound();
error CCM_StablecoinNotSet();
error CCM_RaiseNotFound();
error CCM_RaiseNotActive();
error CCM_RaiseExpired();
error CCM_RaiseNotStarted();
error CCM_WrongKind();            // contribute() on an auction / bid() on a raise
error CCM_InvalidPrice();
error CCM_InvalidGoal();
error CCM_InvalidExpiration();
error CCM_InvalidRewardAsset();   // reward/lot asset is the stablecoin, or price/asset pairing inconsistent
error CCM_EmptyTitle();
error CCM_TitleTooLong();
error CCM_DescriptionTooLong();
error CCM_InsufficientTokenInventory();
error CCM_TooManyOpenRaises();
error CCM_MaxParticipantsReached();
error CCM_NotEligible();          // SaleManager purchase-eligibility gate (IssueToken leg only)
error CCM_BelowMinBalance();      // audience: IssueToken balance below the raise's minTokenBalance
error CCM_NotWhitelisted();       // audience: requireWhitelist and the participant is not whitelisted
error CCM_ZeroAmount();
error CCM_OverGoal();
error CCM_FeeExceedsAmount();     // the fee quote consumed the entire gross — nothing left to escrow
error CCM_BelowReserve();         // auction: resulting total bid below minBid
error CCM_BidNotHighest();        // auction: resulting total bid not strictly above the current highest
error CCM_NothingToClaim();
error CCM_InvalidMaxParticipants();
error CCM_CertCostNotPaid();
error CCM_EmptyCertMessage();
error CCM_TransferFailed();
error CCM_InvalidLimit();         // propose-time: a min/max contribution limit is inconsistent
error CCM_BelowMin();             // contribute: amount below minPerContribution / minPerContributor
error CCM_OverMax();              // contribute: would exceed maxPerContributor
error CCM_BadUserSignature();     // signedMessage did not ecrecover to msg.sender over rawMessage
error CCM_CertNotApproved();      // adminApprovalSig did not ecrecover to a TokenAdmin
error CCM_DirectCallForbidden();  // sidecar body called directly (not via the clone's delegatecall)
error CCM_FundsLocked();          // admin withdrawal would dip into escrowed / reserved / claimable balances
error CCM_EventsOpen();           // stablecoin cannot change while any raise / auction is ACTIVE (escrow is in the current one)

/// @dev Minimal SaleManager surface. statusMode != 0 means the user passed EVERY
///      gate the project's own SaleManager flags currently require. projectFlags
///      bit 21 = PF_NON_SECURITY (selects the non-security contribute fee label).
interface ICCMSaleManager {
    function getPurchaseEligibility(address user) external view returns (
        uint8 statusMode,
        bool isInContentMgr,
        bool isInTokenWhitelist
    );
    function projectFlags() external view returns (uint32);
}

/// @dev Minimal IssueToken surface for the per-raise whitelist option.
interface ICCMIssueToken {
    function getUserRegistrationStatus(address user, bool notGatedOverride) external view returns (uint8);
}

/// @dev Minimal EIP-2612 permit surface (USDC-style).
interface ICCMERC20Permit {
    function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
}

interface ICCMERC20 {
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
    function decimals() external view returns (uint8);
}

// ============================================================================
//  CapitalCallManagerBase — SHARED STORAGE + INTERNALS (model AND sidecar)
// ============================================================================
//  Both CapitalCallManager (the clonable model) and CapitalCallManagerSidecar
//  inherit this ONE abstract contract, so their storage layouts are identical
//  BY CONSTRUCTION (same bases, same declarations, same order) — there is no
//  hand-mirrored copy to keep in sync. Internal functions declared here are
//  compiled into whichever contract actually reaches them, so the model only
//  carries the hot-path bodies and the sidecar only the cold-path ones.
abstract contract CapitalCallManagerBase is ExecutivePeerTreasury, ReentrancyGuard, CloneInitializable {

    /// @notice Bytecode-verification tag.
    ///  v43110: KIND_AUCTION (single winner, strictly-ascending bids), universal reward leg
    ///          (IssueToken / other ERC-20 / off-chain), universal audience (minTokenBalance,
    ///          requireWhitelist), FeeManager fee types 17-21 (absolute per-action fees deducted
    ///          from the gross; success fee taken from the proceeds at settlement), admin
    ///          withdrawal locks on escrowed / reserved / claimable balances, cold paths moved
    ///          to CapitalCallManagerSidecar (EIP-170 relief; deployed by the model ctor).
    ///  v43108: PublicMessageCert default cost scaled to the stable's real decimals at initialize.
    uint16 public constant CONTRACT_VERSION = 43110;

    /* ========== CONSTANTS ========== */

    uint256 public constant MAX_TITLE_LENGTH = 256;
    uint256 public constant MAX_DESCRIPTION_LENGTH = 1024;

    /// @notice Default + ceiling for the per-raise participant cap. The
    ///         ceiling keeps the one-shot refund/distribution loops safely
    ///         inside one block (300 transfers ≈ 9-15M gas worst case).
    uint256 public constant DEFAULT_MAX_PARTICIPANTS = 100;
    uint256 public constant MAX_PARTICIPANTS_CEILING = 300;

    /// @notice Cap on simultaneously OPEN raises (bounds the lazy-refresh walk).
    uint256 public constant MAX_OPEN_RAISES = 20;

    /// @notice Default cost to register a PublicMessageCert — $1.00 in CANONICAL 6-dec
    ///         units. initialize() scales this by 10**(stableDecimals-6) into the
    ///         stable's REAL atomics so the default is $1.00 on every chain.
    uint256 public constant DEFAULT_STABLE_COST_TO_REGISTER_SIGNED_MESSAGE = 1_000_000;

    /// @notice FeeManager label hashes (fee types 17-21). Looked up with try/catch —
    ///         a FeeManager that pre-dates a label reads as "no fee".
    bytes32 public constant KECCAK_FEE_CC_PROPOSE          = keccak256("CapitalCallPropose");            // 17 absolute, proposer
    bytes32 public constant KECCAK_FEE_CC_CONTRIBUTE       = keccak256("CapitalCallContribute");         // 18 absolute, every contribution / bid
    bytes32 public constant KECCAK_FEE_CC_SUCCESS          = keccak256("CapitalCallSuccess");            // 19 % / abs of proceeds, IssueToken leg
    bytes32 public constant KECCAK_FEE_CC_NONSEC_SUCCESS   = keccak256("CapitalCallNonSecuritySuccess"); // 20 % / abs of proceeds, otherwise
    bytes32 public constant KECCAK_FEE_CC_AUCTION_ENTRANCE = keccak256("CapitalCallAuctionEntrance");    // 21 absolute, first bid

    /* ========== KINDS / STATUS ========== */

    uint8 public constant KIND_RAISE   = 0;
    uint8 public constant KIND_AUCTION = 1;

    uint8 public constant STATUS_ACTIVE = 0;
    uint8 public constant STATUS_SUCCEEDED = 1;  // closed, isValid = true (funds kept, reward delivered)
    uint8 public constant STATUS_REFUNDED = 2;   // closed, isValid = false (funds returned)
    uint8 public constant STATUS_CANCELLED = 3;  // admin-cancelled before expiry (funds returned)

    /* ========== TYPES ========== */

    /// @notice One capital event — a raise or an auction (see `kind`).
    struct CapitalRaise {
        uint256 raiseId;
        uint8   kind;                    // KIND_RAISE / KIND_AUCTION
        uint8   status;                  // STATUS_* above
        bool    isValid;                 // true ONLY when closed via goal-reached / auction won
        address proposer;                // the TokenAdmin who proposed
        string  title;
        string  description;             // terms: what the money will be used for / what is rewarded
        uint256 createdAtTimestamp;
        uint256 startTimestamp;          // contributions / bids accepted from here (>= createdAt)
        uint256 expirationTimestamp;     // after this an under-goal raise refunds; an auction settles
        uint256 raiseGoalAmount;         // RAISE: all-or-nothing goal (NET stable atomics). AUCTION: minBid reserve (0 = any)
        uint256 totalContributed;        // RAISE: net escrowed so far. AUCTION: sum of every live bid escrowed
        uint256 maxParticipantsAtCreation; // frozen copy of the global cap
        // ---- reward leg (RAISE: pro-rata; AUCTION: the lot) ----
        address rewardToken;             // address(0) = no on-chain reward (off-chain terms)
        uint8   rewardDecimals;          // rewardToken.decimals() cached at propose
        uint256 stablePricePerToken;     // RAISE only: stable atomics per ONE WHOLE rewardToken (0 when no leg)
        uint256 rewardTokensReserved;    // RAISE: tokensToSell (derived). AUCTION: lotAmount. Pre-escrowed.
        // ---- RAISE contribution limits (NET stable atomics; 0 = ignore) ----
        uint256 minPerContribution;      // floor on EACH contribute() call (waived on exact fill)
        uint256 minPerContributor;       // entry floor: a NEW contributor's FIRST contribution (waived on exact fill)
        uint256 maxPerContributor;       // cumulative cap per contributor address (never waived)
        // ---- audience (both kinds) ----
        uint256 minTokenBalance;         // 0 = public; else IssueToken.balanceOf(participant) >= this
        bool    requireWhitelist;        // IssueToken.getUserRegistrationStatus(participant,false) != 0
        // ---- AUCTION state ----
        address highestBidder;
        uint256 highestBid;              // NET total of the highest bidder
    }

    /// @notice One public message certification.
    struct MessageCert {
        bytes32 rawMessage;              // commit hash of the (templated, field-filled) certified document
        bytes signedMessage;             // registrant's signature over rawMessage
        uint256 timestamp;
        uint256 costPaid;                // amount charged, in native units of the unit below
        bool paidInToken;                // false = project stablecoin, true = project Token
        address recoveredAdminApprover;  // TokenAdmin recovered from adminApprovalSig (address(0) if approval not required)
    }

    /// @notice Propose-time parameters for a KIND_RAISE event.
    struct RaiseParams {
        string  title;
        string  description;
        address rewardToken;             // IssueToken, another ERC-20 this treasury holds, or address(0) = off-chain
        uint256 stablePricePerToken;     // stable atomics per ONE WHOLE rewardToken; MUST be 0 iff rewardToken == 0
        uint256 raiseGoalAmount;         // NET stable atomics; ALL must be raised by expiration or every contribution refunds
        uint256 startTimestamp;          // 0 = now
        uint256 expirationTimestamp;     // must be > start
        uint256 minPerContribution;
        uint256 minPerContributor;
        uint256 maxPerContributor;
        uint256 minTokenBalance;         // audience
        bool    requireWhitelist;        // audience
    }

    /// @notice Propose-time parameters for a KIND_AUCTION event.
    struct AuctionParams {
        string  title;
        string  description;
        address lotAsset;                // IssueToken, another ERC-20 this treasury holds, or address(0) = off-chain lot
        uint256 lotAmount;               // MUST be 0 iff lotAsset == 0
        uint256 minBid;                  // reserve, NET stable atomics; 0 = any positive bid
        uint256 startTimestamp;          // 0 = now
        uint256 activeHours;             // expiration = start + activeHours * 3600; must be > 0
        uint256 minTokenBalance;         // audience
        bool    requireWhitelist;        // audience
    }

    /// @notice Optional EIP-2612 permit for the proposer's fee pull (deadline 0 = skip).
    struct PermitData {
        uint256 deadline;
        uint8   v;
        bytes32 r;
        bytes32 s;
    }

    /* ========== STATE ========== */

    /// @notice Project IssueTokenSaleManager (eligibility oracle + projectFlags),
    ///         resolved from the Controller's SmartContract registry.
    address public issueTokenSaleManager;

    /// @notice Global per-raise participant cap (frozen per raise at propose).
    uint256 public maxParticipants;

    /// @notice Global cost (stablecoin native units) to register one
    ///         PublicMessageCert when paying in stablecoin. TokenAdmin-settable; 0 = free.
    uint256 public stableCostToRegisterSignedMessage;

    /// @notice Global cost (project Token native units) to register one
    ///         PublicMessageCert when messageCertPayInToken is true. 0 = free.
    uint256 public tokenCostToRegisterSignedMessage;

    /// @notice PublicMessageCert policy flags — ALL TokenAdmin-settable, ALL default false.
    ///   messageCertPayInToken          — charge in project Token, not stablecoin.
    ///   messageCertRequireEligibility  — registrant must pass the SaleManager gate.
    ///   messageCertRequireUserSignature— signedMessage must ecrecover to msg.sender over rawMessage.
    ///   messageCertRequireAdminApproval— a TokenAdmin co-signature over (this, chainId, msg.sender, rawMessage).
    bool public messageCertPayInToken;
    bool public messageCertRequireEligibility;
    bool public messageCertRequireUserSignature;
    bool public messageCertRequireAdminApproval;

    uint256 public nextRaiseId; // first raise gets id 1

    mapping(uint256 => CapitalRaise) internal raisesById;
    uint256[] internal _openRaiseIds;    // ACTIVE raises only (compact walk list)
    uint256[] internal _closedRaiseIds;  // settled raises (paginated getter)

    /// @notice raiseId => participant => NET stablecoin escrowed (RAISE: contributed; AUCTION: total bid).
    mapping(uint256 => mapping(address => uint256)) public contributionOf;
    /// @notice raiseId => ordered participant list (bounded by frozen cap).
    mapping(uint256 => address[]) internal _participantsByRaise;

    /// @notice Reward/lot inventory already promised to OPEN raises, per asset (native units).
    mapping(address => uint256) public assetReservedForOpenRaises;

    /// @notice Push-with-fallback claim balances: asset => recipient => amount. Pull via claim(asset).
    mapping(address => mapping(address => uint256)) public claimable;

    /// @notice Sum of every participant's NET stablecoin escrowed in OPEN events (locked
    ///         against admin withdrawal). Decremented in full when an event closes.
    uint256 public stableEscrowed;

    /// @notice Per-asset sum of all outstanding claimable() balances (locked against admin
    ///         withdrawal until claimed).
    mapping(address => uint256) public claimableTotal;

    /// @notice PublicMessageCerts: user => append-only cert array.
    mapping(address => MessageCert[]) internal _messageCertsByUser;

    /* ========== EVENTS ========== */

    event CapitalRaiseProposed(uint256 indexed raiseId, address indexed proposer, uint8 kind, address rewardToken, uint256 stablePricePerToken, uint256 raiseGoalAmount, uint256 rewardTokensReserved, uint256 startTimestamp, uint256 expirationTimestamp);
    event ContributionReceived(uint256 indexed raiseId, address indexed contributor, uint256 netAmount, uint256 feePaid, uint256 totalContributed);
    event BidPlaced(uint256 indexed raiseId, address indexed bidder, uint256 totalBid, uint256 feePaid);
    event CapitalRaiseSucceeded(uint256 indexed raiseId, uint256 totalRaised, uint256 rewardDistributed, uint256 successFee);
    event AuctionSettled(uint256 indexed raiseId, address indexed winner, uint256 winningBid, uint256 totalRefunded, uint256 successFee);
    event CapitalRaiseRefunded(uint256 indexed raiseId, uint8 finalStatus, uint256 totalReturned);
    event TransferFellBackToClaim(address indexed recipient, address indexed asset, uint256 amount);
    event ClaimPaid(address indexed recipient, address indexed asset, uint256 amount);
    event FeeCharged(bytes32 indexed feeLabelHash, address indexed payer, uint256 amount);
    event MessageCertRegistered(address indexed user, uint256 indexed certIndex, bytes32 rawMessage, uint256 costPaid, bool paidInToken, address recoveredAdminApprover);

    // Inert model / sidecar construction: zero controller tells ExecutivePeerTreasury
    // not to touch a live Controller. Clones never run this.
    constructor() ExecutivePeerTreasury(address(0), address(0), address(0), "") {}

    /* ========== SHARED INTERNALS ========== */

    function _requireTokenAdmin() internal view {
        if (!IController(peerTreasuryController).isOfficialEntityFast(KECCAK_TOKEN_ADMIN, msg.sender)) {
            revert NotTokenAdmin();
        }
    }

    /// @dev 10**(stableDecimals-6): canonical-6-dec → stable-atomics multiplier
    ///      (FeeManager configs are canonical 6-dec; its OUTPUTS are already scaled).
    function _stableScale() internal view returns (uint256) {
        uint8 d = ICCMERC20(stableCoinAddress).decimals();
        return d > 6 ? 10 ** uint256(d - 6) : 1;
    }

    /// @dev Quote a FeeManager fee by label. `grossAtomics` is the base for percent slots
    ///      (pass 0 for absolute-only types). Missing label / no FeeManager → (empty, 0).
    function _quoteFee(bytes32 label, uint256 grossAtomics)
        internal view
        returns (IFeeManager.CalculatedEntityAmount[] memory fees, uint256 total)
    {
        address fm = feeManager;
        if (fm == address(0)) return (fees, 0);
        try IFeeManager(fm).calculateChainedAmounts(grossAtomics / _stableScale(), 10000, label)
            returns (IFeeManager.CalculatedEntityAmount[] memory f, uint256 t)
        {
            return (f, t);
        } catch {
            return (fees, 0);
        }
    }

    /// @dev Push already-quoted fee shares to their entities from THIS contract's stablecoin
    ///      balance (the gross was pulled first — one permit for the participant).
    ///      Push-with-fallback so a poisoned fee entity can never block participation.
    function _payFees(IFeeManager.CalculatedEntityAmount[] memory fees, bytes32 label, uint256 total) internal {
        if (total == 0) return;
        address stable = stableCoinAddress;
        for (uint256 i = 0; i < fees.length; i++) {
            if (fees[i].amount == 0 || fees[i].entityAddress == address(0)) continue;
            _pushOrCredit(stable, fees[i].entityAddress, fees[i].amount);
        }
        emit FeeCharged(label, msg.sender, total);
    }

    /// @dev Push-with-fallback transfer: try the direct transfer; if the token reverts or
    ///      returns false (e.g., USDC blacklist), credit a pull-claimable balance instead so
    ///      one poisoned recipient can never brick the loop for everyone else.
    function _pushOrCredit(address asset, address to, uint256 amount) internal {
        try ICCMERC20(asset).transfer(to, amount) returns (bool ok) {
            if (ok) return;
        } catch {}
        claimable[asset][to] += amount;
        claimableTotal[asset] += amount;
        emit TransferFellBackToClaim(to, asset, amount);
    }

    /// @dev Success-fee label for `r`: the securities-flavoured CapitalCallSuccess only when
    ///      the IssueToken is being delivered AND the project is not flagged NON-SECURITY
    ///      (SaleManager.projectFlags bit 21).
    ///      Tolerant: a SaleManager without projectFlags() (or a failed call) is treated as
    ///      a security (CapitalCallSuccess) so settlement can never be bricked by this read.
    function _successFeeLabel(CapitalRaise storage r) internal view returns (bytes32) {
        if (r.rewardToken == issueTokenAddress) {
            try ICCMSaleManager(issueTokenSaleManager).projectFlags() returns (uint32 flags) {
                if ((flags >> 21) & 1 == 1) return KECCAK_FEE_CC_NONSEC_SUCCESS;
            } catch {}
            return KECCAK_FEE_CC_SUCCESS;
        }
        return KECCAK_FEE_CC_NONSEC_SUCCESS;
    }

    /// @dev Settlement-time success fee on `proceeds` (total raised / winning bid): quote,
    ///      push each share from the proceeds push-with-fallback (a poisoned fee entity must
    ///      not brick settlement). Returns the total deducted (capped at the proceeds).
    function _chargeSuccessFee(CapitalRaise storage r, uint256 proceeds) internal returns (uint256 total) {
        bytes32 label = _successFeeLabel(r);
        (IFeeManager.CalculatedEntityAmount[] memory fees, uint256 quoted) = _quoteFee(label, proceeds);
        if (quoted == 0 || quoted > proceeds) return 0;
        address stable = stableCoinAddress;
        for (uint256 i = 0; i < fees.length; i++) {
            if (fees[i].amount == 0 || fees[i].entityAddress == address(0)) continue;
            _pushOrCredit(stable, fees[i].entityAddress, fees[i].amount);
            total += fees[i].amount;
        }
        emit FeeCharged(label, r.proposer, total);
    }

    function _removeFromOpen(uint256 raiseId) internal {
        uint256 n = _openRaiseIds.length;
        for (uint256 i = 0; i < n; i++) {
            if (_openRaiseIds[i] == raiseId) {
                _openRaiseIds[i] = _openRaiseIds[n - 1];
                _openRaiseIds.pop();
                return;
            }
        }
    }

    /// @dev Common close bookkeeping: release the reward reservation and the stablecoin
    ///      escrow lock (the escrow is then either returned or becomes settled proceeds),
    ///      move open → closed.
    function _closeRaise(CapitalRaise storage r, uint8 finalStatus, bool valid) internal {
        r.status = finalStatus;
        r.isValid = valid;
        if (r.rewardToken != address(0)) {
            assetReservedForOpenRaises[r.rewardToken] -= r.rewardTokensReserved;
        }
        stableEscrowed -= r.totalContributed;
        _removeFromOpen(r.raiseId);
        _closedRaiseIds.push(r.raiseId);
    }

    /// @dev Close as REFUNDED/CANCELLED: return every participant's escrowed stablecoin
    ///      push-with-fallback (both kinds; an auction with no bids has no participants).
    function _settleRefund(CapitalRaise storage r, uint8 finalStatus) internal {
        _closeRaise(r, finalStatus, false);

        address stable = stableCoinAddress;
        address[] storage parts = _participantsByRaise[r.raiseId];
        uint256 returned = 0;

        for (uint256 i = 0; i < parts.length; i++) {
            address p = parts[i];
            uint256 amt = contributionOf[r.raiseId][p];
            if (amt == 0) continue;
            returned += amt;
            _pushOrCredit(stable, p, amt);
        }

        emit CapitalRaiseRefunded(r.raiseId, finalStatus, returned);
    }

    /// @dev Close an auction to its unique highest bidder: the success fee is taken from the
    ///      winning bid, the rest stays in this treasury, the lot (if any) is pushed to the
    ///      winner, every other bidder's escrowed total is returned — all push-with-fallback.
    function _settleAuction(CapitalRaise storage r) internal {
        address winner = r.highestBidder;
        address lotAsset = r.rewardToken;
        uint256 lot = r.rewardTokensReserved;
        _closeRaise(r, STATUS_SUCCEEDED, true);

        uint256 successFee = _chargeSuccessFee(r, r.highestBid);

        if (lotAsset != address(0) && lot != 0) {
            _pushOrCredit(lotAsset, winner, lot);
        }

        address stable = stableCoinAddress;
        address[] storage parts = _participantsByRaise[r.raiseId];
        uint256 returned = 0;
        for (uint256 i = 0; i < parts.length; i++) {
            address p = parts[i];
            if (p == winner) continue;
            uint256 amt = contributionOf[r.raiseId][p];
            if (amt == 0) continue;
            returned += amt;
            _pushOrCredit(stable, p, amt);
        }

        emit AuctionSettled(r.raiseId, winner, r.highestBid, returned, successFee);
    }

    /// @dev Lazy-refresh walk: settle every ACTIVE event whose expiration passed. An
    ///      under-goal raise (a full one settles at contribute time) and a bid-less auction
    ///      refund; an auction with a bidder closes to its unique highest bid.
    function _refreshInternal() internal {
        uint256 i = 0;
        while (i < _openRaiseIds.length) {
            CapitalRaise storage r = raisesById[_openRaiseIds[i]];
            if (r.status == STATUS_ACTIVE && block.timestamp >= r.expirationTimestamp) {
                if (r.kind == KIND_AUCTION && r.highestBidder != address(0)) {
                    _settleAuction(r);
                } else {
                    _settleRefund(r, STATUS_REFUNDED);
                }
                // settlement swap-removes r from _openRaiseIds; do NOT i++
            } else {
                i++;
            }
        }
    }

    /// @dev Resolve the CURRENT SaleManager from the Controller registry (label "IssueTokenSaleManager").
    function _syncSaleManagerInternal() internal {
        IController.OfficialEntityStruct[] memory scList =
            IController(peerTreasuryController).getAllOfficialEntities("SmartContract", false);

        bytes32 wanted = keccak256(bytes("IssueTokenSaleManager"));
        for (uint256 i = 0; i < scList.length; i++) {
            if (!scList[i].active) continue;
            if (keccak256(bytes(scList[i].fullNameOfEntityOrLabel)) == wanted) {
                issueTokenSaleManager = scList[i].pubAddress;
                return;
            }
        }
        revert CCM_SaleManagerNotFound();
    }
}

// ============================================================================
//  CapitalCallManager — THE CLONABLE MODEL (hot paths + sidecar stubs)
// ============================================================================
// PROXY BUILD: EIP-1167 clone variant — deployed once per chain as an inert MODEL;
// projects receive a clone configured via initialize(). OZ ReentrancyGuard is
// clone-safe as-is (zero initial state behaves as NOT_ENTERED).
//
// SIDECAR (EIP-170 relief): CapitalCallManagerSidecar (end of this file) is deployed
// by THIS model's constructor (constructor code is not subject to EIP-170), its
// address is an immutable, and NO factory / PPAM / deployer change is required. The
// sidecar carries the COLD paths — initialize(), every TokenAdmin setter, both
// propose functions, cancel, and the PublicMessageCert registration — while the HOT
// paths (contribute / bid / refresh / settlement / claims / views) stay here. Stubs
// below keep the SAME signatures (the compiled ABI is complete) and forward msg.data
// via delegatecall: clone storage, msg.sender, address(this) and event addresses are
// preserved; return data and custom errors bubble verbatim.
contract CapitalCallManager is CapitalCallManagerBase {

    address private immutable SIDECAR;

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

    /* ========== CONSTRUCTOR / CLONE INIT ========== */

    // ===== PROXY BUILD: MODEL CONSTRUCTOR =====
    // No arguments; deploys the sidecar and permanently locks the model.
    constructor() {
        SIDECAR = address(new CapitalCallManagerSidecar());
        _disableInitializers();
    }

    // ===== PROXY BUILD: CLONE CONSTRUCTOR-EQUIVALENT — body in CapitalCallManagerSidecar =====
    // One-shot is enforced by `initializer` HERE (clone storage) before forwarding.
    // Standard peer signature (controller, feeManager, issueToken) — Factory Phase 8.
    function initialize(address, address, address) external initializer { _fwd(); }

    /* ========== SIDECAR STUBS (bodies + NatSpec in CapitalCallManagerSidecar) ========== */
    // NOTE: no `nonReentrant` on these stubs — the sidecar bodies carry it (same guard slot).
    function syncSaleManager() external { _fwd(); }
    function setMaxParticipants(uint256) external { _fwd(); }
    function setStableCostToRegisterSignedMessage(uint256) external { _fwd(); }
    function setTokenCostToRegisterSignedMessage(uint256) external { _fwd(); }
    function setMessageCertPolicy(bool, bool, bool, bool) external { _fwd(); }
    function proposeCapitalRaise(RaiseParams calldata, PermitData calldata) external returns (uint256) { _fwd(); }
    function proposeAuction(AuctionParams calldata, PermitData calldata) external returns (uint256) { _fwd(); }
    function cancelCapitalRaise(uint256) external { _fwd(); }
    function registerMessageCert(bytes32, bytes calldata, bytes calldata, uint256, uint8, bytes32, bytes32) external returns (uint256) { _fwd(); }

    /* ========== PARTICIPATION GATES ========== */

    /// @dev Universal audience + the implicit IssueToken-leg eligibility gate.
    function _checkAudience(CapitalRaise storage r) internal view {
        address it = issueTokenAddress;
        if (r.minTokenBalance != 0 && ICCMERC20(it).balanceOf(msg.sender) < r.minTokenBalance) revert CCM_BelowMinBalance();
        if (r.requireWhitelist && ICCMIssueToken(it).getUserRegistrationStatus(msg.sender, false) == 0) revert CCM_NotWhitelisted();
        if (r.rewardToken == it) {
            (uint8 statusMode, , ) = ICCMSaleManager(issueTokenSaleManager).getPurchaseEligibility(msg.sender);
            if (statusMode == 0) revert CCM_NotEligible();
        }
    }

    /// @dev Shared entry checks for contribute()/bid(): existence, kind, window, amount, audience.
    function _enter(uint256 raiseId, uint8 kind, uint256 amount) internal view returns (CapitalRaise storage r) {
        r = raisesById[raiseId];
        if (r.raiseId == 0) revert CCM_RaiseNotFound();
        if (r.kind != kind) revert CCM_WrongKind();
        if (r.status != STATUS_ACTIVE) revert CCM_RaiseNotActive();
        if (block.timestamp < r.startTimestamp) revert CCM_RaiseNotStarted();
        if (block.timestamp >= r.expirationTimestamp) revert CCM_RaiseExpired();
        if (amount == 0) revert CCM_ZeroAmount();
        _checkAudience(r);
    }

    /// @dev Atomic optional permit + pull of the GROSS into this contract.
    function _pullGross(uint256 amount, uint256 permitDeadline, uint8 v, bytes32 r_, bytes32 s) internal {
        address stable = stableCoinAddress;
        if (permitDeadline != 0) {
            ICCMERC20Permit(stable).permit(msg.sender, address(this), amount, permitDeadline, v, r_, s);
        }
        if (!ICCMERC20(stable).transferFrom(msg.sender, address(this), amount)) revert CCM_TransferFailed();
    }

    /// @dev Register a first-time participant against the frozen cap.
    function _addParticipant(CapitalRaise storage r) internal {
        if (_participantsByRaise[r.raiseId].length >= r.maxParticipantsAtCreation) revert CCM_MaxParticipantsReached();
        _participantsByRaise[r.raiseId].push(msg.sender);
    }

    /* ========== CONTRIBUTE (KIND_RAISE) ========== */

    /**
     * @notice Contribute stablecoin to an active raise. The EIP-2612 permit (when
     *         permitDeadline != 0) executes atomically with the pull — ONE signature
     *         covers the gross; the contribute fee is deducted from it.
     * @param raiseId        Target raise (KIND_RAISE).
     * @param amount         GROSS stablecoin atomics pulled from the caller. The absolute
     *                       CapitalCallContribute fee is pushed to the fee entities; the NET
     *                       (gross − fee) is escrowed and counts toward the goal. Reverts
     *                       CCM_OverGoal when the NET would overshoot (strict all-or-nothing).
     *                       The success fee (if any) is taken from the proceeds only if the
     *                       raise succeeds — see quoteSuccessFee().
     * @param permitDeadline 0 = skip permit (caller pre-approved), else permit deadline.
     * @dev Lazy-refresh settles any EXPIRED raises platform-wide first. Audience +
     *      eligibility gates are enforced HERE (fail-fast). Per-raise limits (NET):
     *      minPerContribution and minPerContributor (the latter only on a NEW contributor's
     *      first contribution) — both WAIVED when the NET fills the goal exactly — and
     *      maxPerContributor on cumulative NET (never waived).
     */
    function contribute(
        uint256 raiseId,
        uint256 amount,
        uint256 permitDeadline,
        uint8 permitV,
        bytes32 permitR,
        bytes32 permitS
    ) external nonReentrant {
        _refreshInternal();
        CapitalRaise storage r = _enter(raiseId, KIND_RAISE, amount);

        _pullGross(amount, permitDeadline, permitV, permitR, permitS);

        (IFeeManager.CalculatedEntityAmount[] memory fees, uint256 fee) = _quoteFee(KECCAK_FEE_CC_CONTRIBUTE, 0);
        if (fee >= amount) revert CCM_FeeExceedsAmount();
        _payFees(fees, KECCAK_FEE_CC_CONTRIBUTE, fee);
        uint256 net = amount - fee;

        if (r.totalContributed + net > r.raiseGoalAmount) revert CCM_OverGoal();

        uint256 prior = contributionOf[raiseId][msg.sender];
        {
            bool exactFill = (net == r.raiseGoalAmount - r.totalContributed);
            if (!exactFill) {
                if (r.minPerContribution != 0 && net < r.minPerContribution) revert CCM_BelowMin();
                if (prior == 0 && r.minPerContributor != 0 && net < r.minPerContributor) revert CCM_BelowMin();
            }
        }
        if (r.maxPerContributor != 0 && prior + net > r.maxPerContributor) revert CCM_OverMax();

        if (prior == 0) _addParticipant(r);

        contributionOf[raiseId][msg.sender] = prior + net;
        r.totalContributed += net;
        stableEscrowed += net;

        emit ContributionReceived(raiseId, msg.sender, net, fee, r.totalContributed);

        // Goal reached — close VALID immediately (nothing further can fit).
        if (r.totalContributed == r.raiseGoalAmount) {
            _settleSuccess(r);
        }
    }

    /* ========== BID (KIND_AUCTION) ========== */

    /**
     * @notice Place or raise a bid on an active auction. `amount` is the GROSS stablecoin
     *         added now; the absolute CapitalCallContribute fee (and, on a bidder's FIRST
     *         bid, the CapitalCallAuctionEntrance fee) is deducted from it and the NET is
     *         added to the caller's escrowed total bid. The resulting total must be >= minBid
     *         and STRICTLY greater than the current highest bid — so no two bids are ever
     *         equal (the tie rule) and the highest is unique by construction.
     * @dev    Every bid stays escrowed until expiry; non-winners are refunded whole at
     *         settlement; the success fee comes out of the winning bid only.
     */
    function bid(
        uint256 raiseId,
        uint256 amount,
        uint256 permitDeadline,
        uint8 permitV,
        bytes32 permitR,
        bytes32 permitS
    ) external nonReentrant {
        _refreshInternal();
        CapitalRaise storage r = _enter(raiseId, KIND_AUCTION, amount);

        _pullGross(amount, permitDeadline, permitV, permitR, permitS);

        uint256 prior = contributionOf[raiseId][msg.sender];

        (IFeeManager.CalculatedEntityAmount[] memory fees, uint256 fee) = _quoteFee(KECCAK_FEE_CC_CONTRIBUTE, 0);
        uint256 feeTotal = fee;
        if (prior == 0) {
            (IFeeManager.CalculatedEntityAmount[] memory eFees, uint256 eFee) = _quoteFee(KECCAK_FEE_CC_AUCTION_ENTRANCE, 0);
            feeTotal += eFee;
            if (feeTotal >= amount) revert CCM_FeeExceedsAmount();
            _payFees(eFees, KECCAK_FEE_CC_AUCTION_ENTRANCE, eFee);
            _addParticipant(r);
        } else if (feeTotal >= amount) {
            revert CCM_FeeExceedsAmount();
        }
        _payFees(fees, KECCAK_FEE_CC_CONTRIBUTE, fee);

        uint256 net = amount - feeTotal;
        uint256 newTotal = prior + net;
        if (r.raiseGoalAmount != 0 && newTotal < r.raiseGoalAmount) revert CCM_BelowReserve();
        if (newTotal <= r.highestBid) revert CCM_BidNotHighest();

        contributionOf[raiseId][msg.sender] = newTotal;
        r.totalContributed += net;
        stableEscrowed += net;
        r.highestBid = newTotal;
        r.highestBidder = msg.sender;

        emit BidPlaced(raiseId, msg.sender, newTotal, feeTotal);
    }

    /* ========== REFRESH / SETTLEMENT ========== */

    /// @notice Settle every event whose expiration passed: an under-goal raise refunds ALL
    ///         participants (isValid=false); an auction with at least one bid closes to its
    ///         unique highest bidder and refunds everyone else; an auction with no bids
    ///         closes invalid. Callable by anyone; also runs at the top of every
    ///         contribute() / bid() / propose (lazy-refresh idiom, as Governance).
    function refresh() external nonReentrant {
        _refreshInternal();
    }

    /// @dev Close a raise as SUCCEEDED: take the success fee from the proceeds, distribute
    ///      the reward pro-rata push-with-fallback (contribution × 10^rewardDecimals / price)
    ///      when there is an on-chain reward leg; the remaining stablecoin stays in this
    ///      treasury until an admin moves it.
    function _settleSuccess(CapitalRaise storage r) internal {
        address asset = r.rewardToken;
        uint256 distributed = 0;
        _closeRaise(r, STATUS_SUCCEEDED, true);

        uint256 successFee = _chargeSuccessFee(r, r.totalContributed);

        if (asset != address(0)) {
            address[] storage parts = _participantsByRaise[r.raiseId];
            uint256 scale = 10 ** uint256(r.rewardDecimals);
            for (uint256 i = 0; i < parts.length; i++) {
                address p = parts[i];
                uint256 rewardAmount = (contributionOf[r.raiseId][p] * scale) / r.stablePricePerToken;
                if (rewardAmount == 0) continue;
                distributed += rewardAmount;
                _pushOrCredit(asset, p, rewardAmount);
            }
        }

        emit CapitalRaiseSucceeded(r.raiseId, r.totalContributed, distributed, successFee);
    }

    /* ========== PULL CLAIMS (fallback path only) ========== */

    /// @notice Pull a balance that could not be pushed at settlement (stablecoin refund,
    ///         reward tokens, an auction lot, or a fee share) — see `claimable(asset, you)`.
    function claim(address asset) external nonReentrant {
        uint256 amt = claimable[asset][msg.sender];
        if (amt == 0) revert CCM_NothingToClaim();
        claimable[asset][msg.sender] = 0;
        claimableTotal[asset] -= amt;
        if (!ICCMERC20(asset).transfer(msg.sender, amt)) revert CCM_TransferFailed();
        emit ClaimPaid(msg.sender, asset, amt);
    }

    /* ========== ADMIN WITHDRAWAL LOCKS ========== */

    /// @notice Balance of `asset` this contract must retain: stablecoin escrowed in OPEN
    ///         events + reward/lot inventory reserved by OPEN events + unclaimed fallback
    ///         balances. Everything above it (settled proceeds, unreserved inventory) is
    ///         withdrawable through the inherited ExecutivePeerTreasury paths.
    function lockedBalance(address asset) public view returns (uint256) {
        return (asset == stableCoinAddress ? stableEscrowed : 0)
            + assetReservedForOpenRaises[asset]
            + claimableTotal[asset];
    }

    function _requireUnlocked(address asset, uint256 amount) internal view {
        if (ICCMERC20(asset).balanceOf(address(this)) < lockedBalance(asset) + amount) revert CCM_FundsLocked();
    }

    /// @dev Inherited admin withdrawal paths, guarded. Auth stays in the parent bodies.
    function executiveWithdrawTokens(address personAddress, uint256 amt, address tokenSCAddress, string calldata note) public override {
        _requireUnlocked(tokenSCAddress, amt);
        super.executiveWithdrawTokens(personAddress, amt, tokenSCAddress, note);
    }

    function peerTreasuryTransferTokens(address token, address to, uint256 amount) public override {
        _requireUnlocked(token, amount);
        super.peerTreasuryTransferTokens(token, to, amount);
    }

    function peerTreasuryTransferTokensDirect(address token, address to, uint256 amount) public override {
        _requireUnlocked(token, amount);
        super.peerTreasuryTransferTokensDirect(token, to, amount);
    }

    /// @dev The escrow, the fee pulls and lockedBalance() are all denominated in the CURRENT
    ///      stablecoin, so it may only change while NO event is ACTIVE (every escrow has
    ///      been returned or settled). Fallback claims in the OLD stable remain claimable
    ///      and locked per-asset via claimableTotal[oldStable]. Auth stays in the parent.
    function setStableCoinAddress(address newStableCoinAddress) public override {
        if (_openRaiseIds.length != 0) revert CCM_EventsOpen();
        super.setStableCoinAddress(newStableCoinAddress);
    }

    /* ========== VIEWS ========== */

    function getCapitalRaise(uint256 raiseId) external view returns (CapitalRaise memory) {
        return raisesById[raiseId];
    }

    /// @notice ACTIVE raise ids (bounded by MAX_OPEN_RAISES — no pagination needed).
    function getOpenRaiseIds() external view returns (uint256[] memory) {
        return _openRaiseIds;
    }

    /// @notice Paginated closed raise ids. count == 0 returns all from start.
    function getClosedRaiseIds(uint256 start, uint256 count) external view returns (uint256[] memory out) {
        uint256 len = _closedRaiseIds.length;
        if (start > len) revert CCM_RaiseNotFound();
        uint256 remaining = len - start;
        if (count == 0 || count > remaining) count = remaining;
        out = new uint256[](count);
        for (uint256 i = 0; i < count; i++) out[i] = _closedRaiseIds[start + i];
    }

    function getParticipants(uint256 raiseId) external view returns (address[] memory) {
        return _participantsByRaise[raiseId]; // bounded by frozen maxParticipants
    }

    function getParticipantCount(uint256 raiseId) external view returns (uint256) {
        return _participantsByRaise[raiseId].length;
    }

    /// @notice UI pre-flight: for a GROSS `amount` sent by `participant` to `raiseId`, the
    ///         per-action fee that would be deducted (CapitalCallContribute + the entrance fee
    ///         on a first auction bid) and the NET that would be escrowed. Does not check
    ///         gates or limits.
    function quoteParticipation(uint256 raiseId, address participant, uint256 amount)
        external view returns (uint256 fee, uint256 net)
    {
        CapitalRaise storage r = raisesById[raiseId];
        if (r.raiseId == 0) revert CCM_RaiseNotFound();
        (, fee) = _quoteFee(KECCAK_FEE_CC_CONTRIBUTE, 0);
        if (r.kind == KIND_AUCTION && contributionOf[raiseId][participant] == 0) {
            (, uint256 eFee) = _quoteFee(KECCAK_FEE_CC_AUCTION_ENTRANCE, 0);
            fee += eFee;
        }
        net = fee >= amount ? 0 : amount - fee;
    }

    /// @notice UI pre-flight: the success fee that settlement would deduct from `proceeds`
    ///         (the goal for a raise, a hypothetical winning bid for an auction), using the
    ///         label the event resolves to today (CapitalCallSuccess vs NonSecurity).
    function quoteSuccessFee(uint256 raiseId, uint256 proceeds) external view returns (uint256 fee) {
        CapitalRaise storage r = raisesById[raiseId];
        if (r.raiseId == 0) revert CCM_RaiseNotFound();
        (, fee) = _quoteFee(_successFeeLabel(r), proceeds);
        if (fee > proceeds) fee = 0;
    }

    function getMessageCertCount(address user) external view returns (uint256) {
        return _messageCertsByUser[user].length;
    }

    /// @notice Paginated cert getter. count == 0 returns all from start.
    function getMessageCerts(address user, uint256 start, uint256 count) external view returns (MessageCert[] memory out) {
        MessageCert[] storage arr = _messageCertsByUser[user];
        uint256 len = arr.length;
        if (start > len) revert CCM_NothingToClaim();
        uint256 remaining = len - start;
        if (count == 0 || count > remaining) count = remaining;
        out = new MessageCert[](count);
        for (uint256 i = 0; i < count; i++) out[i] = arr[start + i];
    }
}

// ============================================================================
//  CapitalCallManagerSidecar — COLD-PATH BODIES (PROXY BUILD, delegatecall)
// ============================================================================
//  Holds initialize(), the TokenAdmin setters, proposeCapitalRaise / proposeAuction,
//  cancelCapitalRaise and registerMessageCert so those bytes count against THIS
//  contract's EIP-170 budget instead of the model's. Deployed by the model's own
//  constructor; the model's same-signature stubs forward msg.data via delegatecall,
//  so each body executes against the CLONE's storage with address(this) = clone and
//  msg.sender = the original caller. Storage layout is shared through
//  CapitalCallManagerBase — identical by construction.
//
//  Direct calls are rejected (__SELF guard) — they would hit THIS contract's own
//  (empty) storage.
contract CapitalCallManagerSidecar is CapitalCallManagerBase {

    address private immutable __SELF;

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

    modifier onlyDelegated() {
        if (address(this) == __SELF) revert CCM_DirectCallForbidden();
        _;
    }

    /* ========== CLONE INIT (body) ========== */

    /**
     * @param _controller  Project Controller for entity gating.
     * @param _feeManager  Project FeeManager (fee quotes for types 17-21).
     * @param _issueToken  Project IssueToken (audience balance source; default reward asset).
     * @dev One-shot is enforced by the MODEL's `initializer` stub before forwarding here.
     *      The parent ExecutivePeerTreasury self-registers this contract on the Controller
     *      (init "CapitalCallManager") and pulls stableCoinAddress from the IssueToken. The
     *      SaleManager is resolved from the Controller registry — by Phase 8 every peer is
     *      already registered.
     */
    function initialize(address _controller, address _feeManager, address _issueToken) external onlyDelegated {
        __ExecutivePeerTreasury_init(_controller, _feeManager, _issueToken, "CapitalCallManager");

        if (_issueToken == address(0)) revert InvalidTokenAddress();
        if (stableCoinAddress == address(0)) revert CCM_StablecoinNotSet();

        maxParticipants = DEFAULT_MAX_PARTICIPANTS;
        // Scale the canonical $1.00 default into the stable's REAL atomics (6-dec → ×1;
        // 18-dec BNB-peg → ×1e12) so the default is $1.00 on every chain.
        stableCostToRegisterSignedMessage = DEFAULT_STABLE_COST_TO_REGISTER_SIGNED_MESSAGE * _stableScale();
        nextRaiseId = 1;

        _syncSaleManagerInternal();
    }

    /* ========== ADMIN / MAINTENANCE (bodies) ========== */

    /// @notice Re-resolve the project SaleManager from the Controller's SmartContract
    ///         registry. Callable by ANY address (registry is the source of truth).
    function syncSaleManager() external onlyDelegated {
        _syncSaleManagerInternal();
    }

    function setMaxParticipants(uint256 newMax) external onlyDelegated {
        _requireTokenAdmin();
        if (newMax == 0 || newMax > MAX_PARTICIPANTS_CEILING) revert CCM_InvalidMaxParticipants();
        maxParticipants = newMax; // frozen per raise at propose; open raises unaffected
    }

    function setStableCostToRegisterSignedMessage(uint256 newCost) external onlyDelegated {
        _requireTokenAdmin();
        stableCostToRegisterSignedMessage = newCost; // 0 = free
    }

    function setTokenCostToRegisterSignedMessage(uint256 newCost) external onlyDelegated {
        _requireTokenAdmin();
        tokenCostToRegisterSignedMessage = newCost; // 0 = free
    }

    /// @notice Set all PublicMessageCert policy flags at once (bytecode-lean).
    function setMessageCertPolicy(
        bool payInToken,
        bool requireEligibility,
        bool requireUserSignature,
        bool requireAdminApproval
    ) external onlyDelegated {
        _requireTokenAdmin();
        messageCertPayInToken = payInToken;
        messageCertRequireEligibility = requireEligibility;
        messageCertRequireUserSignature = requireUserSignature;
        messageCertRequireAdminApproval = requireAdminApproval;
    }

    /* ========== PROPOSE (TokenAdmin ONLY) ========== */

    /// @dev Shared propose plumbing: TokenAdmin gate, lazy refresh, CapitalCallPropose fee
    ///      (absolute-only, pulled from the proposer with an optional permit), text/window
    ///      validation, reward-asset validation + pre-escrow reservation, id + list bookkeeping.
    function _openRaise(
        uint8 kind,
        string calldata title,
        string calldata description,
        address rewardAsset,
        uint256 rewardAmount,
        uint256 startTimestamp,
        uint256 expirationTimestamp,
        PermitData calldata permitData
    ) private returns (CapitalRaise storage r) {
        _requireTokenAdmin();
        _refreshInternal(); // settle any expired events first (frees reservations)

        if (stableCoinAddress == address(0)) revert CCM_StablecoinNotSet();
        if (bytes(title).length == 0) revert CCM_EmptyTitle();
        if (bytes(title).length > MAX_TITLE_LENGTH) revert CCM_TitleTooLong();
        if (bytes(description).length > MAX_DESCRIPTION_LENGTH) revert CCM_DescriptionTooLong();
        if (_openRaiseIds.length >= MAX_OPEN_RAISES) revert CCM_TooManyOpenRaises();

        if (startTimestamp == 0) startTimestamp = block.timestamp;
        if (startTimestamp < block.timestamp) revert CCM_InvalidExpiration();
        if (expirationTimestamp <= startTimestamp) revert CCM_InvalidExpiration();

        // Reward/lot asset: address(0) ⇔ amount 0 (off-chain); never the escrow stablecoin.
        if ((rewardAsset == address(0)) != (rewardAmount == 0)) revert CCM_InvalidRewardAsset();
        if (rewardAsset == stableCoinAddress) revert CCM_InvalidRewardAsset();

        uint8 rewardDec = 0;
        if (rewardAsset != address(0)) {
            rewardDec = ICCMERC20(rewardAsset).decimals();
            // Pre-escrow check: unreserved inventory must cover this event.
            uint256 inventory = ICCMERC20(rewardAsset).balanceOf(address(this));
            if (inventory < assetReservedForOpenRaises[rewardAsset] + rewardAmount) revert CCM_InsufficientTokenInventory();
            assetReservedForOpenRaises[rewardAsset] += rewardAmount;
        }

        // CapitalCallPropose fee — absolute-only, paid by the proposer (optional permit).
        (IFeeManager.CalculatedEntityAmount[] memory fees, uint256 fee) = _quoteFee(KECCAK_FEE_CC_PROPOSE, 0);
        if (fee > 0) {
            address stable = stableCoinAddress;
            if (permitData.deadline != 0) {
                ICCMERC20Permit(stable).permit(msg.sender, address(this), fee, permitData.deadline, permitData.v, permitData.r, permitData.s);
            }
            if (!ICCMERC20(stable).transferFrom(msg.sender, address(this), fee)) revert CCM_TransferFailed();
            _payFees(fees, KECCAK_FEE_CC_PROPOSE, fee);
        }

        uint256 raiseId = nextRaiseId++;
        r = raisesById[raiseId];
        r.raiseId = raiseId;
        r.kind = kind;
        r.proposer = msg.sender;
        r.title = title;
        r.description = description;
        r.createdAtTimestamp = block.timestamp;
        r.startTimestamp = startTimestamp;
        r.expirationTimestamp = expirationTimestamp;
        r.maxParticipantsAtCreation = maxParticipants;
        r.rewardToken = rewardAsset;
        r.rewardDecimals = rewardDec;
        r.rewardTokensReserved = rewardAmount;
        // status defaults to STATUS_ACTIVE (0); isValid defaults false

        _openRaiseIds.push(raiseId);
    }

    /**
     * @notice Propose a new all-or-nothing capital raise (KIND_RAISE).
     * @param p       See RaiseParams. Reward leg: (rewardToken, stablePricePerToken) —
     *                IssueToken or any ERC-20 this treasury holds with price > 0, or
     *                (address(0), 0) for an off-chain reward described in `description`.
     *                tokensToSell = goal × 10^rewardDecimals / price is derived and
     *                pre-escrowed (reverts CCM_InsufficientTokenInventory otherwise — fund
     *                this contract first, e.g. IssueToken.peerTreasuryTransferTokensDirect).
     * @param permitData  Optional permit for the CapitalCallPropose fee pull (deadline 0 = skip).
     * @return raiseId The new raise id.
     */
    function proposeCapitalRaise(RaiseParams calldata p, PermitData calldata permitData)
        external nonReentrant onlyDelegated returns (uint256 raiseId)
    {
        if (p.raiseGoalAmount == 0) revert CCM_InvalidGoal();
        if ((p.rewardToken == address(0)) != (p.stablePricePerToken == 0)) revert CCM_InvalidPrice();

        // Contribution-limit consistency (all optional; 0 = ignore).
        if (p.minPerContribution > p.raiseGoalAmount) revert CCM_InvalidLimit();
        if (p.minPerContributor > p.raiseGoalAmount) revert CCM_InvalidLimit();
        if (p.maxPerContributor != 0) {
            if (p.minPerContribution > p.maxPerContributor) revert CCM_InvalidLimit();
            if (p.minPerContributor > p.maxPerContributor) revert CCM_InvalidLimit();
        }

        uint256 tokensToSell = 0;
        if (p.rewardToken != address(0)) {
            tokensToSell = (p.raiseGoalAmount * (10 ** uint256(ICCMERC20(p.rewardToken).decimals()))) / p.stablePricePerToken;
            if (tokensToSell == 0) revert CCM_InvalidGoal();
        }

        CapitalRaise storage r = _openRaise(
            KIND_RAISE, p.title, p.description, p.rewardToken, tokensToSell,
            p.startTimestamp, p.expirationTimestamp, permitData
        );
        r.stablePricePerToken = p.stablePricePerToken;
        r.raiseGoalAmount = p.raiseGoalAmount;
        r.minPerContribution = p.minPerContribution;
        r.minPerContributor = p.minPerContributor;
        r.maxPerContributor = p.maxPerContributor;
        r.minTokenBalance = p.minTokenBalance;
        r.requireWhitelist = p.requireWhitelist;
        raiseId = r.raiseId;

        emit CapitalRaiseProposed(raiseId, msg.sender, KIND_RAISE, p.rewardToken, p.stablePricePerToken, p.raiseGoalAmount, tokensToSell, r.startTimestamp, r.expirationTimestamp);
    }

    /**
     * @notice Propose a single-winner auction (KIND_AUCTION).
     * @param p       See AuctionParams. Lot: (lotAsset, lotAmount) — IssueToken or any ERC-20
     *                this treasury holds, pre-escrowed; or (address(0), 0) for an off-chain lot.
     *                minBid is the reserve (NET); bids must be strictly ascending.
     *                expiration = start + activeHours × 3600.
     * @param permitData  Optional permit for the CapitalCallPropose fee pull (deadline 0 = skip).
     * @return raiseId The new auction id.
     */
    function proposeAuction(AuctionParams calldata p, PermitData calldata permitData)
        external nonReentrant onlyDelegated returns (uint256 raiseId)
    {
        if (p.activeHours == 0) revert CCM_InvalidExpiration();
        uint256 start = p.startTimestamp == 0 ? block.timestamp : p.startTimestamp;

        CapitalRaise storage r = _openRaise(
            KIND_AUCTION, p.title, p.description, p.lotAsset, p.lotAmount,
            start, start + p.activeHours * 3600, permitData
        );
        r.raiseGoalAmount = p.minBid;
        r.minTokenBalance = p.minTokenBalance;
        r.requireWhitelist = p.requireWhitelist;
        raiseId = r.raiseId;

        emit CapitalRaiseProposed(raiseId, msg.sender, KIND_AUCTION, p.lotAsset, 0, p.minBid, p.lotAmount, r.startTimestamp, r.expirationTimestamp);
    }

    /// @notice TokenAdmin may cancel an ACTIVE raise or auction; every escrowed
    ///         contribution / bid refunds to its contributor in one shot (status = CANCELLED).
    /// @dev    THIS IS THE NO-BRICK GUARANTEE. It is the only settlement path that:
    ///           • ignores expiration (an event whose automatic settlement failed is still
    ///             ACTIVE, so it can always be unwound);
    ///           • does NOT run _refreshInternal() first (so a failing settlement elsewhere
    ///             can never block it);
    ///           • bypasses the success / auction path entirely — no success fee, no
    ///             FeeManager, no SaleManager read, no reward push — straight to
    ///             _settleRefund, which pushes each participant's NET back to THEM
    ///             (push-with-fallback: a blocked recipient becomes a claim(), never a revert)
    ///             and releases the reward reservation + escrow lock.
    ///         Funds always return to source; they are never released to the admin.
    function cancelCapitalRaise(uint256 raiseId) external nonReentrant onlyDelegated {
        _requireTokenAdmin();
        CapitalRaise storage r = raisesById[raiseId];
        if (r.raiseId == 0) revert CCM_RaiseNotFound();
        if (r.status != STATUS_ACTIVE) revert CCM_RaiseNotActive();
        _settleRefund(r, STATUS_CANCELLED);
    }

    /* ========== PUBLIC MESSAGE CERTS ========== */

    /**
     * @notice Register a signed-message certification under msg.sender.
     *         Anyone may call, subject to the TokenAdmin-configured policy flags.
     * @dev Policy (all default OFF — base service is open + stablecoin-priced):
     *   (a) COST is OPTIONAL and unit-selectable — 0 means free; the unit is the
     *       project stablecoin, or the project Token when messageCertPayInToken.
     *       Permit (permitDeadline != 0) executes atomically with the pull on the
     *       chosen asset; otherwise a prior approve() works.
     *   (b) messageCertRequireEligibility gates registration behind the SAME
     *       SaleManager check an IssueToken-leg contributor must pass.
     *   (c) messageCertRequireUserSignature verifies signedMessage ecrecovers to
     *       msg.sender over rawMessage.
     *   (d) messageCertRequireAdminApproval requires `adminApprovalSig` to be a
     *       TokenAdmin signature over keccak256(this, chainId, msg.sender, rawMessage).
     * @return certIndex Index of the new cert in the caller's array.
     */
    function registerMessageCert(
        bytes32 rawMessage,
        bytes calldata signedMessage,
        bytes calldata adminApprovalSig,
        uint256 permitDeadline,
        uint8 permitV,
        bytes32 permitR,
        bytes32 permitS
    ) external nonReentrant onlyDelegated returns (uint256 certIndex) {
        if (rawMessage == bytes32(0)) revert CCM_EmptyCertMessage();

        if (messageCertRequireEligibility) {
            (uint8 statusMode, , ) = ICCMSaleManager(issueTokenSaleManager).getPurchaseEligibility(msg.sender);
            if (statusMode == 0) revert CCM_NotEligible();
        }

        if (messageCertRequireUserSignature) {
            if (_recoverSigner(_ethSignedHash(rawMessage), signedMessage) != msg.sender) {
                revert CCM_BadUserSignature();
            }
        }

        address recoveredAdminApprover = address(0);
        if (messageCertRequireAdminApproval) {
            bytes32 approvalDigest = keccak256(abi.encode(address(this), block.chainid, msg.sender, rawMessage));
            recoveredAdminApprover = _recoverSigner(_ethSignedHash(approvalDigest), adminApprovalSig);
            if (recoveredAdminApprover == address(0) ||
                !IController(peerTreasuryController).isOfficialEntityFast(KECCAK_TOKEN_ADMIN, recoveredAdminApprover)) {
                revert CCM_CertNotApproved();
            }
        }

        bool payInToken = messageCertPayInToken;
        address asset = payInToken ? issueTokenAddress : stableCoinAddress;
        uint256 cost = payInToken ? tokenCostToRegisterSignedMessage : stableCostToRegisterSignedMessage;
        if (cost > 0) {
            if (asset == address(0)) revert CCM_StablecoinNotSet();
            if (permitDeadline != 0) {
                ICCMERC20Permit(asset).permit(msg.sender, address(this), cost, permitDeadline, permitV, permitR, permitS);
            }
            if (!ICCMERC20(asset).transferFrom(msg.sender, address(this), cost)) revert CCM_CertCostNotPaid();
        }

        MessageCert[] storage arr = _messageCertsByUser[msg.sender];
        arr.push(MessageCert({
            rawMessage: rawMessage,
            signedMessage: signedMessage,
            timestamp: block.timestamp,
            costPaid: cost,
            paidInToken: payInToken,
            recoveredAdminApprover: recoveredAdminApprover
        }));
        certIndex = arr.length - 1;

        emit MessageCertRegistered(msg.sender, certIndex, rawMessage, cost, payInToken, recoveredAdminApprover);
    }

    /* ========== SIGNATURE HELPERS (EOA ecrecover) ========== */

    /// @dev EIP-191 "personal_sign" digest of a 32-byte payload.
    function _ethSignedHash(bytes32 h) private pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", h));
    }

    /// @dev Recover the signer of a 65-byte (r,s,v) signature; returns
    ///      address(0) on malformed input or invalid v. EOA-only (no ERC-1271).
    function _recoverSigner(bytes32 digest, bytes memory sig) private pure returns (address) {
        if (sig.length != 65) return address(0);
        bytes32 r;
        bytes32 s;
        uint8 v;
        assembly ("memory-safe") {
            r := mload(add(sig, 0x20))
            s := mload(add(sig, 0x40))
            v := byte(0, mload(add(sig, 0x60)))
        }
        if (v < 27) v += 27;
        if (v != 27 && v != 28) return address(0);
        return ecrecover(digest, v, r, s);
    }
}

@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/ExecutivePeerTreasury.sol

// SPDX-License-Identifier: UNLICENSED
// =====================================================================
//  EquityMint.org / DataCloud OS  —  Official Sovereign Issuance Suite
//  Module: ExecutivePeerTreasury.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 2017-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.
// 
// Executive Peer Treasury - Base treasury contract enabling secure ETH and ERC20 token transfers between 
// authorized contracts with role-based access control. Provides foundation for peer-to-peer treasury operations
// across the EquityMint ecosystem with TreasuryAdmin and Super role enforcement integrated with Controller.
// 
// Chief Architect and CEO: Ken Silverman, US Fintech LLC
// Designed by Ken Silverman as part of the EquityMint treasury infrastructure.
// @author Ken Silverman
// 
// ⚖️  AUTHORIZED USE RESTRICTIONS:
// Only projects deploying these contracts via the EquityMint platform at equitymint.org 
// which contain this preamble and Fee structures generated through EquityMint.org have 
// permission to use these contracts or any derivative works thereto. Any such deployment 
// must contain these words. This contract is part of a greater system. They are owned 
// and licensed exclusively in writing and through US Fintech, LLC. 
// 
// Any breach of these terms will be investigated and pursued through all available civil 
// and criminal remedies to the fullest extent permitted by applicable law. Enforcement is 
// discretionary. The failure to enforce any provision shall not constitute a waiver of the 
// right to enforce at any time. All projects and platform users interacting with this system 
// are subject to additional terms and conditions as may be published or updated from time to 
// time at https://equitymint.org and/or https://DataCloudOS.com.
pragma solidity 0.8.35;

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

// Earlier versions Compiled by Maleeha Naveed. May 5th, 2025
// ExecutivePeerTreasury is a contract that allows for the transfer of ETH and ERC20 tokens between different contracts.
/// @author Ken Silverman 
// - first decentralized RWA management architect, est. 2017.
contract ExecutivePeerTreasury is TreasuryConstants {

    using SafeERC20 for IERC20;
    
    event PeerTreasuryReceivedETH(address indexed sender, uint256 amount);
    event PeerTreasuryReceivedTokens(address indexed sender, address indexed token, uint256 amount);
    event PeerTreasuryTransferredETH(address indexed to, uint256 amount);
    event PeerTreasuryTransferredTokens(address indexed to, address indexed token, uint256 amount);
    event ExecutiveWithdrawalEvent(address indexed adminCaller, address indexed receiver, uint256 amt, string note, address tokenOrZero);
    event StableCoinAddressChanged(address newStableCoinAddress, address indexed changedBy);


    struct TreasuryEntry {
        uint256 totalReceived;
        uint256 totalWithdrawn;
    }

    struct Withdrawal{
        address to;
        address asset;
        uint256 amt;
        string note;
    }

    // PROXY BUILD: peerTreasuryController / feeManager / issueTokenAddress were
    // `immutable` in the full-deployment build. Clones share one runtime bytecode,
    // so per-project values cannot live in code — storage variables, assigned once
    // in __ExecutivePeerTreasury_init (or the transitional constructor).
    address public peerTreasuryController;
    address public feeManager;
    address public issueTokenAddress;
    address public stableCoinAddress; // Can be set by children or via setter

    mapping(address => TreasuryEntry) private tokenPeerTreasury;
    address[] internal knownTokens; // <-- Needed for enumeration

    TreasuryEntry private ethPeerTreasury;
    Withdrawal[] private withdrawals; // Track all executive withdrawals

    error LowEthBal();
    error LowTokenBal();
    error SenderNotOfficialSC();
    error RecipientNotOfficialSC();
    error InvalidController();
    error ETHTransferFailed();
    error InvalidTokenAddress();
    error InsufficientUSDCForFees();
    error NoETHSent();
    error ZeroAmount();
    error InvalidAddress();

    modifier onlyTreasuryOrSCAdmin() {
        require(
            IController(peerTreasuryController).isOfficialDoubleEntityFast(KECCAK_TREASURY_ADMIN, msg.sender, KECCAK_SMART_CONTRACT, msg.sender, false),
            "Unauthorized"
        );
        _;
    }

    // PROXY BUILD: the constructor is retained (transitionally) so contracts not yet
    // converted to the clone pattern keep compiling; converted contracts call
    // __ExecutivePeerTreasury_init from their initialize() instead. One shared body.
    // A ZERO controller signals an inert MODEL deployment by a converted child
    // (models take no real args and must not touch a live Controller); unconverted
    // children always pass a real controller and get full legacy behavior.
    constructor(
        address _controller,
        address _feeManager,
        address _issueToken,
        string memory _contractName
    ) {
        if (_controller != address(0)) {
            __ExecutivePeerTreasury_init(_controller, _feeManager, _issueToken, _contractName);
        }
    }

    /// @dev Clone-side equivalent of the constructor. Called exactly once, from the
    ///      inheriting contract's initialize() (guarded there by `initializer`).
    ///      Self-registers with the Controller via init() — in the clone flow this runs
    ///      inside the factory transaction while the Controller's init window is open,
    ///      exactly as the constructor did in the full-deployment flow.
    function __ExecutivePeerTreasury_init(
        address _controller,
        address _feeManager,
        address _issueToken,
        string memory _contractName
    ) internal {
        if (_controller == address(0)) revert InvalidController();

        peerTreasuryController = _controller;
        feeManager = _feeManager;
        issueTokenAddress = _issueToken;

        // Get stablecoin address from IssueToken (if provided)
        // Skip if _issueToken == address(this) (called from IssueToken's own initialize - can't query self yet)
        // IssueToken will set its own stableCoinAddress in its initialize body after this runs
        if (_issueToken != address(0) && _issueToken != address(this)) {
            (bool success, bytes memory data) = _issueToken.staticcall(
                abi.encodeWithSignature("stableCoinAddress()")
            );
            if (success && data.length == 32) {
                stableCoinAddress = abi.decode(data, (address));
            }
        }

        IController(_controller).init(address(this), _contractName);
    }

    // EMERGENCY withdraw for admin controlled DIRECT withdrawals to a PERSON (not a smart contract)
    // this can ONLY happen for example, when the company wants to send some USDC or ETH from the Sales contract
    // to an EXECUTIVE of the company for the purposes of exchanging to USDC, as an example.
    // Such USDC can be spent on a capital expense or manually passed into the vesting pool.
    // ONLY HUBS can do this. For example, only contracts GENERATING or expected to RECEIVE
    // ETH or tokens from an external event (not from a HUB)  should be declared as HUBS.
    // EXCEPTIONS: send tokens to a launchpad or other noted entity can be a SC.
    function executiveWithdrawETH(address personAddress, uint256 amt, string memory note) public virtual onlyTreasuryOrSCAdmin {
        if (address(this).balance < amt) revert LowEthBal();
        (bool success, ) = payable(personAddress).call{value: amt}("");
        if (!success) revert ETHTransferFailed();
        ethPeerTreasury.totalWithdrawn += amt;
        withdrawals.push(Withdrawal(personAddress,address(0),amt,note));
        emit ExecutiveWithdrawalEvent(msg.sender, personAddress, amt, note, address(0));
    }

    function executiveWithdrawTokens(address personAddress, uint256 amt, address tokenSCAddress, string calldata note) public virtual onlyTreasuryOrSCAdmin {
        if (tokenSCAddress == address(0)) revert InvalidTokenAddress();
        IERC20 token = IERC20(tokenSCAddress);
        if (token.balanceOf(address(this)) < amt) revert LowTokenBal();
        
        // If withdrawing IssueToken, manually collect transfer fees (like holder fees in PRT)
        // Transfer itself will be fee-exempt (SmartContract → User), but we collect fees anyway
        if (tokenSCAddress == issueTokenAddress && feeManager != address(0)) {
            // pass 0 value, no percent TRANSFERfees possible.
            // without saleManager, NAVPool or LP price. Absolute fees only.
            // TODO next version get from NAV last price with SaleManger or LP last price fallback
            // Passing 0 instead of tokenAmount, still preserves absolute TRANSFER fees  
            (IFeeManager.CalculatedEntityAmount[] memory fees, uint256 totalFee) = 
                IFeeManager(feeManager).calculateChainedAmounts(0, 10000, keccak256("Transfer"));
            
            if (totalFee > 0) {
                // Distribute fees by pulling from msg.sender (same as IssueToken transfer fees)
                for (uint256 i = 0; i < fees.length; i++) {
                    if (fees[i].amount > 0) {
                        IERC20(stableCoinAddress).safeTransferFrom(msg.sender, fees[i].entityAddress, fees[i].amount);
                    }
                }
            }
        }
        
        // Execute token transfer (fee-exempt since we're a SmartContract)
        IERC20(tokenSCAddress).safeTransfer(personAddress, amt);
        tokenPeerTreasury[tokenSCAddress].totalWithdrawn += amt;
        withdrawals.push(Withdrawal(personAddress,tokenSCAddress,amt,note));
        emit ExecutiveWithdrawalEvent(msg.sender, personAddress, amt, note, tokenSCAddress);
    }

    /// @notice Receive ETH from any source and track it
    function peerTreasuryReceiveETH() virtual external payable {
        if (msg.value == 0) revert NoETHSent();
        if (!IController(peerTreasuryController).isOfficialEntityFast(KECCAK_SMART_CONTRACT, msg.sender)) revert SenderNotOfficialSC();
        ethPeerTreasury.totalReceived += msg.value;
        emit PeerTreasuryReceivedETH(msg.sender, msg.value);
    }

    /// @notice Transfer ETH to another peer contract (OfficialEntity SmartContract)
    function peerTreasuryTransferETH(address payable to, uint256 amount) virtual public onlyTreasuryOrSCAdmin {
        if (address(this).balance < amount) revert LowEthBal();
        if (!IController(peerTreasuryController).isOfficialEntityFast(KECCAK_SMART_CONTRACT, to)) revert RecipientNotOfficialSC();
        ethPeerTreasury.totalWithdrawn += amount;
        ExecutivePeerTreasury(to).peerTreasuryReceiveETH{value: amount}();
        emit PeerTreasuryTransferredETH(to, amount);
    }

    /// @notice Receive ERC20 tokens and track source
    function peerTreasuryReceiveTokens(address token, uint256 amount) virtual external {
        if (amount == 0) revert ZeroAmount();
        if (!IController(peerTreasuryController).isOfficialEntity("SmartContract", msg.sender)) revert SenderNotOfficialSC();
        IERC20(token).safeTransferFrom(msg.sender, address(this), amount);

        // Track the token if it's the first time we're seeing it
        if (tokenPeerTreasury[token].totalReceived == 0 && tokenPeerTreasury[token].totalWithdrawn == 0) {
            knownTokens.push(token);
        }

        tokenPeerTreasury[token].totalReceived += amount;
        emit PeerTreasuryReceivedTokens(msg.sender, token, amount);
    }

    /// @notice Transfer ERC20 tokens to another peer contract (OfficialEntity SmartContract)
    function peerTreasuryTransferTokens(address token, address to, uint256 amount) virtual public onlyTreasuryOrSCAdmin {
        if (IERC20(token).balanceOf(address(this)) < amount) revert LowTokenBal();
        if (!IController(peerTreasuryController).isOfficialEntityFast(KECCAK_SMART_CONTRACT, to)) revert RecipientNotOfficialSC();
        tokenPeerTreasury[token].totalWithdrawn += amount;
         // Get current allowance and reset to zero using decrease
        uint256 currentAllowance = IERC20(token).allowance(address(this), to);
        if (currentAllowance > 0) {
            IERC20(token).safeDecreaseAllowance(to, currentAllowance);
        }
        // Set new allowance using increase
        IERC20(token).safeIncreaseAllowance(to, amount);
        ExecutivePeerTreasury(to).peerTreasuryReceiveTokens(token, amount);
        emit PeerTreasuryTransferredTokens(to, token, amount);
    }

    /// @notice Check ETH available (total received - total withdrawn)
    /// @return The signed balance (can be negative if more was withdrawn than received - which is OK!)
    /// obviously the first lateral movement will be a withdrawal from a peerTreasury source
    function peerETHAvailable() external view returns (int256) {
        // Convert to int256 before subtraction to allow negative results
        return int256(ethPeerTreasury.totalReceived) - int256(ethPeerTreasury.totalWithdrawn);
    }

    /// @notice Check token available (total received - total withdrawn)
    /// @return The signed balance (can be negative if more was withdrawn than received)
    /// obviously the first lateral movement will be a withdrawal from a peerTreasury source
    function peerTokenAvailable(address token) external view returns (int256) {
        TreasuryEntry storage e = tokenPeerTreasury[token];
        // Convert to int256 before subtraction to allow negative results
        return int256(e.totalReceived) - int256(e.totalWithdrawn);
    }

    struct TreasurySnapshot {
        address token;
        uint256 totalReceived;
        uint256 totalWithdrawn;
    }


    /// @notice Return all known peer treasury token entries
   function getPeerTreasuries() external view returns (TreasurySnapshot[] memory) {
        uint256 len = knownTokens.length;
        TreasurySnapshot[] memory result = new TreasurySnapshot[](len);
        for (uint256 i = 0; i < len; i++) {
            address token = knownTokens[i];
            TreasuryEntry storage entry = tokenPeerTreasury[token];

            result[i] = TreasurySnapshot({
                token: token,
                totalReceived: entry.totalReceived,
                totalWithdrawn: entry.totalWithdrawn
            });
        }
        return result;
    }

    /// @notice Return individual peer treasury entry for a token
    function getPeerTreasury(address token) external view returns (uint256 received, uint256 withdrawn) {
        TreasuryEntry storage entry = tokenPeerTreasury[token];
        return (entry.totalReceived, entry.totalWithdrawn);
    }

    /// @notice Return ETH treasury data
    function getPeerTreasuryETH() external view returns (uint256 received, uint256 withdrawn) {
        return (ethPeerTreasury.totalReceived, ethPeerTreasury.totalWithdrawn);
    }

    function getAllWithdrawals() external view returns(Withdrawal[] memory){
        return withdrawals;
    }

    
    
    // SAFE DIRECT METHODS
    /// @notice DIRECT TOKEN TRANSFER - Transfer tokens directly without approve/transferFrom pattern
    /// @param token Token contract address
    /// @param to Recipient PeerTreasury contract
    /// @param amount Amount to transfer
    function peerTreasuryTransferTokensDirect(address token, address to, uint256 amount) virtual public onlyTreasuryOrSCAdmin {
        if (IERC20(token).balanceOf(address(this)) < amount) revert LowTokenBal();
        if (!IController(peerTreasuryController).isOfficialEntityFast(KECCAK_SMART_CONTRACT, to)) revert RecipientNotOfficialSC();
        // Update withdrawal tracking
        tokenPeerTreasury[token].totalWithdrawn += amount;
        // Direct transfer - handles USDT properly
        IERC20(token).safeTransfer(to, amount);
        // Notify receiver for tracking (no actual transfer needed)
        ExecutivePeerTreasury(to).peerTreasuryNotifyReceived(token, amount);
        emit PeerTreasuryTransferredTokens(to, token, amount);
    }

    /// @notice NOTIFICATION METHOD - Update counters when tokens received via direct transfer
    /// @param token Token contract address  
    /// @param amount Amount received
    function peerTreasuryNotifyReceived(address token, uint256 amount) virtual public {
        if (!IController(peerTreasuryController).isOfficialEntityFast(KECCAK_SMART_CONTRACT, msg.sender)) revert SenderNotOfficialSC();
        // Update received tracking (same as peerTreasuryReceiveTokens but no transferFrom)
        tokenPeerTreasury[token].totalReceived += amount;
        // tokenPeerTreasury[token].currentBalance += amount;
        emit PeerTreasuryReceivedTokens(msg.sender, token, amount);
    }

    /// @notice Receive ETH fees from FeeManager (ultra-lightweight, no accounting)
    /// @dev ONLY for FeeManager → ProjectRevenueTreasury ETH fee distribution
    ///      Does NOT update totalReceived (reserved for peer-to-peer transfer accounting)
    ///      Does NOT emit events (gas optimization)
    ///      ⚠️ Use peerTreasuryReceiveETH() for tracked peer transfers that trigger downstream logic
    ///      ⚠️ NORMAL OPERATION: Funds received via this method are NOT auto-deployed
    ///         They accumulate in treasury balance until processRevenueAndDisperse() is called
    function receiveFee() external payable {
        // Just accept ETH - no tracking or events
    }

    /// @notice Set or update the stablecoin address used for fee payments
    /// @param newStableCoinAddress New stablecoin contract address (e.g., USDC)
    /// @dev Can only be called by PlatformTreasurer
    ///      Updates stableCoinAddress for this contract and all children can access it
    ///      Made public virtual so IssueToken can override with super.setStableCoinAddress()
    function setStableCoinAddress(address newStableCoinAddress) public virtual {
        if (!IController(peerTreasuryController).isOfficialEntityFast(KECCAK_TOKEN_ADMIN, msg.sender)) revert NotTokenAdmin();
        if (!IController(peerTreasuryController).isPlatformAdmin(newStableCoinAddress, KECCAK_OFFICIAL_STABLECOIN)) revert InvalidStablecoin();
        if (newStableCoinAddress == address(0)) revert InvalidAddress();
        stableCoinAddress = newStableCoinAddress;
        emit StableCoinAddressChanged(newStableCoinAddress, msg.sender);
    }
    
}

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

interfaces/IFeeManager.sol

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

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

    struct CalculatedEntityAmount {
        address entityAddress;
        uint256 amount;
    }

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

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

    // Per-root subtree freeze (Project Admin, after freezeDelay, reversible).
    // When set, blocks all mutations in that subtree for every caller (including platform).
    // Default chain type only — flat map, no bytes32 outer key.
    function freezeRootPath(address root, bool isFreeze) external returns (bool);
    function rootFamilyLocked(address root) external view returns (bool);
    
    // Query functions
    function isChainedEntity(string calldata chainType, address entity) external view returns (bool);
    
    function isChainedEntityFast(bytes32 hashedChainType, address entity) external view returns (bool);
    
    function getChainedEntity(string calldata chainType, address entity) external view returns (ChainedEntityStruct memory);
    
    function getActiveChainedEntities(string calldata chainType) external view returns (ChainedEntityStruct[] memory);
    
    // Fee calculation with hash (GAS-OPTIMIZED: ~200-300 gas savings vs string version)
    // Saves gas by avoiding ABI encoding overhead (96 bytes for string vs 32 bytes for hash)
    function calculateChainedAmounts(
        uint256 totalVal,
        uint256 maxPct,
        bytes32 feeTypeHash
    ) external view returns (
        CalculatedEntityAmount[] memory calculatedAmounts,
        uint256 totalAmount
    );
    
    // Fee calculation (advanced - custom chain type with uint8 feeType)
    function calculateChainedAmounts(
        bytes32 chainType,
        uint256 totalVal,
        uint256 maxPct,
        uint8 feeType
    ) external view returns (
        CalculatedEntityAmount[] memory calculatedAmounts,
        uint256 totalAmount
    );
    
    function distributeFees(
        CalculatedEntityAmount[] calldata calculatedFees,
        address payer,
        address paymentToken
    ) external returns (uint256 totalDistributed);
    
    function triggerNotify() external;
    
    // Fee type management
    function addFeeType(string calldata label) external;  // Auto-assigns next fee type
    function getAllFeeTypeLabels() external view returns (string[] memory);  // Batch getter for all labels
    function feeTypeLabels(uint8 index) external view returns (string memory);  // Query by array index 0-49!
    function feeTypeLabelToType(string calldata label) external view returns (uint8);  // Reverse mapping: label → type
    function getTypeForLabel(string calldata label) external view returns (uint8);  // Get type by label (reverts if undefined)
    function currentMaxFeeType() external view returns (uint8);  // Returns current max fee type (dynamic, starts at 7, max 50)
    function ABSOLUTE_MAX_FEE_TYPES() external view returns (uint8);  // Returns 50
    // v43108: canonical-6-dec → official-stable-atomics output multiplier (10**(decimals-6)).
    // 0 (pre-v43108 instance) must be treated as 1 by callers. See FeeManager.stableScale.
    function stableScale() external view returns (uint256);
    function syncStableCoin(string calldata itLabel) external;  // TRUSTLESS re-sync after stable rotation: anyone may call — label must be "IssueToken_<symbol>" (strict prefix guard) and resolve on the clone's own controller; coin read from that IT's live stableCoinAddress()
    
    // ProjectRevenueTreasury notification registration
    function setProjectRevenueTreasury(address treasury) external;  // One-time registration of treasury for fee notifications
    
    // Constants
    function BASIS_POINTS_DIVISOR() external view returns (uint256);
    function ACTION_ADD() external view returns (uint8);
    function ACTION_UPDATE() external view returns (uint8);
    function ACTION_REMOVE() external view returns (uint8);
    function ACTION_LOCK() external view returns (uint8);
    function ACTION_UNLOCK() external view returns (uint8);
    function ACTION_REACTIVATE() external view returns (uint8);
}

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

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.