Skip to content
Verified contractExactUNLICENSED

ExecutiveReleaseManager

Address0x08d8d0bae673c5b4e4a0ae3b6063b57557f5acf3
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, 5,000 runs
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,340,273
Creation transaction
0x66b828c9cf…c35f76ac9d

contracts/ExecutiveReleaseManager.sol

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

import "../interfaces/IController.sol";
import "../interfaces/IElasticTreasuryHub.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./ExecutivePeerTreasury.sol"; // New! Peer Treasury for tracked ETH/token inflows/outflows outside the HUB SPOKE model - lateral transfers acording to your topology
import "./CloneInitializable.sol";
/// @notice v43107 (folded, no version bump): minimal view of IssueToken's lifetime-holder map,
///         used by the once-per-NEW-holder payout transfer fee (see _collectPayoutTransferFee).
interface IIssueTokenHolderQueryERM {
    function isHolder(address account) external view returns (bool);
}
/// @author Ken Silverman
/// @notice Manages the release of tokens and/or eth from a secure network of Smart Contracts comprising a private secure network of treasury accounts.
/// @dev PROXY BUILD: EIP-1167 clone variant — inert MODEL + per-project clones via initialize().
contract ExecutiveReleaseManager is ExecutivePeerTreasury, CloneInitializable {

    using SafeERC20 for IERC20;
    
    uint16 public constant CONTRACT_VERSION = 43109; // v43109: TransferAgent permanentRestrictThenCancel (re-key / court-order cancel of ALL schedules incl. non-revokable, every asset) + beneficiaryRestricted gate on claim/new schedules; cold admin bodies (forced start times, cliff/period, fee mode, linearVest, permanentRestrictThenCancel) moved to the ctor-deployed ExecutiveReleaseManagerSidecar (EIP-170). Prior: 43103.
    uint256 private constant TWO_YEARS_SECONDS = 732 days;
    uint256 private constant ONE_YEAR_SECONDS = 365 days;
    
    // Custom errors (gas-optimized)
    error InvalidBeneficiary();
    error InvalidPayAmount();
    error InvalidNumPayments();
    error InvalidPeriod();
    error InvalidStartTime();
    error InvalidCliff();
    error InsufficientBalance();
    error NoSchedulesFound();
    error NothingToClaim();
    error InvalidScheduleIndex();
    error NotRevokable();
    error TransferFailed();
    error NumUnlocksZero();
    error UnlockIntervalTooSmall();
    error VestingTooShort();
    error Unauthorized();
    // Single mapping for all assets (tokens and ETH)
    mapping(address => uint256) public globalAmountOwed;
    // ETH address constant for dummy ETH addresskey
    address constant ETH_ADDRESS = address(0);
    // Array to track all asset addresses with non-zero amounts
    address[] public globalAssetAddresses;

    // Replace blocksPerPeriod with secondsPerPeriod (30 days default)
    // PROXY BUILD: `= 2592000` default moved to initialize() (inline initializers never run for clones).
    uint256 public secondsPerPeriod; 

    // Only need one mapping for forced start times
    // NEW!  support for forced start times for early purchasers and early founder/purchasers 
    //(no need for DTVX!)
    mapping(address => uint256) private forcedStartTimes;

    struct Schedule {
        uint256 singlePayAmount;
        uint256 numPayments;
        uint256 totalValue;
        uint256 totalLeftToPay;
        uint256 startTimestamp;
        uint256 lastClaimedTime;
        uint256 periodSeconds;     
        uint256 totalPaidOut;
        bool isRevokable;
    }

    ///@notice This is the input structure for the beneficiary schedule
    struct BeneficiaryScheduleInput {
        address beneficiary;
        uint256 singlePayAmount;
        uint256 numPayments;
        uint256 startTimeOffsetSeconds;  // renamed from startBlockOffset
        bool isStartTimeAbsolute;
        uint256 periodSeconds;          // Add this field
        bool isRevokable;
    }

    struct BeneficiarySchedule {
        address beneficiary;
        Schedule schedule;
    }

    // support preferential or (delayed)  from known DTVC holders with different roles 
    // ie early purchasers instead of launch pad holders for excample
    struct ForcedStartTimeData {
        address beneficiary;
        uint256 startTime;
    }

    // key is the token contract address, value is a map with key as the beneficiary address and value as an array of schedules
    mapping(address => mapping(address => Schedule[])) public schedules;
    // key is the token contract address, value is an array of beneficiaries
    mapping(address => address[]) public tokenScheduleBeneficiaries;
    mapping(address => Schedule[]) public ethSchedules;
    address[] public ethScheduleBeneficiaries;
    // PROXY BUILD: `= 90 days` default moved to initialize().
    uint256 public defaultCliffSeconds;

    // Replace period event
    event PeriodChanged(uint256 oldSecondsPerPeriod, uint256 newSecondsPerPeriod);
    event DefaultCliffChanged(uint256 oldCliffSeconds, uint256 newCliffSeconds);

    // Optimized event declarations
    event ReleaseScheduleAdded(address indexed tokenContractAddressOrZeroForETH, address indexed beneficiary, uint256 totalValue, uint256 startTimestamp);
    event ReleaseScheduleListAdded(address indexed tokenContractAddressOrZeroForETH, uint256 successfullyAdded);
    event ScheduleClaimed(address indexed tokenContractAddressOrZeroForETH, address indexed beneficiary, uint256 amountClaimed);
    event ForcedStartTimeAdded(address indexed beneficiary, uint256 startTime, bool isAbsolute);
    event ForcedStartTimeRemoved(address indexed beneficiary);



     modifier onlyTreasuryAdminOrContract() {
        if(!IController(peerTreasuryController).isOfficialDoubleEntityFast(KECCAK_TREASURY_ADMIN, msg.sender, KECCAK_SMART_CONTRACT, msg.sender, false)) revert Unauthorized();
        _;
    }
    // ===== v43109: COLD-PATH SIDECAR (bytecode) =====
    // ExecutiveReleaseManagerSidecar (bottom of this file) carries the bodies of the
    // rarely-called admin / TransferAgent functions. Deployed ONCE by this model's
    // constructor; its address is an immutable, so clones (which run this model's
    // code) see it — NO factory / PPAM / UI change. Stubs below forward msg.data via
    // delegatecall: bodies run against the CLONE's storage with the caller's
    // msg.sender, events are emitted from the clone — byte-identical semantics.
    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()) }
        }
    }

    // ===== PROXY BUILD: MODEL CONSTRUCTOR =====
    // No arguments; permanently locks the model. Zero controller tells
    // ExecutivePeerTreasury this is an inert model deployment.
    constructor() ExecutivePeerTreasury(address(0), address(0), address(0), "") {
        SIDECAR = address(new ExecutiveReleaseManagerSidecar());
        _disableInitializers();
    }

    // ===== PROXY BUILD: CLONE CONSTRUCTOR-EQUIVALENT =====
    // _hub must be the token contract address
    function initialize(
        address _controller,
        address _feeManager,
        address _issueToken
    ) external initializer {
        __ExecutivePeerTreasury_init(_controller, _feeManager, _issueToken, "ExecutiveReleaseManager");
        // Ex-inline initializer defaults (see declarations):
        secondsPerPeriod = 2592000;
        defaultCliffSeconds = 90 days;
        transferFeeChargeMode = 1; // default: chargeOnce per NEW lifetime holder
    }

    // ===== v43107 (folded, no version bump): payout transfer-fee collection =====
    // ERM's claim() sends IssueTokens SC -> EOA, which the token layer fee-exempts
    // (TimeLock Scenario 5). But every FIRST-TIME holder created that way still accrues
    // a platform HOLDER fee against the ProjectRevenueTreasury. Default mode 1 keeps
    // that covered: pull the ABSOLUTE stablecoin Transfer-chain fees (base 0 => percent
    // fees excluded) from the claimant ONCE — only when they have never held the token.
    // Mirrors ExecutivePeerTreasury.executiveWithdrawTokens' manual fee leg.
    /// @notice 0 = never charge, 1 = once per NEW lifetime holder (default,
    ///         "to allow for default covering of any platform level holder fee"), 2 = every claim.
    /// @dev PROXY BUILD: `= 1` default set in initialize() (inline initializers never run for clones).
    uint8 public transferFeeChargeMode;

    /// @notice TreasuryAdmin ∨ SmartContract. Body in ExecutiveReleaseManagerSidecar (v43109).
    function setTransferFeeChargeMode(uint8) external { _fwd(); }

    function _collectPayoutTransferFee(address payer, address recipient) internal {
        uint8 mode = transferFeeChargeMode;
        if (mode == 0 || feeManager == address(0)) return;
        // Mode 1: skip anyone who is (or ever was) a holder — no new holder-fee obligation.
        // NOTE: charge decision MUST happen BEFORE the token transfer marks them a holder.
        if (mode == 1 && IIssueTokenHolderQueryERM(issueTokenAddress).isHolder(recipient)) return;
        (IFeeManager.CalculatedEntityAmount[] memory fees, uint256 totalFee) =
            IFeeManager(feeManager).calculateChainedAmounts(0, 10000, keccak256("Transfer"));
        if (totalFee == 0) return;
        for (uint256 i = 0; i < fees.length; i++) {
            if (fees[i].amount > 0) {
                IERC20(stableCoinAddress).safeTransferFrom(payer, fees[i].entityAddress, fees[i].amount);
            }
        }
    }

    // New! Function to set forced start times for multiple beneficiaries
    // @param beneficiaries: array of addresses of beneficiaries
    // v43109 — bodies in ExecutiveReleaseManagerSidecar (TokenAdmin; cold). ABI unchanged.
    function addForcedStartTimes(ForcedStartTimeData[] calldata) external { _fwd(); }
    function removeForcedStartTimes(address[] calldata) external { _fwd(); }

    // New! Function to check if a beneficiary has a forced start time
    // @param beneficiary: address of the beneficiary
    function getForcedStartTime(address beneficiary) internal view returns (bool exists, uint256 startTime, bool isAbsolute) {
        startTime = forcedStartTimes[beneficiary];
        exists = startTime > 0;
        // Determine if absolute based on the value (> two years means absolute)
        isAbsolute = startTime > TWO_YEARS_SECONDS;
        return (exists, startTime, isAbsolute);
    }

    // @notice Add a token or ETH (address(0)) to the global token list
    function addToGlobalAssets(address tokenOrZero) internal {
        // Only try to add if current amount is zero (likely new asset)
        if (globalAmountOwed[tokenOrZero] == 0) {
            // Double-check by scanning the array to be sure it's not already tracked
            for (uint256 i = 0; i < globalAssetAddresses.length; i++) {
                if (globalAssetAddresses[i] == tokenOrZero) return;
            }
            // If truly not in the array, add it
            globalAssetAddresses.push(tokenOrZero);
        }
    }

    // v43109 — bodies in ExecutiveReleaseManagerSidecar (TokenAdmin; cold). ABI unchanged.
    function setDefaultCliffSeconds(uint256) external { _fwd(); }
    function changePeriod(uint256) external { _fwd(); }

// Modify _processSchedule to handle time offset in seconds
    function _processSchedule(address tokenOrZero, address beneficiary, uint256 singlePayAmount, uint256 numPayments, uint256 startTimeOffsetSeconds, bool isStartTimeAbsolute,
        uint256 periodSeconds, bool isRevokable, bool isMerge) internal returns (bool added) {
        // Initial setup
        added = false;
        // New! Check if beneficiary has a forced start time
        (bool hasForcedStart, uint256 forcedStartTime, bool forcedIsAbsolute) = getForcedStartTime(beneficiary);
        if (hasForcedStart) {
            startTimeOffsetSeconds = forcedStartTime;
            isStartTimeAbsolute = forcedIsAbsolute;
        }
        // Validate inputs
        // Set default time offset if 0 or -1 was passed
        if (!isStartTimeAbsolute) {
             if (startTimeOffsetSeconds == 0) {
                startTimeOffsetSeconds = defaultCliffSeconds;  // offset for cliff model
             }
        }
        if (periodSeconds == 0) {
            periodSeconds = secondsPerPeriod;
        }
        _validateScheduleInputs(beneficiary, singlePayAmount, numPayments, startTimeOffsetSeconds, periodSeconds, isStartTimeAbsolute);
        uint256 startTimestamp = isStartTimeAbsolute ? startTimeOffsetSeconds : block.timestamp + startTimeOffsetSeconds;
        // Calculate values
        uint256 newTotal = singlePayAmount * numPayments;
        // Attempt to merge if requested
        if (isMerge) {
            uint256 mergeResult = _attemptScheduleMerge(tokenOrZero, beneficiary, singlePayAmount, numPayments, newTotal,startTimestamp, periodSeconds, isRevokable);
            if (mergeResult == 1) {
                // Successfully merged
                added = true;
                emit ReleaseScheduleAdded(tokenOrZero, beneficiary, newTotal, startTimestamp);
                return added;
            }
            // For mergeResult 0 or 2, we'll create a new schedule below
        }
        // Create a new schedule
        Schedule[] storage beneficiarySchedules = tokenOrZero == address(0) ? ethSchedules[beneficiary] : schedules[tokenOrZero][beneficiary];
        // Track new beneficiaries
        if (beneficiarySchedules.length == 0) {
            if (tokenOrZero == address(0)) {
                ethScheduleBeneficiaries.push(beneficiary);
            } else {
                tokenScheduleBeneficiaries[tokenOrZero].push(beneficiary);
            }
        }
        // Create new schedule
        if (tokenOrZero == address(0)) {
            _createNewEthSchedule(beneficiary, singlePayAmount, numPayments, newTotal, startTimestamp, periodSeconds, isRevokable);
        } else {
            _createNewSchedule(tokenOrZero, beneficiary, singlePayAmount, numPayments, newTotal, startTimestamp, periodSeconds, isRevokable);
        }
        added = true;
        emit ReleaseScheduleAdded(tokenOrZero, beneficiary, newTotal, startTimestamp);
        return added;
    }

    // Update validation function for time-based offsets
    function _validateScheduleInputs(address beneficiary,uint256 singlePayAmount, uint256 numPayments, uint256 startTimeOffsetSeconds,uint256 periodSeconds, bool isStartTimeAbsolute) internal view {
        if(beneficiary == address(0) || beneficiaryRestricted[beneficiary]) revert InvalidBeneficiary();
        if(singlePayAmount == 0) revert InvalidPayAmount();
        if(numPayments == 0) revert InvalidNumPayments();
        if(periodSeconds > ONE_YEAR_SECONDS) revert InvalidPeriod();
        if (isStartTimeAbsolute) {
            if(startTimeOffsetSeconds > block.timestamp + TWO_YEARS_SECONDS || startTimeOffsetSeconds < block.timestamp - TWO_YEARS_SECONDS) revert InvalidStartTime();
            // commenting out the next line allows retroactive start times for early purchasers and early founder/purchasers  
            // Not our business model, but we will support it for other projects we provide this contract to under license.
            // require(startTimeOffsetSeconds >= block.timestamp, "Start time must be in the future"); 
        } else {
            if(startTimeOffsetSeconds > TWO_YEARS_SECONDS) revert InvalidStartTime();
        }
    }


    // Update merge function to use timestamps for comparison,, zero means ALWAYS use default even if changed over course of claim
    function _attemptScheduleMerge(address tokenOrZero, address beneficiary, uint256 singlePayAmount, uint256 numPayments,
        uint256 newTotal, uint256 startTimestamp,uint256 periodSeconds, bool isRevokable) internal returns (uint256 mergeResult) {
        // Default result: no match found
        mergeResult = 0;
        // Get the right schedules storage
        Schedule[] storage beneficiarySchedules = tokenOrZero == address(0) ? ethSchedules[beneficiary] : schedules[tokenOrZero][beneficiary];
        if (beneficiarySchedules.length > 0) {
            for (uint i = 0; i < beneficiarySchedules.length; i++) {
                Schedule storage existing = beneficiarySchedules[i];
                // Only consider schedules that match start timestamp and haven't started yet
                if (existing.startTimestamp == startTimestamp && block.timestamp < existing.startTimestamp) {
                    // Check if the existing schedule is non-revokable
                    if (!existing.isRevokable || existing.numPayments != numPayments) {
                        // Cannot merge into a non-revokable schedule or non-matching numPayments
                        return 2; // Return 2: found match but can't merge
                    }
                    // Check if periods match
                    bool periodsMatch = (existing.periodSeconds == periodSeconds) || 
                                        (existing.periodSeconds == 0 && periodSeconds == secondsPerPeriod) || 
                                        (periodSeconds == 0 && existing.periodSeconds == secondsPerPeriod);
                    if (periodsMatch) {
                        if (tokenOrZero == address(0)) {
                            if(address(this).balance < newTotal + globalAmountOwed[ETH_ADDRESS]) revert InsufficientBalance();
                        } else {
                            if(IERC20(tokenOrZero).balanceOf(address(this)) < newTotal + globalAmountOwed[tokenOrZero]) revert InsufficientBalance();
                        }
                        // Safety: ensure asset is tracked
                        addToGlobalAssets(tokenOrZero);     
                        // Update amounts
                        globalAmountOwed[tokenOrZero] += newTotal;
                        existing.singlePayAmount += singlePayAmount;
                        existing.numPayments = numPayments;
                        existing.totalValue += newTotal;
                        existing.totalLeftToPay += newTotal;
                        // Apply the more restrictive revokable status
                        existing.isRevokable = existing.isRevokable && isRevokable;
                        return 1; // Successfully merged
                    } else {
                        return 2; // Found match but can't merge due to period mismatch
                    }
                }
            }
        }
        return 0; // No match found
    }

    // Update _createNewSchedule function
    function _createNewSchedule(address tokenContractAddress, address beneficiary, uint256 singlePayAmount, uint256 numPayments, 
                            uint256 newTotal, uint256 startTimestamp, uint256 periodSeconds, bool isRevokable) private {
        if(IERC20(tokenContractAddress).balanceOf(address(this)) < newTotal + globalAmountOwed[tokenContractAddress]) revert InsufficientBalance();
        schedules[tokenContractAddress][beneficiary].push(Schedule({
            singlePayAmount: singlePayAmount,
            numPayments: numPayments,
            totalValue: newTotal,
            totalLeftToPay: newTotal,
            startTimestamp: startTimestamp,
            lastClaimedTime: 0,
            periodSeconds: periodSeconds,
            totalPaidOut: 0,
            isRevokable: isRevokable
        }));
        addToGlobalAssets(tokenContractAddress);
        globalAmountOwed[tokenContractAddress] += newTotal;
    }

    // Update _createNewEthSchedule function
    function _createNewEthSchedule(address beneficiary, uint256 singlePayAmount, uint256 numPayments, 
                                uint256 newTotal, uint256 startTimestamp, uint256 periodSeconds, bool isRevokable) private {
        if(address(this).balance < newTotal + globalAmountOwed[ETH_ADDRESS]) revert InsufficientBalance();
        
        ethSchedules[beneficiary].push(Schedule({
            singlePayAmount: singlePayAmount,
            numPayments: numPayments,
            totalValue: newTotal,
            totalLeftToPay: newTotal,
            startTimestamp: startTimestamp,
            lastClaimedTime: 0,
            periodSeconds: periodSeconds,
            totalPaidOut: 0,
            isRevokable: isRevokable
        }));
        addToGlobalAssets(ETH_ADDRESS);
        globalAmountOwed[ETH_ADDRESS] += newTotal;
    }

    function addReleaseScheduleAbsolute(address tokenContractAddress, address beneficiary, uint256 singlePayAmount, uint256 numPayments, 
        uint256 startTimeOffsetSeconds, bool isStartTimeAbsolute, uint256 periodSeconds,bool isRevokable, bool isMerge) public onlyTreasuryAdminOrContract returns (bool added) {
        return _processSchedule(tokenContractAddress, beneficiary, singlePayAmount, numPayments, startTimeOffsetSeconds,isStartTimeAbsolute,periodSeconds,isRevokable, isMerge);
    }

    // Update the public functions to accept seconds
    function addReleaseSchedule(address tokenContractAddress, address beneficiary, uint256 singlePayAmount, uint256 numPayments, 
        uint256 startTimeOffsetSeconds,uint256 periodSeconds,bool isRevokable, bool isMerge) public onlyTreasuryAdminOrContract returns (bool added) {
        return _processSchedule(tokenContractAddress, beneficiary, singlePayAmount, numPayments, startTimeOffsetSeconds,false,periodSeconds,isRevokable, isMerge);
    }

    function addEthReleaseSchedule(address beneficiary, uint256 singlePayAmount, uint256 numPayments, uint256 startTimeOffsetSeconds,uint256 periodSeconds,
        bool isRevokable,  bool isMerge) public onlyTreasuryAdminOrContract returns (bool added) {
        return _processSchedule(address(0), beneficiary, singlePayAmount, numPayments, startTimeOffsetSeconds,false,periodSeconds,isRevokable, isMerge);
    }

    // Also update addReleaseScheduleList
    function addReleaseScheduleList(address tokenContractAddressOrZeroForETH, BeneficiaryScheduleInput[] calldata scheduleData, bool isMerge) external onlyTreasuryAdminOrContract returns (uint256 addedCount) {
      for (uint i = 0; i < scheduleData.length; i++) {
        BeneficiaryScheduleInput calldata sched = scheduleData[i];
        if (addReleaseScheduleAbsolute(tokenContractAddressOrZeroForETH,sched.beneficiary,sched.singlePayAmount,sched.numPayments,sched.startTimeOffsetSeconds,sched.isStartTimeAbsolute,sched.periodSeconds,sched.isRevokable,isMerge)) {
            addedCount++;
        }
      }
      emit ReleaseScheduleListAdded(tokenContractAddressOrZeroForETH, addedCount);
      return addedCount;
    }


    /// @notice Claims all available payments up to the current block for the caller
    // Update claim function to use schedule-specific period
    // Merged claim function that handles both tokens and ETH
    /// @notice Default claim using global issueToken (convenience method)
    function claim() external {
        claim(issueTokenAddress);
    }

   function claim(address tokenContractAddress) public {
    if (beneficiaryRestricted[msg.sender]) revert Unauthorized(); // v43109 vacated wallet
    // Get the appropriate schedules
    Schedule[] storage userSchedules = tokenContractAddress == ETH_ADDRESS ? ethSchedules[msg.sender] : schedules[tokenContractAddress][msg.sender];
    if(userSchedules.length == 0) revert NoSchedulesFound();
    uint256 totalClaimAmount = 0;
    for (uint i = 0; i < userSchedules.length; i++) {
        Schedule storage sch = userSchedules[i];
        // Skip schedules that haven't started or have nothing to claim
        if (block.timestamp < sch.startTimestamp || sch.totalLeftToPay == 0) {
            continue;
        }
        // Simplified period logic: if periodSeconds > 0, use it; otherwise use global default
        // will NEVER be zero but here in case of a future allowing of ZERO to mean whatever the CURRENT period default is 
        // so in theory that could accelerate everybody's schedule who used zero.
        // but for now, no schedule can have a zero period as zero changes to default at time of adding schedule.
        uint256 periodToUse = sch.periodSeconds > 0 ? sch.periodSeconds : secondsPerPeriod;
        // Calculate complete periods using timestamps
        // floor operation
        uint256 periodsPassed = (block.timestamp - sch.startTimestamp) / periodToUse;
        // CRITICAL CHANGE: Add 1 to make the first payment available immediately at start
        // - At startTimestamp: periodsPassed=0, eligiblePayments=1
        // - After 1 period: periodsPassed=1, eligiblePayments=2
        // - After 2 periods: periodsPassed=2, eligiblePayments=3, etc.
        uint256 eligiblePayments = periodsPassed + 1;
        // Cap periods to the number of scheduled payments
        if (eligiblePayments > sch.numPayments) {
            eligiblePayments = sch.numPayments;
        }
        // Calculate total eligible amount with cliff model
        uint256 totalEligible = eligiblePayments * sch.singlePayAmount;
        // Ensure there's something new to claim
        if (totalEligible <= sch.totalPaidOut) {
            continue; // Nothing new to claim for this schedule
        }
        // Calculate amount to pay
        uint256 amountToPay = totalEligible - sch.totalPaidOut;
        // Update schedule state if payment is possible
        if (amountToPay > 0 && sch.totalLeftToPay >= amountToPay) {
            sch.totalPaidOut += amountToPay;
            sch.totalLeftToPay -= amountToPay;
            sch.lastClaimedTime = block.timestamp;
            globalAmountOwed[tokenContractAddress] -= amountToPay;
            totalClaimAmount += amountToPay;
        }
    }
    
    if(totalClaimAmount == 0) revert NothingToClaim();
    
    // v43107 (folded, no version bump): the safeTransfer below is fee-exempt at the token
    // layer (SC -> EOA), so collect the absolute Transfer-chain fee from the claimant here
    // (default: only once, when this claim creates a NEW lifetime holder). Must run BEFORE
    // the transfer, which flips IssueToken.isHolder[claimant] to true.
    if (tokenContractAddress != ETH_ADDRESS && tokenContractAddress == issueTokenAddress) {
        _collectPayoutTransferFee(msg.sender, msg.sender);
    }
    
    // Different transfer logic based on token type
    if (tokenContractAddress == ETH_ADDRESS) {
        (bool success, ) = msg.sender.call{value: totalClaimAmount}("");
        if(!success) revert TransferFailed();
    } else {
        IERC20(tokenContractAddress).safeTransfer(msg.sender, totalClaimAmount);
    }
    
    // Emit claim event
    emit ScheduleClaimed(tokenContractAddress, msg.sender, totalClaimAmount);
}



    // Add event for schedule removals
    event SchedulesRemoved(address indexed tokenContractAddress, address indexed beneficiary, uint256 amount, bool removedAll);
    event MultipleSchedulesRemoved(address indexed tokenContractAddress, uint256 beneficiaryCount, uint256 removedCount);

    // Update removeSchedule to handle both ETH and tokens
    function removeSchedule(address tokenContractAddress, address beneficiary, uint256 scheduleIndex, bool removeAll) public onlyTreasuryAdminOrContract returns (bool removed) {
        Schedule[] storage userSchedules = tokenContractAddress == ETH_ADDRESS ? ethSchedules[beneficiary] : schedules[tokenContractAddress][beneficiary];
        uint256 amountRemoved = 0;
        if (removeAll) {
            // Iterate backwards: swap-and-pop only revokable entries, preserving non-revokable ones
            for (uint i = userSchedules.length; i > 0; i--) {
                if (userSchedules[i - 1].isRevokable) {
                    amountRemoved += userSchedules[i - 1].totalLeftToPay;
                    if (i - 1 != userSchedules.length - 1) {
                        userSchedules[i - 1] = userSchedules[userSchedules.length - 1];
                    }
                    userSchedules.pop();
                }
            }
            if (amountRemoved > 0) {
                globalAmountOwed[tokenContractAddress] -= amountRemoved;
                removed = true;
            }
        } else {
            if(scheduleIndex >= userSchedules.length) revert InvalidScheduleIndex();
            
            if (userSchedules[scheduleIndex].isRevokable) {
                amountRemoved = userSchedules[scheduleIndex].totalLeftToPay;
                globalAmountOwed[tokenContractAddress] -= amountRemoved;
                
                if (scheduleIndex != userSchedules.length - 1) {
                    userSchedules[scheduleIndex] = userSchedules[userSchedules.length - 1];
                }
                userSchedules.pop();
                removed = true;
            }
        }
        
        if (removed) {
            _removeBeneficiaryIfEmpty(tokenContractAddress, beneficiary);
            emit SchedulesRemoved(tokenContractAddress, beneficiary, amountRemoved, removeAll);
        }
        return removed;
    }

    // Update removeMultipleSchedules to emit event
    function removeMultipleSchedules(address tokenContractAddress, address[] calldata beneficiaries) external onlyTreasuryAdminOrContract returns (uint256 removedCount) {
        removedCount = 0;
        for (uint i = 0; i < beneficiaries.length; i++) {
            if (removeSchedule(tokenContractAddress, beneficiaries[i], 0, true)) {
                removedCount++;
            }
        }
        // Emit event with summary information
        emit MultipleSchedulesRemoved(tokenContractAddress, beneficiaries.length, removedCount);
        return removedCount;
    }

    /* ========== v43109 TRANSFER AGENT: HOLDER-OF-RECORD RECOVERY ========== */

    /// @notice Wallets vacated by a TransferAgent recovery / court-ordered burn. APPENDED storage.
    mapping(address => bool) public beneficiaryRestricted;
    event BeneficiaryRecoveryApplied(address indexed origAddress, address indexed newAddress, uint256 schedulesAffected, bool restricted, address indexed by);

    /*
     * permanentRestrictThenCancel(origAddress, newAddress, revokeRestriction)
     *   TransferAgent ∨ SmartContract. Companion to DM.recoverHolder for vesting schedules.
     *   origAddress       Beneficiary wallet being vacated.
     *   newAddress        0 → CANCEL every schedule of origAddress on EVERY asset (tokens and
     *                     ETH), INCLUDING non-revokable ones (court order overrides the grant);
     *                     unpaid amounts return to the free treasury balance.
     *                     ≠0 → SWAP: every schedule of origAddress on every asset is moved
     *                     to newAddress (appended after any schedules it already has);
     *                     a forced start time, if any, moves with it.
     *   revokeRestriction true → ONLY clear beneficiaryRestricted[origAddress] and return.
     * v43109 — BODY in ExecutiveReleaseManagerSidecar (cold). ABI unchanged; plain comment
     * because the stub's parameters are unnamed (NatSpec @param would not parse).
     */
    function permanentRestrictThenCancel(address, address, bool) external { _fwd(); }

    function _removeBeneficiaryIfEmpty(address tokenOrZero, address beneficiary) internal {
        bool hasSchedules = tokenOrZero == address(0)
            ? ethSchedules[beneficiary].length > 0
            : schedules[tokenOrZero][beneficiary].length > 0;
        if (hasSchedules) return;

        if (tokenOrZero == address(0)) {
            _removeAddressFromArray(ethScheduleBeneficiaries, beneficiary);
        } else {
            _removeAddressFromArray(tokenScheduleBeneficiaries[tokenOrZero], beneficiary);
        }
    }

    function _removeAddressFromArray(address[] storage arr, address addr) internal {
        for (uint256 i = 0; i < arr.length; i++) {
            if (arr[i] == addr) {
                arr[i] = arr[arr.length - 1];
                arr.pop();
                return;
            }
        }
    }

    /// @notice Returns all schedules for a beneficiary
    function getAllSchedulesForBeneficiary(address tokenContractAddressOrZeroForEth, address beneficiary) external view returns (Schedule[] memory) {
        return tokenContractAddressOrZeroForEth == ETH_ADDRESS ? ethSchedules[beneficiary] : schedules[tokenContractAddressOrZeroForEth][beneficiary];
    }

    // Update this function to return all schedules
    // Update parameter name to be more explicit
    function getAllSchedulesByToken(address tokenContractAddressOrZeroForEth) external view returns (BeneficiarySchedule[] memory) {
        // Get the appropriate beneficiary list based on token type
        address[] memory benes = tokenContractAddressOrZeroForEth == ETH_ADDRESS ? ethScheduleBeneficiaries : tokenScheduleBeneficiaries[tokenContractAddressOrZeroForEth];
        uint256 totalSchedules = 0;
        // Count total number of schedules
        for (uint i = 0; i < benes.length; i++) {
            address bene = benes[i];
            totalSchedules += tokenContractAddressOrZeroForEth == ETH_ADDRESS 
                ? ethSchedules[bene].length 
                : schedules[tokenContractAddressOrZeroForEth][bene].length;
        }
        BeneficiarySchedule[] memory results = new BeneficiarySchedule[](totalSchedules);
        uint256 resultIndex = 0;
        // Populate results array
        for (uint i = 0; i < benes.length; i++) {
            address bene = benes[i];
            Schedule[] memory userScheds = tokenContractAddressOrZeroForEth == ETH_ADDRESS 
                ? ethSchedules[bene] 
                : schedules[tokenContractAddressOrZeroForEth][bene];
            
            for (uint j = 0; j < userScheds.length; j++) {
                results[resultIndex] = BeneficiarySchedule({
                    beneficiary: bene,
                    schedule: userScheds[j]
                });
                resultIndex++;
            }
        }
        return results;
    }

    /**
 * @notice Get schedules for a specific token with pagination support
 * @param tokenContractAddressOrZeroForEth Token address or 0 for ETH
 * @param startIndex The index to start from (0-based)
 * @param maxAmount Maximum number of schedules to return
 * @param isReversed If true, return schedules in reverse order (newest first)
 * @return results Array of beneficiary schedules
 * @return totalCount Total number of schedules available
 */
function getAllSchedulesByTokenPaginated(
    address tokenContractAddressOrZeroForEth,
    uint256 startIndex,
    uint256 maxAmount,
    bool isReversed
) external view returns (BeneficiarySchedule[] memory results, uint256 totalCount) {
    // Get the appropriate beneficiary list based on token type
    address[] memory benes = tokenContractAddressOrZeroForEth == ETH_ADDRESS 
        ? ethScheduleBeneficiaries 
        : tokenScheduleBeneficiaries[tokenContractAddressOrZeroForEth];
    
    // First count total schedules to determine array size and pagination bounds
    totalCount = 0;
    for (uint i = 0; i < benes.length; i++) {
        address bene = benes[i];
        totalCount += tokenContractAddressOrZeroForEth == ETH_ADDRESS 
            ? ethSchedules[bene].length 
            : schedules[tokenContractAddressOrZeroForEth][bene].length;
    }
    
    // Handle empty case
    if (totalCount == 0) {
        return (new BeneficiarySchedule[](0), 0);
    }
    
    // Validate startIndex
    if (startIndex >= totalCount) {
        startIndex = 0;
    }
    
    // Determine actual count to return (respecting bounds)
    uint256 countToReturn = maxAmount;
    if (countToReturn > totalCount) {
        countToReturn = totalCount;
    }
    if (startIndex + countToReturn > totalCount) {
        countToReturn = totalCount - startIndex;
    }
    
    // Initialize result array with the correct size
    results = new BeneficiarySchedule[](countToReturn);
    
    // Handle case where nothing to return
    if (countToReturn == 0) {
        return (results, totalCount);
    }
    
    // For reverse ordering, adjust the starting index
    uint256 effectiveStartIndex = startIndex;
    if (isReversed) {
        effectiveStartIndex = totalCount - startIndex - countToReturn;
    }
    
    // Find the schedules at the requested indices
    uint256 globalIndex = 0;
    uint256 resultIndex = 0;
    
    // Processing in forward order always (we'll handle reverse at the end)
    for (uint i = 0; i < benes.length && resultIndex < countToReturn; i++) {
        address bene = benes[i];
        Schedule[] memory userScheds = tokenContractAddressOrZeroForEth == ETH_ADDRESS 
            ? ethSchedules[bene] 
            : schedules[tokenContractAddressOrZeroForEth][bene];
        
        for (uint j = 0; j < userScheds.length && resultIndex < countToReturn; j++) {
            // Only include schedules that fall within our pagination window
            if (globalIndex >= effectiveStartIndex && globalIndex < (effectiveStartIndex + countToReturn)) {
                results[resultIndex] = BeneficiarySchedule({
                    beneficiary: bene,
                    schedule: userScheds[j]
                });
                resultIndex++;
            }
            globalIndex++;
        }
    }
    
    // If we need reverse order, reverse the array
    if (isReversed) {
        // Reverse the array in-place
        for (uint i = 0; i < countToReturn / 2; i++) {
            BeneficiarySchedule memory temp = results[i];
            results[i] = results[countToReturn - i - 1];
            results[countToReturn - i - 1] = temp;
        }
    }
    
    return (results, totalCount);
}

    
    // do not use modifier here, let super handle that. Its expensive.
    function peerTreasuryTransferETH(address payable to, uint256 amount) override public onlyTreasuryAdminOrContract {
        uint256 balance = address(this).balance;
        if(balance < globalAmountOwed[ETH_ADDRESS] + amount) revert InsufficientBalance();
        super.peerTreasuryTransferETH(to, amount);
    }
    // do not use modifier here, let super handle that. Its expensive.
    function peerTreasuryTransferTokens(address token, address to, uint256 amount) override public onlyTreasuryAdminOrContract {
        uint256 balance = IERC20(token).balanceOf(address(this));
        if(balance < globalAmountOwed[token] + amount) revert InsufficientBalance();
        super.peerTreasuryTransferTokens(token, to, amount);
    }

    // Protect beneficiary-owed tokens from TreasuryAdmin/SC drain. Emergency lever:
    // call removeSchedule / removeMultipleSchedules first to free obligations, then withdraw surplus.
    // Non-revokable schedules are permanent by explicit design (isRevokable=false).
    function peerTreasuryTransferTokensDirect(address token, address to, uint256 amount) override public onlyTreasuryAdminOrContract {
        uint256 balance = IERC20(token).balanceOf(address(this));
        if(balance < globalAmountOwed[token] + amount) revert InsufficientBalance();
        super.peerTreasuryTransferTokensDirect(token, to, amount);
    }

    function executiveWithdrawTokens(address personAddress, uint256 amt, address tokenSCAddress, string calldata note) public override onlyTreasuryAdminOrContract {
        uint256 balance = IERC20(tokenSCAddress).balanceOf(address(this));
        if(balance < globalAmountOwed[tokenSCAddress] + amt) revert InsufficientBalance();
        super.executiveWithdrawTokens(personAddress, amt, tokenSCAddress, note);
    }

    function executiveWithdrawETH(address personAddress, uint256 amt, string memory note) public override onlyTreasuryAdminOrContract {
        uint256 balance = address(this).balance;
        if(balance < globalAmountOwed[ETH_ADDRESS] + amt) revert InsufficientBalance();
        super.executiveWithdrawETH(personAddress, amt, note);
    }


    // OPTIONAL MANUAL ETH SCHEDULES FOR SPECIAL CASES ONLY IF IT DOES NOT TAKE TOO MUCH MEMORY
    // ===== NEW: ETH SCHEDULE ENUMERATION =====


    // ===== NEW: Add an ETH release schedule =====
    

    








    // Simple function for both token and ETH schedules, to be called by TokenSaleAndSwap
    function addDefaultSchedule(address tokenAddressOrZeroForETH, address recipient, uint256 amountPerPayment, uint256 numberOfPayments, 
                                uint256 startTimeOffsetSeconds, uint256 periodSeconds) external {
        bool isRevokable = true;  // Default value
        bool isMerge = true;      // Enable merging of schedules with same start time
        if (tokenAddressOrZeroForETH == address(0)) {
            addEthReleaseSchedule(recipient, amountPerPayment, numberOfPayments, startTimeOffsetSeconds, periodSeconds, isRevokable, isMerge);
        } else {
            addReleaseSchedule(tokenAddressOrZeroForETH, recipient, amountPerPayment, numberOfPayments, startTimeOffsetSeconds, periodSeconds, isRevokable, isMerge);
        }
    }

    // Define a struct for the asset-amount pair
    struct AssetAmount {
        address asset;
        uint256 amount;
    }

    // Function returning array of asset-amount pairs
    function getAllGlobalAmountsOwed() external view returns (AssetAmount[] memory assetAmounts) {
        uint256 count = globalAssetAddresses.length;
        assetAmounts = new AssetAmount[](count);
        for (uint256 i = 0; i < count; i++) {
            address asset = globalAssetAddresses[i];
            assetAmounts[i] = AssetAmount({
                asset: asset,
                amount: globalAmountOwed[asset]
            });
        }
        return assetAmounts;
    }

    // Removed getAmountOwed() - access globalAmountOwed mapping directly

    /// @notice Get the number of beneficiaries with schedules for a given asset
    /// @param asset The token address or address(0) for ETH
    /// @return count The number of beneficiaries with schedules for the asset
    function getBeneficiaryCount(address asset) external view returns (uint256 count) {
        if (asset == address(0)) {
            // For ETH, return number of beneficiaries with ETH schedules
            return ethScheduleBeneficiaries.length;
        } else {
            // For tokens, return number of beneficiaries with token schedules
            return tokenScheduleBeneficiaries[asset].length;
        }
    }

    // ===== 🆕 LINEAR VESTING FUNCTION =====
    
    /*
     * (plain comment — v43109: body lives in ExecutiveReleaseManagerSidecar; stub params unnamed)
     * @notice Create linear vesting schedule with optional cliff (REVOCABLE or LOCKED)
     * @param tokenAddressOrZeroForETH Token address or address(0) for ETH
     * @param beneficiary Address to receive vested tokens
     * @param totalAmount Total tokens/ETH to vest
     * @param cliffMonths Cliff period in months (0 = no cliff)
     * @param numUnlocks Number of equal unlock periods (e.g., 12 = monthly, 48 = monthly over 4 years)
     * @param vestingDays Total vesting period in days from NOW
     * @param isRevokable If true, unvested tokens can be revoked; if false, schedule is LOCKED
     * 
     * ⚠️ CRITICAL DIFFERENCE from TeamManager:
     * - ExecutiveReleaseManager HOLDS tokens and releases on schedule
     * - Revocation returns UNVESTED tokens to contract
     * - Beneficiary does NOT receive tokens until they vest
     * 
     * USE CASES:
     * - Revocable employee vesting (can revoke if employee leaves)
     * - Founder vesting with revocation rights
     * - Advisor grants with termination clauses
     * - Locked vesting (isRevokable=false) for guaranteed allocations
     * 
     * EXAMPLE 1: Standard 4-year monthly vest with 1-year cliff (REVOCABLE)
     *   cliffMonths = 12 (1 year cliff)
     *   numUnlocks = 48 (monthly unlocks)
     *   vestingDays = 1460 (4 years total)
     *   isRevokable = true
     *   → NO tokens released for first 12 months
     *   → After cliff: 1/48th releases every ~30 days
     *   → Can revoke unvested portion anytime
     * 
     * EXAMPLE 2: Quarterly unlock, no cliff (LOCKED - cannot revoke)
     *   cliffMonths = 0 (no cliff)
     *   numUnlocks = 4 (quarterly)
     *   vestingDays = 365 (1 year)
     *   isRevokable = false
     *   → 1/4th releases every ~91 days
     *   → CANNOT be revoked (guaranteed vesting)
     * 
     * @dev Creates multiple payment schedules with calculated intervals
     */
    // v43109 — BODY in ExecutiveReleaseManagerSidecar (TreasuryAdmin ∨ SC; cold). ABI unchanged.
    function linearVest(address, address, uint256, uint256, uint256, uint256, bool) external returns (bool) { _fwd(); }
    
    // Event for linear vesting creation
    event LinearVestingCreated(
        address indexed tokenAddressOrZeroForETH,
        address indexed beneficiary,
        uint256 totalAmount,
        uint256 finalUnlockTime
    );

}

// =====================================================================
//  ExecutiveReleaseManagerSidecar — cold-path bodies for ExecutiveReleaseManager (v43109)
// =====================================================================
//  Bytecode carrier for the rarely-called admin / TransferAgent functions of the
//  model above (same pattern as IssueTokenDMColdSidecar /
//  IssueTokenTimeLockSidecar). Deployed ONCE by ExecutiveReleaseManager's own
//  constructor; the model stores its address as an immutable. Stubs in the
//  model delegatecall here, so every body runs against the CLONE's storage with
//  the caller's msg.sender and emits from the clone address.
//
//  STORAGE: inherits the SAME bases in the SAME order (ExecutivePeerTreasury,
//  CloneInitializable) and then mirrors ExecutiveReleaseManager's own state
//  VERBATIM (order AND types) so every slot lines up. Never add state here
//  that is not also in the model, in the same position.
//
//  Direct calls are rejected (__SELF guard) — they would hit THIS contract's
//  own (empty) storage.
contract ExecutiveReleaseManagerSidecar is ExecutivePeerTreasury, CloneInitializable {
    using SafeERC20 for IERC20;

    uint256 private constant TWO_YEARS_SECONDS = 732 days;
    address constant ETH_ADDRESS = address(0);

    // errors mirrored from the model (declared inside the model, so not shared)
    error InvalidBeneficiary();
    error InvalidPayAmount();
    error InvalidStartTime();
    error InvalidPeriod();
    error InvalidCliff();
    error InsufficientBalance();
    error NumUnlocksZero();
    error UnlockIntervalTooSmall();
    error VestingTooShort();
    error Unauthorized();
    error DirectCallForbidden();

    /* ===== storage mirror (verbatim order/types of ExecutiveReleaseManager) ===== */
    mapping(address => uint256) public globalAmountOwed;
    address[] public globalAssetAddresses;
    uint256 public secondsPerPeriod;
    mapping(address => uint256) private forcedStartTimes;

    struct Schedule {
        uint256 singlePayAmount;
        uint256 numPayments;
        uint256 totalValue;
        uint256 totalLeftToPay;
        uint256 startTimestamp;
        uint256 lastClaimedTime;
        uint256 periodSeconds;
        uint256 totalPaidOut;
        bool isRevokable;
    }
    struct ForcedStartTimeData {
        address beneficiary;
        uint256 startTime;
    }

    mapping(address => mapping(address => Schedule[])) public schedules;
    mapping(address => address[]) public tokenScheduleBeneficiaries;
    mapping(address => Schedule[]) public ethSchedules;
    address[] public ethScheduleBeneficiaries;
    uint256 public defaultCliffSeconds;
    uint8 public transferFeeChargeMode;
    mapping(address => bool) public beneficiaryRestricted;
    /* ===== end storage mirror ===== */

    // events mirrored from the model (emitted from the clone under delegatecall)
    event PeriodChanged(uint256 oldSecondsPerPeriod, uint256 newSecondsPerPeriod);
    event DefaultCliffChanged(uint256 oldCliffSeconds, uint256 newCliffSeconds);
    event ForcedStartTimeAdded(address indexed beneficiary, uint256 startTime, bool isAbsolute);
    event ForcedStartTimeRemoved(address indexed beneficiary);
    event SchedulesRemoved(address indexed tokenContractAddress, address indexed beneficiary, uint256 amount, bool removedAll);
    event BeneficiaryRecoveryApplied(address indexed origAddress, address indexed newAddress, uint256 schedulesAffected, bool restricted, address indexed by);
    event LinearVestingCreated(address indexed tokenAddressOrZeroForETH, address indexed beneficiary, uint256 totalAmount, uint256 finalUnlockTime);

    address private immutable __SELF;

    constructor() ExecutivePeerTreasury(address(0), address(0), address(0), "") {
        __SELF = address(this);
        _disableInitializers();
    }

    modifier notDirect() {
        if (address(this) == __SELF) revert DirectCallForbidden();
        _;
    }

    function _onlyTokenAdmin() private view {
        if (!IController(peerTreasuryController).isOfficialEntity("TokenAdmin", msg.sender)) revert Unauthorized();
    }
    function _onlyTreasuryAdminOrContract() private view {
        if (!IController(peerTreasuryController).isOfficialDoubleEntityFast(KECCAK_TREASURY_ADMIN, msg.sender, KECCAK_SMART_CONTRACT, msg.sender, false)) revert Unauthorized();
    }

    /* ========== ADMIN SETTERS (bodies of the model's stubs) ========== */

    /// @notice 0 = never charge, 1 = once per NEW lifetime holder (default), 2 = every claim.
    function setTransferFeeChargeMode(uint8 mode) external notDirect {
        _onlyTreasuryAdminOrContract();
        if (mode > 2) revert(); // only 0/1/2 are valid modes
        transferFeeChargeMode = mode;
    }

    function addForcedStartTimes(ForcedStartTimeData[] calldata forcedStartDataList) external notDirect {
        _onlyTokenAdmin();
        for (uint256 i = 0; i < forcedStartDataList.length; i++) {
            address beneficiary = forcedStartDataList[i].beneficiary;
            uint256 startTime = forcedStartDataList[i].startTime;
            forcedStartTimes[beneficiary] = startTime;
            emit ForcedStartTimeAdded(beneficiary, startTime, startTime > TWO_YEARS_SECONDS);
        }
    }

    function removeForcedStartTimes(address[] calldata beneficiaries) external notDirect {
        _onlyTokenAdmin();
        for (uint256 i = 0; i < beneficiaries.length; i++) {
            address beneficiary = beneficiaries[i];
            if (forcedStartTimes[beneficiary] > 0) emit ForcedStartTimeRemoved(beneficiary);
            delete forcedStartTimes[beneficiary];
        }
    }

    function setDefaultCliffSeconds(uint256 newCliffSeconds) external notDirect {
        _onlyTokenAdmin();
        if (newCliffSeconds == 0) revert InvalidCliff();
        emit DefaultCliffChanged(defaultCliffSeconds, newCliffSeconds);
        defaultCliffSeconds = newCliffSeconds;
    }

    function changePeriod(uint256 newSecondsPerPeriod) external notDirect {
        _onlyTokenAdmin();
        if (newSecondsPerPeriod == 0) revert InvalidPeriod();
        emit PeriodChanged(secondsPerPeriod, newSecondsPerPeriod);
        secondsPerPeriod = newSecondsPerPeriod;
    }

    /* ========== v43109 TRANSFER AGENT: HOLDER-OF-RECORD RECOVERY ========== */

    /**
     * @notice TransferAgent ∨ SmartContract. Companion to DM.recoverHolder for vesting schedules.
     * @param origAddress       Beneficiary wallet being vacated.
     * @param newAddress        0 → CANCEL every schedule of origAddress on EVERY asset (tokens and
     *                          ETH), INCLUDING non-revokable ones (court order overrides the grant);
     *                          unpaid amounts return to the free treasury balance.
     *                          ≠0 → SWAP: every schedule of origAddress on every asset is moved
     *                          to newAddress (appended after any schedules it already has);
     *                          a forced start time, if any, moves with it.
     * @param revokeRestriction true → ONLY clear beneficiaryRestricted[origAddress] and return.
     */
    function permanentRestrictThenCancel(address origAddress, address newAddress, bool revokeRestriction) external notDirect {
        if (!IController(peerTreasuryController).isOfficialDoubleEntityFast(KECCAK_TRANSFER_AGENT, msg.sender, KECCAK_SMART_CONTRACT, msg.sender, false)) revert Unauthorized();
        if (origAddress == address(0) || origAddress == newAddress || beneficiaryRestricted[newAddress]) revert InvalidBeneficiary();

        if (revokeRestriction) {
            beneficiaryRestricted[origAddress] = false;
            emit BeneficiaryRecoveryApplied(origAddress, address(0), 0, false, msg.sender);
            return;
        }
        beneficiaryRestricted[origAddress] = true;

        uint256 affected;
        for (uint256 a = 0; a < globalAssetAddresses.length; a++) {
            address asset = globalAssetAddresses[a];
            Schedule[] storage src = asset == ETH_ADDRESS ? ethSchedules[origAddress] : schedules[asset][origAddress];
            uint256 n = src.length;
            if (n == 0) continue;

            if (newAddress == address(0)) {
                uint256 removedAmt;
                for (uint256 i = 0; i < n; i++) removedAmt += src[i].totalLeftToPay;
                globalAmountOwed[asset] -= removedAmt;
                emit SchedulesRemoved(asset, origAddress, removedAmt, true);
            } else {
                Schedule[] storage dst = asset == ETH_ADDRESS ? ethSchedules[newAddress] : schedules[asset][newAddress];
                if (dst.length == 0) {
                    if (asset == ETH_ADDRESS) ethScheduleBeneficiaries.push(newAddress);
                    else tokenScheduleBeneficiaries[asset].push(newAddress);
                }
                for (uint256 i = 0; i < n; i++) dst.push(src[i]);
            }
            if (asset == ETH_ADDRESS) delete ethSchedules[origAddress]; else delete schedules[asset][origAddress];
            _removeBeneficiaryIfEmpty(asset, origAddress);
            affected += n;
        }

        uint256 fst = forcedStartTimes[origAddress];
        if (fst != 0) {
            delete forcedStartTimes[origAddress];
            if (newAddress != address(0)) forcedStartTimes[newAddress] = fst;
        }

        emit BeneficiaryRecoveryApplied(origAddress, newAddress, affected, true, msg.sender);
    }

    /* ========== LINEAR VESTING (body of the model's stub) ========== */

    /// @notice Create linear vesting schedule with optional cliff (REVOCABLE or LOCKED).
    ///         See the full usage notes above the stub in ExecutiveReleaseManager.
    function linearVest(
        address tokenAddressOrZeroForETH,
        address beneficiary,
        uint256 totalAmount,
        uint256 cliffMonths,
        uint256 numUnlocks,
        uint256 vestingDays,
        bool isRevokable
    ) external notDirect returns (bool success) {
        _onlyTreasuryAdminOrContract();
        if (beneficiary == address(0)) revert InvalidBeneficiary();
        if (totalAmount == 0) revert InvalidPayAmount();
        if (numUnlocks == 0) revert NumUnlocksZero();
        if (vestingDays == 0) revert InvalidStartTime();

        uint256 cliffSeconds;
        uint256 vestingSeconds;
        unchecked {
            cliffSeconds = cliffMonths * 30 days;
            vestingSeconds = vestingDays * 1 days;
        }
        if (vestingSeconds <= cliffSeconds) revert VestingTooShort();

        uint256 amountPerUnlock;
        uint256 unlockInterval;
        unchecked {
            amountPerUnlock = totalAmount / numUnlocks;
            unlockInterval = vestingSeconds / numUnlocks;
        }
        if (amountPerUnlock == 0) revert InvalidPayAmount();
        if (unlockInterval == 0) revert UnlockIntervalTooSmall();

        if (tokenAddressOrZeroForETH == address(0)) {
            if (address(this).balance < totalAmount + globalAmountOwed[ETH_ADDRESS]) revert InsufficientBalance();
        } else {
            if (IERC20(tokenAddressOrZeroForETH).balanceOf(address(this)) < totalAmount + globalAmountOwed[tokenAddressOrZeroForETH]) revert InsufficientBalance();
        }

        Schedule[] storage beneficiarySchedules = tokenAddressOrZeroForETH == address(0)
            ? ethSchedules[beneficiary]
            : schedules[tokenAddressOrZeroForETH][beneficiary];

        if (beneficiarySchedules.length == 0) {
            if (tokenAddressOrZeroForETH == address(0)) ethScheduleBeneficiaries.push(beneficiary);
            else tokenScheduleBeneficiaries[tokenAddressOrZeroForETH].push(beneficiary);
        }

        // numUnlocks single-payment schedules, each releasing at cliff + unlockInterval × i
        uint256 remainder = totalAmount % numUnlocks;
        for (uint256 i = 1; i <= numUnlocks; i++) {
            uint256 amount = amountPerUnlock;
            if (i == numUnlocks) amount += remainder;
            beneficiarySchedules.push(Schedule({
                singlePayAmount: amount,
                numPayments: 1,
                totalValue: amount,
                totalLeftToPay: amount,
                startTimestamp: block.timestamp + cliffSeconds + (unlockInterval * i),
                lastClaimedTime: 0,
                periodSeconds: 0,
                totalPaidOut: 0,
                isRevokable: isRevokable
            }));
        }

        _addToGlobalAssets(tokenAddressOrZeroForETH);
        globalAmountOwed[tokenAddressOrZeroForETH] += totalAmount;

        emit LinearVestingCreated(tokenAddressOrZeroForETH, beneficiary, totalAmount, block.timestamp + cliffSeconds + vestingSeconds);
        return true;
    }

    /* ========== internal helpers duplicated from the model ========== */

    function _addToGlobalAssets(address tokenOrZero) private {
        if (globalAmountOwed[tokenOrZero] == 0) {
            for (uint256 i = 0; i < globalAssetAddresses.length; i++) {
                if (globalAssetAddresses[i] == tokenOrZero) return;
            }
            globalAssetAddresses.push(tokenOrZero);
        }
    }

    function _removeBeneficiaryIfEmpty(address tokenOrZero, address beneficiary) private {
        bool hasSchedules = tokenOrZero == address(0)
            ? ethSchedules[beneficiary].length > 0
            : schedules[tokenOrZero][beneficiary].length > 0;
        if (hasSchedules) return;
        if (tokenOrZero == address(0)) _removeAddressFromArray(ethScheduleBeneficiaries, beneficiary);
        else _removeAddressFromArray(tokenScheduleBeneficiaries[tokenOrZero], beneficiary);
    }

    function _removeAddressFromArray(address[] storage arr, address addr) private {
        for (uint256 i = 0; i < arr.length; i++) {
            if (arr[i] == addr) {
                arr[i] = arr[arr.length - 1];
                arr.pop();
                return;
            }
        }
    }
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@openzeppelin/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

contracts/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/IElasticTreasuryHub.sol

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

interface IElasticTreasuryHub {
   function executiveWithdrawETH(address personAddress, uint256 amt, string calldata note) external;
   function executiveWithdrawTokens(address personAddress, uint256 amt, address tokenSCAddress, string calldata note) external;
   function treasuryTransfer(address SCAddress, string calldata allCoinLabel, address tokenAddress, string calldata tokenLabel, uint256 amount) external returns (bool);
   function treasuryTransferETH(address payable SCAddress, string calldata allCoinLabel, string calldata ethLabel, uint256 amount) external returns (bool);
   function treasuryReceiveReclaimedETH() external payable returns (bool);
   function treasuryReceiveReclaimedTokens(address tokenAddress, uint256 amt) external returns (bool);
   function treasuryReclaimRequest(address SCAddress, address tokenAddress, uint256 amount) external returns (bool);
   function treasuryReclaimRequestETH(address payable SCAddress, uint256 amount) external returns (bool);
}

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": 5000,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.