Skip to content
Verified contractPartialUNLICENSED

IssueTokenSaleManager

Address0x93762d6ecbb0cc3d6f0141351c35756f01c853bc
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 700 runs
Via IR
yes
License
UNLICENSED
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,707,450
Creation transaction
0x1582e48226…9e751a7ece

contracts/IssueTokenSaleManager.sol

// SPDX-License-Identifier: UNLICENSED
// =====================================================================
//  EquityMint.org / DataCloud OS  —  Official Sovereign Issuance Suite
//  Module: IssueTokenSaleManager.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.
//
// Issue Token Sale Manager - Primary market sales manager for IssueToken with automatic FEE_TYPE_PURCHASE
// (type 3) and FEE_TYPE_SALESREG (type 2) fee collection via ContentManager
// (type 2) fee distribution. Supports ETH, USDC, and USDT payments with Chainlink price feeds for accurate
// USD-denominated pricing. Integrates with FeeManager for hierarchical fee distribution and triggers
// ProjectRevenueTreasury buyback coordination after each purchase.
//
// Chief Architect and CEO: Ken Silverman, US Fintech LLC
// Designed by Ken Silverman as part of the EquityMint sales 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 "./ExecutivePeerTreasury.sol";
import "./CloneInitializable.sol";
import "../interfaces/IFeeManager.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/* ========== INTERFACES ========== */
interface ITokenDecimals {
    function decimals() external view returns (uint8);
    function symbol() external view returns (string memory);
    function transfer(address recipient, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}

interface IIssueToken {
    struct WhitelistEntry {
        address user;
        string note;
        bool isUS;
    }

    function transfer(address recipient, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
    function getUserRegistrationStatus(address user, bool notGatedOverride) external view returns (uint8);
    function isActivated() external view returns (bool);
    function timeLockManager() external view returns (address);
    function contentManager() external view returns (address);
    function stableCoinAddress() external view returns (address);
    function whitelistUserWithRegKey(address user, bool isUS, bytes calldata registrarSignedMessage, string calldata registrationNote, uint64 expiry) external returns (address);
    function addWhitelistedUsers(WhitelistEntry[] calldata entries) external;
    // Maximum decimal precision (0–18) the IssueToken enforces on _every_ transfer.
    // SaleManager reads this to keep buyer-net and fee transfers aligned to the
    // same grid (step = 10^(18 - MAX_DECIMALS)) so IssueToken.transfer() can't
    // revert with AmountExceedsMaxDecimalPrecision.
    function MAX_DECIMALS() external view returns (uint256);
}

interface IIssueTokenTimeLock {
    function addTimeLockedAllocation(address user, uint256 amount) external;
    // function addTimeLockCustom(address user, uint256 amount, uint256 unlockTime) external;  // Not used - SalesManager always uses default lock settings
}

interface AggregatorV3Interface {
    function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
    // v43105: needed by setFiat() and addPaymentToken() to cache feed precision once
    // (vs. reading per-buy). Chainlink mainnet X/USD feeds are uniformly 8-dec but the
    // interface exposes this for future-proofing against feeds with different scales.
    function decimals() external view returns (uint8);
}

interface IIssueTokenContentManager {
    function buildCertificationMessage(address user, address tokenAddress, uint256 timestamp, bytes32 subscriptionHash, string calldata chainName, bytes32 referredByEmailHash, bytes32 testamentHash) external view returns (string memory);
    function subscriptionAgreementHash() external view returns (bytes32);
    function confirmHash(bytes32 hash) external view returns (uint256 firstIndex, uint256 firstTimestamp);
    function isUserRegistered(address user, address tokenAddress) external view returns (bool);
    function registerUser(address user, address tokenAddress, bytes calldata signature, uint256 timestamp, bool requireEmailMode, bytes calldata platformRegistrarQuestionnaireAndEmailVerifierSignature, bytes32 referredByEmailHash, bytes32 testamentHash) external;
    function getAllEmails(bool activeOnly) external view returns (string[] memory);
    function getRegistrationProof(address user, address tokenAddress) external view returns (
        string memory message,
        bytes memory signature,
        bool signatureValid,
        bool tokenBindingValid,
        bool subscriptionHashValid
    );
}

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

/* ========== CUSTOM ERRORS (Gas Optimization) ========== */
error SymbolMismatch();
error PriceZero();
error PriceFeedNotFresh();
error StablecoinChangeRequiresFeedUpdate();
error NotTreasuryAdmin();
error LenMismatch();
error EmptyArr();
error Trigger0();
error PriceInvalid();
error TriggerOrder();
error SaleInactive();
error TokenInactive();
error NotReg();
error RegReq();
error ThresholdTooLow();
error UnderMin();
error OverMax();
error MaxBuyers();
error XferFail();
error StalePrice();
error PriceOld();
error InvalidRecip();
error AmtZero();
error OfferInactive();
error SelfRegOff();
error NoActiveProjectEmail();
error FeeTransferFail();
// v43105: UnsupportedPaymentToken removed (replaced by PaymentTokenNotRegistered).
error TokenNotRegistered();
error FeeManagerZero();
// v43105: NotPlatformRegistrar, PlatformWhitelistNotPermitted, PlatformWhitelistRequired
// removed — platform no longer signs Sig A (whitelist).
error NoRegistrarSignature();  // Sig B required (bit 4 OR bit 6 ON) but missing
error StablecoinNot6Dec();  // stableCoinAddress must be 6-decimal token (USDC/USDT/EUROC)
error NotRegistrar();  // Reuse: wrong registrar type for required whitelist signature
error ThirdPartyWhitelistNotPermitted();
// v43206 — third-party-registrar bridge (PSTPR) IS now an on-chain enforcement
// gate as well as a server/modal switch. `thirdPartyBridgeProviderId` (the
// PSTPR storage byte; see ADMIN FUNCTIONS section) is read directly in
// `selfRegisterForSales` and, when non-zero, REQUIRES a Sig A to be present
// — without one, the dispatch reverts with `ThirdPartyBridgeSigRequired`.
// This replaces the previous off-chain hold in CryptoRegistrar.php STEP 6.65b
// with a chain-authoritative gate. The court-proof binding of the provider
// attestation still lives in the `registrationNote` string, which
// IssueToken.whitelistUserWithRegKey commits to via
// `keccak256(bytes(registrationNote))` inside its rawMessage; with v43206's
// `whitelistedUsers[user]` expiry-prefix storage convention, the full audit
// reconstruction is achievable from chain state alone.
error ThirdPartyBridgeSigRequired();
error PlatformDomainEmailSigNotPermitted();
error ReferrerRequired();
error ReferrerNotActive();
error ReferralCapReached();
error ZeroHash();
error ReferrerAlreadyActive();
error ReferrerAlreadyInactive();
// v43105 — payment-token allowlist + fiat switching.
error PaymentTokenAlreadyRegistered();
error PaymentTokenNotRegistered();
// (former) InvalidFeed: dropped — all three feed-config sites now route through
// _getValidatedPrice which throws PriceInvalid / StalePrice / PriceOld instead.
error FiatSymbolEmpty();      // setFiat() received an empty symbol

/**
 * @title IssueTokenSaleManager
 * @dev Handles IssueToken sales with automatic fee distribution
 * @author Ken Silverman
 */
// PROXY BUILD: EIP-1167 clone variant — deployed once per chain as an inert MODEL;
// projects receive a clone configured via initialize().
contract IssueTokenSaleManager is ExecutivePeerTreasury, CloneInitializable {
    using SafeERC20 for IERC20;

    /* ========== CONSTANTS ========== */
    /// @notice On-chain version marker.
    /// @dev v43105 architecture (vs v43102/v43103 — those are the only "in the wild"
    ///      pre-v43105 deployments. v43104 was never deployed.) Note that pre-v43105
    ///      had NO fiatSymbol() / setFiat() / usdToFiatFeed() / paymentTokenInfo()
    ///      selectors at all — pricing was hardcoded USD with no symbol storage —
    ///      so client UIs MUST treat "selector missing → revert → default 'USD'"
    ///      as the only backward-compat path. There is no string-returning
    ///      ancestor of fiatSymbol().
    ///
    ///      1. PRICE IS FIAT-DENOMINATED IN STORAGE; CONSTRUCTOR ARG IS USD.
    ///         The deployer specifies the initial price in USD (via the
    ///         `_purchasePriceInUSD` constructor argument and the
    ///         ControllerFactory's `SaleManagerParams.purchasePriceInUSD` field).
    ///         The contract immediately assigns that value to internal storage
    ///         named `purchasePriceInFIAT`, because at runtime the same number
    ///         is interpreted in whatever fiat is currently active.
    ///         At deployment, fiat defaults to USD (fiatSymbol="USD",
    ///         usdToFiatFeed=address(0)), so "USD at deploy" is honest.
    ///         Token-admin can later switch fiat via setFiat("EUR", eurUsdFeed),
    ///         from which point the SAME stored number is interpreted as EUR.
    ///         Token-admin can also call setPurchasePriceInFIAT(newAmount) at any
    ///         time to re-quote in the active fiat.
    ///      2. NO BAKED-IN USDC. The constructor no longer accepts `_usdcAddress`.
    ///         USDC (or any other ERC20) is opt-in via addPaymentToken(token, feed)
    ///         post-deployment. saleStable + USDT + ETH remain the three baked-in
    ///         payment paths because their oracles are required at construction time
    ///         anyway.
    ///      3. ADDRESS-BASED BUY INTERFACE. buyWithStableCoinPermit now takes the
    ///         payment-token address directly. The old `(amount, uint8 mode, ...)`
    ///         interface is gone — it never made it into a deployed v43104, and
    ///         the address form composes cleanly with the allowlist.
    ///      4. FIXED LATENT FEE BUG (carried over from v43103). The old
    ///         `_convertStablecoinToPaymentToken` fed FeeManager USD-6 amounts but
    ///         then ran Step-1 through the saleStable/USD oracle, silently
    ///         mis-pricing fees on non-USD-pegged saleStables (EUROC over-paid by
    ///         ~18%, XSGD under-paid by ~26%). Replaced by `_convertFiatToPaymentToken`
    ///         which composes fiat-6 → fiat-18 → USD-18 → payment-token cleanly,
    ///         using each token's OWN USD oracle (not the saleStable's).
    uint16 public constant CONTRACT_VERSION = 43107;
    uint256 private constant MAXIMUM_ACCEPTABLE_DELAY = 30 minutes;

    // NOTE: issueTokenAddress and feeManager inherited from ExecutivePeerTreasury as public immutable

    /// @notice Pre-computed MAX_DECIMALS grid step = 10^(18 - IssueToken.MAX_DECIMALS()),
    ///         clamped to 1 when MAX_DECIMALS == 18. Read once from the IssueToken in our
    ///         constructor and baked in as `immutable` so the runtime path in
    ///         `_completePurchase` is a single PUSH instead of an external call + EXP.
    /// @dev Moving the lookup to constructor-time keeps it OUT of the EIP-170 runtime-
    ///      size budget; it costs nothing toward the 24,576-byte cap. All buyer/fee
    ///      rounding inside `_completePurchase` aligns to this step:
    ///        • buyer's tokenAmount → floor to step (round DOWN, silent)
    ///        • each fee18         → ceil  to step (round UP,   protects fee recipients)
    ///        • buyerNet = tokenAmount − Σ fee18  (aligned − aligned = aligned)
    // PROXY BUILD: was `immutable` (constructor-time cache) — now storage, set once in
    // initialize(). The runtime read is an SLOAD instead of a PUSH, but the external
    // call + EXP elimination described above still holds.
    uint256 private _MAX_DEC_STEP;

    /// @dev PROXY BUILD: this model's initializer sidecar (holds the former
    ///      constructor body — see IssueTokenSaleManagerInitializer at the end
    ///      of this file). Deployed by the model's own constructor; immutable =
    ///      lives in the model RUNTIME (shared by every clone), NO storage slot.
    address private immutable INIT_SIDECAR;

    // Contract state variables
    // v43105: USDC is no longer baked in. Projects that want to accept USDC
    // (or any other ERC20) call addPaymentToken(token, priceFeed) post-deploy.
    // USDT and the project's saleStable remain hardcoded payment paths because
    // their oracles are required by the constructor anyway.
    // PROXY BUILD: was `immutable` — now storage, set once in initialize().
    address public usdtAddress;

    /// @notice ETH / USD oracle (8-dec). ETH is the only payment path NOT in
    ///         paymentTokenInfo (which is keyed by ERC20 address; ETH would
    ///         collide with address(0) so we keep it as a dedicated slot).
    AggregatorV3Interface public ethUsdPriceFeed;
    /// @dev v43105 unification: usdtUsdPriceFeed and stablecoinUsdPriceFeed
    ///      storage variables removed. Both are now read from
    ///      paymentTokenInfo[usdtAddress].feed and
    ///      paymentTokenInfo[stableCoinAddress].feed respectively.

    // ============================================================
    // v43105: switchable FIAT denomination.
    // The contract's price (`purchasePriceInFIAT`) and FeeManager basis are
    // ALWAYS expressed in the currently-selected fiat. Default is USD.
    // To switch fiat (e.g. to EUR), token-admin calls setFiat("EUR", eurUsdFeed).
    // The bridge oracle is "USD / fiat"; we read it via _getValidatedPrice() and
    // INVERT it (1 / price) so the math stays composable. When fiat == USD,
    // usdToFiatFeed == address(0) and the inversion step is skipped.
    // ============================================================
    /// @notice Display symbol for the active fiat (e.g. "USD", "EUR", "GBP", "JPY").
    /// @dev v43105 bytecode-saver: stored as bytes8 instead of `string`. The
    ///      auto-generated getter for `string public` is ~100 bytes vs ~20 for
    ///      `bytes8 public`. UI decodes bytes8 → ASCII (right-padded with 0x00).
    ///      Anything longer than 8 ASCII chars is rejected by setFiat().
    bytes8 public fiatSymbol;
    AggregatorV3Interface public usdToFiatFeed; // address(0) ⇒ fiat IS USD

    // ============================================================
    // v43105: unified payment-token allowlist.
    // Every accepted ERC20 (saleStable, USDT, and any admin-added tokens)
    // lives in this single mapping. ETH is NOT in the mapping (it is keyed
    // off address(0) and uses ethUsdPriceFeed directly). Caching tokenDecimals
    // and feedDecimals skips two runtime calls per buy. `usePermit` lets us
    // skip the EIP-2612 permit() call for tokens that don't implement it
    // (notably mainnet USDT).
    //
    // The 4-field layout fits in ONE storage slot:
    //   address (20) + uint8 (1) + uint8 (1) + bool (1) = 23 bytes.
    //
    // v43105 (bytecode-trim): the previous `bool registered` flag was dropped.
    // `feed != address(0)` is now the registered sentinel — a registered
    // token always has a feed, and `removePaymentToken` zeros the entry. We
    // cannot distinguish "deregistered" from "never registered" on-chain
    // anymore, but indexers still see PaymentTokenAdded / PaymentTokenRemoved
    // events for the full history.
    // ============================================================
    struct PaymentTokenInfo {
        AggregatorV3Interface feed;        // token / USD oracle (== address(0) ⇒ NOT registered)
        uint8  feedDecimals;               // typically 8 for Chainlink USD feeds
        uint8  tokenDecimals;              // ERC20 native decimals
        bool   usePermit;                  // false ⇒ caller must approve() first (e.g. USDT)
    }
    mapping(address => PaymentTokenInfo) public paymentTokenInfo;
    address[] public registeredPaymentTokens; // for enumeration / UI listing — INCLUDES saleStable + USDT

    /**
     * ============================================================================
     *  4-BYTE PROJECT POLICY FLAGS (uint32 bitmask)
     * ============================================================================
     *
     * we dont need one manager for many tokens.   uint24 was intended to allow for a set of up to 24 ones and zeroes to be netered into to act as a bit mask
     *
     * BYTE 1 — Access / Offering Posture
     * Bit	Meaning
     * 0	Private offering only – public solicitation not allowed
     * 1	Referral email required to begin registration
     * 2	Referral expansion allowed (investors may become referrers)
     * 3	Registrar Whitelist Required (if off, gating must also be off).  This automtically allows manual Registration.  *whitelists with no-sig)
     * 4	Questionnaire Required (full registrant questionnaire flow + platform Sig B attestation; OFF = click-through-agree only, testamentHash = keccak256("")).
     * 5	Third-Party Registrar Permitted. (Whitelists via Sig A)
     * 6	Platform acts as Questionnaire AND Email Verifier (Sig B mode 1: questionnaire + email round-trip).
     * 7	U.S. persons allowed
     *
     * Operational rule for UI:
     *
     * If bit0 = 1, the platform never displays the full token address.
     * Investor must paste the token address obtained from a referrer.    RULE 2:  Even if no Registrar is checked and gating is turned off (permitting a sale)  NO sale may proceed if user doe not SELF-CERT.  SELF-CERT if ALWAYS rewuired even if no SIGNATURE is reuired nor any manaul registration.
     *
     * BYTE 2 — Verification / Evidence Requirements
     * Bit	Meaning
     * 0	Exclude sanctioned / restricted jurisdictions
     * 1	U.S. investors must be accredited
     * 2	Non-U.S. investors must be accredited
     * 3	Registrar KYC / AML verification required
     * 4	Registrar accreditation verification required
     * 5	Registrar  jurisdiction / residency verification required
     * 6	Non-US persons allowed
     * 7	show Token Locked for Set Time Disclaimer for rule 144
     *
     * Notes:
     *
     * Platform Registrar (Sig B): represents the platform's questionnaire-validation
     * attestation (mode 0) and, when bit 6 is also ON, the platform's email round-trip
     * verification (mode 1). Possession of that signature, when emailed to the user,
     * also proves the user controls the email address. The platform NEVER signs Sig A
     * (whitelist signature); the only whitelist signature path is third-party (bit 5).
     *
     * So email verification (when bit 6 is ON) is cryptographically embedded in the
     * platform Sig B that ContentManager consumes during self-cert.
     *
     * BYTE 3 — Project Declared Classification
     * Bit	Meaning
     * 0	Project purports to rely on Rule 506(b)
     * 1	Project purports to rely on Rule 506(c)
     * 2	Project purports to rely on Regulation S
     * 3	Project purports to rely on Regulation A
     * 4	Registered public security
     * 5	Non-security product / service / donation / license / membership (NOT a security)
     * 6	Auto-Whitelist on Questionnaire-Valid Self-Cert (SaleManager-as-SmartContract calls IssueToken.addWhitelistedUsers directly; requires bit 4 OR bit 6 of BYTE 1).
     * 7	Crowdfunding (Reg CF style participation)
     *
     * NOTE: ContentManager does NOT need these flags for court evidence; they are primarily for UI + SaleManager gating decisions.
     * ============================================================================
     */
    uint32 public projectFlags;

    // Byte 1 bits (0..7)
    uint8 private constant PF_PRIVATE_OFFERING_ONLY = 0;
    uint8 private constant PF_REFERRAL_EMAIL_REQUIRED = 1;
    uint8 private constant PF_REFERRAL_EXPANSION_ALLOWED = 2;
    uint8 private constant PF_REGISTRAR_WHITELIST_REQUIRED = 3;
    // PF_QUESTIONNAIRE_REQUIRED (bit 4): ON → selfRegisterForSales requires a
    // non-empty platform Sig B (questionnaire attestation). OFF → Sig B must
    // be empty and testamentHash must equal keccak256("") (click-through-agree
    // sentinel). (bit 4 OR bit 6) is the gating predicate. See flags.js.
    uint8 private constant PF_QUESTIONNAIRE_REQUIRED = 4;
    uint8 private constant PF_THIRD_PARTY_REGISTRAR_PERMITTED = 5;
    uint8 private constant PF_PLATFORM_QUESTIONNAIRE_EMAIL_VERIFIER = 6;
    uint8 private constant PF_US_PERSONS_ALLOWED = 7;

    // Byte 2 bits (8..15)
    uint8 private constant PF_EXCLUDE_SANCTIONED_JURISDICTIONS = 8;
    uint8 private constant PF_US_MUST_BE_ACCREDITED = 9;
    uint8 private constant PF_NONUS_MUST_BE_ACCREDITED = 10;
    uint8 private constant PF_REGISTRAR_KYC_AML_REQUIRED = 11;
    uint8 private constant PF_REGISTRAR_ACCREDITATION_REQUIRED = 12;
    uint8 private constant PF_REGISTRAR_JURISDICTION_REQUIRED = 13;
    uint8 private constant PF_NONUS_PERSONS_ALLOWED = 14;
    uint8 private constant PF_SHOW_RULE144_LOCK_DISCLAIMER = 15;

    // Byte 3 bits (16..23)
    uint8 private constant PF_RULE_506B = 16;
    uint8 private constant PF_RULE_506C = 17;
    uint8 private constant PF_REG_S = 18;
    uint8 private constant PF_REG_A = 19;
    uint8 private constant PF_REGISTERED_PUBLIC_SECURITY = 20;
    uint8 private constant PF_NON_SECURITY = 21; // product/service/donation/license/membership (non-security)
    // PF_AUTO_WHITELIST_ON_QUESTIONNAIRE_VALID (bit 22): when ON and (bit 4 OR
    // bit 6) is also ON, selfRegisterForSales calls IIssueToken.addWhitelistedUsers
    // directly after Sig B verifies. SaleManager is the project's KECCAK_SMART_CONTRACT
    // entity, and addWhitelistedUsers accepts (SmartContract OR Registrar) callers.
    uint8 private constant PF_AUTO_WHITELIST_ON_QUESTIONNAIRE_VALID = 22;
    uint8 private constant PF_CROWDFUNDING_REG_CF = 23;

    // Byte 4 bits (24..31)
    // Manual sales approval required (for e.g. green-stamp benefits programs):
    // - Self-cert (ContentManager) remains mandatory.
    // - Token whitelist is NOT required for purchase eligibility (unless PF_REGISTRAR_WHITELIST_REQUIRED is also enabled).
    // - Approval is stored ONLY in SaleManager (does not whitelist user in the IssueToken).
    uint8 private constant PF_MANUAL_SALES_APPROVAL_REQUIRED = 24;
    // Bits 25..31 below are documented for visibility but are NOT consumed
    // inside IssueTokenSaleManager itself — they are purely informational
    // policy flags interpreted off-chain by CryptoRegistrar.php and the
    // CryptoRegistrarQuestionnaireValidator. Including them as named
    // constants here is intentional: it lets the contract-level allow-list
    // for projectFlags reject any bit positions outside [0..31] semantics
    // (currently enforced by the uint32 width) AND keeps the canonical
    // bit-number ↔ name mapping in one auditable place.
    //
    // bit 25 — PF_DOCS_REQUIRED_IN_SELFCERT (off-chain): registrant must
    //           upload a single supporting PDF (ID / accreditation proof /
    //           jurisdiction doc) at self-cert time.
    // bit 26 — PF_ALLOW_BUCKET_SELFCERT_DOCS (off-chain): when paired with
    //           bit 25, route the registrant's PDF upload through the
    //           platform GCS bucket (durable signed-URL access link)
    //           instead of the legacy base64-in-email attachment. Has no
    //           effect when bit 25 is OFF (nothing to upload).
    // bit 27 — PF_OVER_18_REQUIRED (off-chain; reserved).
    // bit 28 — PF_OVER_21_REQUIRED (off-chain; reserved).
    // bit 29 — PF_POLITICAL_DONATION (off-chain; reserved).
    // bit 30 — PF_STORE_QUESTIONNAIRE_ON_PLATFORM (off-chain): CR.php writes
    //           the full registrant questionnaire (JSON1 + JSON2) into the
    //           platform `global.offChainData` table with ~60-day auto-prune
    //           retention. Used in tandem with bit 6 OFF when projects want
    //           queryable/sortable/exportable registrant data without running
    //           their own audit-CC inbox. Admin reads/exports via the
    //           "Registrants Admin" menu in tokensale.html (backed by
    //           TokenSaleModalRegistrantsAdmin.php + CryptoRegistrarGlobalWriter).
    //           Projects under strict no-third-party-data-stewardship regimes
    //           leave this OFF; CR.php then skips the platform write.
    // bit 31 — PF_STORE_QUESTIONNAIRE_AT_PROJECT_ENDPOINT (off-chain): when
    //           ON, CR.php additionally mirrors the questionnaire to the URL
    //           stored at
    //             global.offChainProjectData.JSON1.projectQuestionnaireEndpoint
    //           (keyed on tokenAddress). Project admin configures the URL via
    //           the "Registrants Admin" menu. Delivery is best-effort: webhook
    //           failures log a warning but do NOT fail the user's registration.
    //           Independent of bit 30 — a project may mirror to its own
    //           endpoint without retaining a platform-side copy.
    //
    // Referrer-required policy (private-sale hash gating):
    //   The private-sale code hash is gated by (bit 1 OR bit 16). Bit 1
    //   (PF_REFERRAL_EMAIL_REQUIRED) and bit 16 (PF_RULE_506B) each on its
    //   own forces the 3-element hash (referrerEmail + investorEmail + code).
    //   506(b) prohibits general solicitation and therefore intrinsically
    //   requires a referral relationship — admins do NOT need to flip bit 1
    //   separately when bit 16 is set. There is no longer a separate
    //   "referrer required for hash" bit; the legacy 2-element preimage
    //   (no referrer) has been retired.

    event ProjectFlagsChanged(uint32 newFlags);

    function _hasFlag(uint8 bitPos) internal view returns (bool) {
        return (projectFlags & (uint32(1) << bitPos)) != 0;
    }

    /// @dev Bytecode-saver: 14 admin functions previously inlined this check
    ///      (~50–80 bytes per site). Centralizing it folds them all to a single
    ///      JUMP. Reverts with NotTokenAdmin() if msg.sender is not registered
    ///      as KECCAK_TOKEN_ADMIN in the project's Controller.
    function _requireTokenAdmin() internal view {
        if (!IController(peerTreasuryController).isOfficialEntityFast(KECCAK_TOKEN_ADMIN, msg.sender)) revert NotTokenAdmin();
    }

    /// @dev Bytecode-saver: callers needing "TokenAdmin OR Official SmartContract
    ///      on this project's Controller" route through here instead of inlining
    ///      the OR-check (~180 bytes per inlined site → one JUMP).  Uses
    ///      isOfficialDoubleEntityFast (single STATICCALL, isAnd=false) which is
    ///      itself the gas-optimized form vs two separate isOfficialEntityFast
    ///      calls (~2.3k runtime gas saved per invocation in addition to the
    ///      bytecode savings).  Reverts NotTokenAdmin() if neither role holds.
    ///
    ///      Used by the v43105+ widened-gate admin functions (setReferrerEmailHash,
    ///      setManualSaleApproval) where project-side SmartContract helpers
    ///      (e.g. BatchTransferAndExtrasManager) must be able to invoke admin
    ///      actions on behalf of TokenAdmin batches.  The SmartContract caller
    ///      is responsible for its OWN role/bit gate before invoking us.
    function _requireTokenAdminOrSmartContract() internal view {
        if (!IController(peerTreasuryController).isOfficialDoubleEntityFast(
            KECCAK_TOKEN_ADMIN,    msg.sender,
            KECCAK_SMART_CONTRACT, msg.sender,
            false
        )) revert NotTokenAdmin();
    }

    /// @dev Bytecode-saver: 6 callsites (3 buy-paths in buyWithETH/buyWithStableCoinPermit
    ///      and 3 fee-payout conversions in _convertStablecoinToPaymentToken) used to
    ///      inline this 4-step Chainlink validation. Returns the validated price as
    ///      uint256 (8 decimals for all three feeds: ETH/USD, USDT/USD, stablecoin/USD).
    ///
    ///      A8 (open): on L2s (Arbitrum / Optimism / Base) Chainlink also publishes
    ///      a Sequencer-Uptime feed. For an L2-aware version, also require
    ///      `(uptime.answer == 0) && (block.timestamp - uptime.startedAt > GRACE)`
    ///      before trusting the price. Skipped here because deploy chain isn't
    ///      pinned at compile time and the uptime-feed address varies per chain;
    ///      worth wiring once chain residency is fixed (~80–120 bytes per chain).
    function _getValidatedPrice(AggregatorV3Interface feed) internal view returns (uint256) {
        (uint80 roundId, int256 p, , uint256 updatedAt, uint80 answeredInRound) = feed.latestRoundData();
        if (p <= 0) revert PriceInvalid();
        if (answeredInRound < roundId) revert StalePrice();
        if (block.timestamp - updatedAt >= MAXIMUM_ACCEPTABLE_DELAY) revert PriceOld();
        return uint256(p);
    }

    /// @dev v43105: convert a USD-18 amount to fiat-18.
    ///      When fiat == USD (usdToFiatFeed == address(0)): identity.
    ///      Otherwise we read a "fiat/USD" feed (e.g. EUR/USD ≈ 1.08e8 means
    ///      1 EUR = $1.08) and invert: fiatAmount = usdAmount / (fiat/USD).
    ///
    ///      Formula: fiatAmount18 = usdAmount18 * 10^feedDecimals / fiatUsdPrice.
    ///      Chainlink fiat/USD feeds use 8 decimals on mainnet; we cache
    ///      whatever feed.decimals() returned at setFiat() time, so atypical
    ///      feeds still compose correctly.
    function _usdToFiat(uint256 usdAmount18) internal view returns (uint256) {
        if (address(usdToFiatFeed) == address(0)) return usdAmount18;
        return (usdAmount18 * (10 ** _usdToFiatFeedDecimals)) / _getValidatedPrice(usdToFiatFeed);
    }

    /// @dev Inverse of _usdToFiat. Used by the fee-payout path.
    function _fiatToUsd(uint256 fiatAmount18) internal view returns (uint256) {
        if (address(usdToFiatFeed) == address(0)) return fiatAmount18;
        return (fiatAmount18 * _getValidatedPrice(usdToFiatFeed)) / (10 ** _usdToFiatFeedDecimals);
    }

    /// @dev Cached at setFiat() time so we don't call feed.decimals() per buy.
    ///      Only meaningful when usdToFiatFeed != address(0).
    uint8 internal _usdToFiatFeedDecimals;

    // Packed storage slot: bools + uint8 = 1 slot
    bool public saleActive;
    // v43105 unification: usdtDecimals removed — now in paymentTokenInfo[usdtAddress].tokenDecimals.

    uint256 public startSaleBlockNum = 0;
    /// @notice Base purchase price per token (18 decimals), in the contract's
    ///         currently-selected fiat.
    /// @dev    Constructor argument is named `_purchasePriceInUSD` because the
    ///         deployer literally specifies USD at deploy time (the contract
    ///         boots with fiatSymbol="USD"). The constructor body assigns the
    ///         USD param to this FIAT-named storage slot — the rename is purely
    ///         semantic and reflects what the slot actually holds at runtime.
    ///         If token-admin later runs setFiat("EUR", eurUsdFeed), THIS NUMBER
    ///         IS NOT REWRITTEN — it is now interpreted as EUR. Re-quote with
    ///         setPurchasePriceInFIAT(newEurAmount) to make that explicit.
    uint256 public purchasePriceInFIAT;
    uint256 public totalTokensSold;
    uint256 public totalPurchaserCount;  // Count of unique purchasers (for holder fee optimization)
    // REPLACED: minDollarValue removed to stay within bytecode limit.
    // uint256 public minDollarValue = 300e18;
    uint256 public minTokensPerPurchase;   // 0 = no minimum per single purchase (in 18-dec token units)
    uint256 public maxTokensPerPurchase;   // 0 = no maximum cumulative per address (in 18-dec token units)
    uint256 public maxPurchasers;          // 0 = unlimited unique purchasers

    /// @notice Staggered pricing tier.
    /// @dev `priceInFIAT` is in the contract's currently-selected fiat (default USD).
    ///      Same semantic note as `purchasePriceInFIAT` above.
    struct PriceTier {
        uint256 priceInFIAT;        // Price per token in fiat (18 decimals)
        uint256 amountSoldTrigger;  // Total tokens sold at which this price activates (0 = from beginning)
    }

    /// @notice Array of price tiers (sorted by amountSoldTrigger ascending).
    ///         External readers use getPriceTiers() (returns whole array).
    PriceTier[] private priceTiers;

    // Mappings
    mapping(address => uint256) public tokensSoldByPaymentToken;
    mapping(address => uint256) public userPurchases;  // Track purchases by user

    // Optional manual sales-approval list (independent from IssueToken whitelist).
    mapping(address => bool) private _salesApproved;

    // Optional referral allowlist (hash-based; hash typically of email + code/key combos).
    // We keep minimal audit history as two monotonic timestamp trails.
    // Active if lastActiveTimestamp > lastInactiveTimestamp (latest action wins).
    mapping(bytes32 => uint256[]) private referrerEmailCombosPlusCodeOrKeyHashActiveTimes;
    mapping(bytes32 => uint256[]) private referrerEmailCombosPlusCodeOrKeyHashInactiveTimes;

    // Per-hash referral usage counter (key = referrerEmailCombosPlusCodeOrKeyHash).
    // Atomically incremented by selfRegisterForSales() when bit-1 (PF_REFERRAL_EMAIL_REQUIRED)
    // is set; capped by maxReferralUseCount (see ReferralCapReached revert). Pre-flight
    // reads of this mapping (public auto-getter) are used by CryptoRegistrar.php to fail
    // fast before the user wastes gas on a doomed tx.
    mapping(bytes32 => uint256) public referralUseCount;

    // Default cap on per-hash referral uses (default 10). Settable by token admin.
    // Sized for the typical gate hit-count of one full file download per investor
    // plus headroom for re-downloads / form retries before the same access code
    // is treated as exhausted. Witness Range-GETs do NOT count toward this cap —
    // they are read-only checks against the doc URL, not registrations.
    /// @dev v43106 (bytecode-trim): made `public` (auto-getter) and renamed from
    ///      `_maxReferralUseCount` so the manual `getMaxReferralUseCount()` view
    ///      function could be deleted (~40–60 bytes off the EIP-170 budget).
    ///      External ABI now exposes `maxReferralUseCount()` instead.
    // PROXY BUILD: `= 10` default moved to initialize() (inline initializers never run for clones).
    uint256 public maxReferralUseCount;

    /* ========== EVENTS ========== */
    // v43105 bytecode-trim: `totalFees` field dropped from TokenSold. It was the
    // stablecoin-denominated purchase-fee total returned by _distributeFees(),
    // not the token-denominated TokenPurchase fee. Off-chain indexers can
    // reconstruct it from FeeManager's own per-recipient distribution events
    // (FeeManager emits one per fee transfer), so we don't lose any auditable
    // information by dropping it here. Removing the field also lets
    // _distributeFees() return void, which removes the per-iteration
    // accumulation + named-return slot from its body.
    event TokenSold(address indexed buyer, address indexed paymentToken, uint256 paymentAmount, uint256 tokenAmount);
    // event FeeDistributed(address indexed recipient, address indexed paymentToken, uint256 amount, bool isPct); // REMOVED: wasteful gas/bytecode
    event SaleStatusChanged(address indexed caller, bool newStatus);
    event StartSaleBlockNumChanged(uint256 newStartSaleBlockNum);
    event PurchasePriceChanged(uint256 newPrice);
    // event MinDollarValueChanged(uint256 newMinDollarValue); // REPLACED by token-based min/max
    event MinMaxTokensPerPurchaseChanged(uint256 minTokens, uint256 maxTokens);
    event MaxPurchasersChanged(uint256 maxPurchasers);
    event StaggeredPriceSet(uint256 tierCount);
    // v43105 — payment-token allowlist + fiat switching.
    event PaymentTokenAdded(address indexed token, address indexed feed);
    event PaymentTokenRemoved(address indexed token);
    event FiatChanged(bytes8 symbol, address indexed usdToFiatFeed);

    /* ========== CONSTRUCTOR ========== */
    // ===== PROXY BUILD: MODEL CONSTRUCTOR =====
    // No arguments; permanently locks the model. Zero controller tells
    // ExecutivePeerTreasury this is an inert model deployment.
    // Deploys this model's initializer sidecar (constructor/init code is NOT
    // subject to EIP-170, so the embedded sidecar costs the model no runtime
    // bytes — only a one-time deposit at model deployment).
    constructor() ExecutivePeerTreasury(address(0), address(0), address(0), "") {
        INIT_SIDECAR = address(new IssueTokenSaleManagerInitializer());
        _disableInitializers();
    }

    // ===== PROXY BUILD: INITIALIZER-SIDECAR STUB =====
    // The former constructor body lives in IssueTokenSaleManagerInitializer
    // (end of this file) and runs HERE via nested delegatecall against the
    // clone's storage — identical semantics, but those bytes count against the
    // SIDECAR's EIP-170 budget instead of this model's. One-shot is enforced
    // by `initializer` in THIS stub before delegating. Params are unnamed
    // (unused here); full NatSpec docs live on the sidecar's initialize().
    /// @notice Clone constructor-equivalent — body in IssueTokenSaleManagerInitializer.
    function initialize(
        address,
        address,
        uint256,
        address,
        address,
        address,
        address,
        address
    ) external initializer {
        _delegateInit(INIT_SIDECAR);
    }

    // REPLACED: setMinDollarValue removed — bytecode savings; use setMinMaxTokensPerPurchaseAddress instead
    // function setMinDollarValue(uint256 _minDollarValue) external {
    //     if (!IController(peerTreasuryController).isOfficialEntityFast(KECCAK_TOKEN_ADMIN, msg.sender)) revert NotTokenAdmin();
    //     if (_minDollarValue < 200) revert ThresholdTooLow();
    //     minDollarValue = _minDollarValue * 1e18;
    //     emit MinDollarValueChanged(_minDollarValue);
    // }

    /// @notice Set min/max token amount constraints per address
    /// @param _min Minimum tokens per single purchase (18 decimals). 0 = no minimum.
    /// @param _max Maximum cumulative tokens an address can purchase (18 decimals). 0 = no maximum.
    function setMinMaxTokensPerPurchaseAddress(uint256 _min, uint256 _max) external {
        _requireTokenAdmin();
        minTokensPerPurchase = _min;
        maxTokensPerPurchase = _max;
        emit MinMaxTokensPerPurchaseChanged(_min, _max);
    }

    /// @notice Set maximum number of unique purchaser addresses (0 = unlimited)
    function setMaxPurchasers(uint256 _maxPurchasers) external {
        _requireTokenAdmin();
        maxPurchasers = _maxPurchasers;
        emit MaxPurchasersChanged(_maxPurchasers);
    }

    /// @notice Get current min/max token-per-address constraints
    /// @return min Minimum tokens per purchase (0 = no minimum)
    /// @return max Maximum cumulative tokens per address (0 = no maximum)
    function getMinMax() external view returns (uint256 min, uint256 max) {
        return (minTokensPerPurchase, maxTokensPerPurchase);
    }

    /* ========== ADMIN FUNCTIONS ========== */
    function setSaleActive(bool _active) external {
        _requireTokenAdmin();
        saleActive = _active;
        emit SaleStatusChanged(msg.sender, _active);
    }

    function setProjectFlags(uint32 newFlags) external {
        _requireTokenAdmin();
        projectFlags = newFlags;
        emit ProjectFlagsChanged(newFlags);
    }

    // ===========================================================================
    // v43200: THIRD-PARTY-REGISTRAR BRIDGE PROVIDER ID (PSTPR)
    //         "Platform Signs on behalf of Third-Party Registrar"
    // ===========================================================================
    //
    // PSTPR IS A SERVER/MODAL SWITCH — NOT AN ON-CHAIN ENFORCEMENT GATE.
    //
    // The on-chain whitelist-signature path is unchanged from prior revisions:
    // bit 5 ON + a recovered signer that satisfies
    //     isOfficialEntityFast(KECCAK_THIRD_PARTY_REGISTRAR, signer)
    // on the project's Controller. There is exactly ONE Sig A path on-chain.
    //
    // What changes off-chain is WHO can be that signer:
    //
    //   • DIRECT THIRD-PARTY REGISTRAR
    //     For providers that DO sign EIP-191 messages directly (Chainalysis-
    //     style services that natively expose a signing key). The project
    //     admin registers the provider's signing address as
    //     KECCAK_THIRD_PARTY_REGISTRAR on the project's Controller.
    //
    //   • PLATFORM-BRIDGE
    //     For real-world KYC/AML providers (Sumsub, Persona, Veriff, Onfido,
    //     Jumio, Trulioo, ShuftiPro, ComplyAdvantage, iDenfy, iProov, …) that
    //     do NOT produce EIP-191 signatures. Their REST APIs only report
    //     "user X was verified by us." The PROJECT ADMIN registers the
    //     PLATFORM'S OWN bridge address as KECCAK_THIRD_PARTY_REGISTRAR on the
    //     project's Controller. The platform's bridge endpoint
    //     (ThirdPartyRegistrarBridge.php) mints Sig A only after server-side
    //     confirmation that the provider's API returned "approved" for
    //     (tokenAddress, userAddress).
    //
    // From the chain's perspective both paths are indistinguishable: in each
    // case the recovered signer is an address the project admin has listed as
    // KECCAK_THIRD_PARTY_REGISTRAR. No `isPlatformAdmin` check, no OR-mode
    // dual-tag check, no PSTPR-driven tag switch. Just LAST behavior.
    //
    // ROLE OF `thirdPartyBridgeProviderId` (PSTPR)
    //   The PSTPR storage byte tells the OFF-CHAIN platform and the modal
    //   which workflow is active for this project:
    //
    //     PSTPR == 0  →  No platform bridge. The platform's PHP
    //                    (ThirdPartyRegistrarBridge.php) will REFUSE to mint
    //                    any Sig A for this project — bridge is fully off.
    //                    Bit 5 may still be on (direct third-party path);
    //                    the user obtains Sig A out-of-band and pastes it.
    //     PSTPR != 0  →  Platform bridge is enabled for this project. The
    //                    modal (TSMU) reads this byte via the auto-generated
    //                    public getter to decide whether to render the
    //                    bridge UI block, and ThirdPartyRegistrarBridge.php
    //                    uses it to look up which provider adapter to invoke
    //                    (BridgeProviderRegistry.php's BRIDGE_PROVIDER_TABLE).
    //
    //   The on-chain contract never reverts on the value of this byte. If a
    //   user submits without Sig A, they simply don't get whitelisted — bit 3
    //   (if set) then blocks buying until an admin whitelists them manually,
    //   which is the intended UX.
    //
    // COURT-PROOF CHAIN
    //   When the platform signs as bridge, the note it embeds is committed to
    //   on-chain via IssueToken.whitelistUserWithRegKey's rawMessage:
    //
    //       keccak256(abi.encodePacked(
    //         user, token, isUS, expiry,
    //         keccak256(bytes(registrationNote))
    //       ))
    //
    //   So substituting the note at submit time breaks ecrecover. The
    //   platform's defense in any "we never signed this" claim is:
    //     (a) Read whitelistedUsers[user] from chain. v43206 storage shape:
    //           bytes[0:8] = uint64 big-endian expiry
    //           bytes[8:]  = registrationNote text
    //         Readers MUST declare the ABI return as `bytes` (not `string`)
    //         to avoid ethers UTF-8 decode errors on the binary prefix.
    //     (b) Parse the note text (bytes[8:]) as
    //         "TPR:<providerId>:<slug>:<providerConfirmationId>:<auditId>:<utc>"
    //         — the bridge's emitted shape (server convention, not enforced here).
    //     (c) Cross-reference auditId against the bridge's audit log table.
    //     (d) Pull the provider's own record by providerConfirmationId.
    //     (e) Confirm thirdPartyBridgeProviderId() at the time of mint equaled
    //         the <providerId> in the note.
    //   The on-chain triple (expiry, note, sig) is enough to RECONSTRUCT and
    //   ECRECOVER the full rawMessage without any off-chain hop; (c)-(e) are
    //   additional independent corroborations for full court certainty.
    //
    // REGISTRATION NOTE (SERVER POLICY — NEVER PARSED ON CHAIN)
    //   The bridge endpoint emits notes shaped like
    //       TPR:<providerId>:<slug>:<providerConfirmationId>:<auditId>:<utcYYYYMMDD>
    //   but this contract does NOT prefix-check, slug-check, length-check, or
    //   otherwise inspect the string. The keccak commit above is the only
    //   enforcement. Direct third-party registrars are free to use whatever
    //   note shape they prefer.
    //
    // PROVIDER ID TABLE  (canonical; mirrors BridgeProviderRegistry.php)
    //   Must stay in lockstep with BridgeProviderRegistry.php's BRIDGE_PROVIDER_TABLE
    //   so a future audit / court-proof investigation can reconstruct which
    //   provider was attested to from the note's TPR:<id>: alone.
    //
    //     id   slug             provider
    //     ---- ---------------- ---------------------------------------
    //       1  jumio            Jumio                — https://www.jumio.com/
    //       2  sumsub           Sumsub               — https://sumsub.com/
    //       3  persona          Persona              — https://withpersona.com/
    //       4  onfido           Onfido               — https://onfido.com/
    //       5  veriff           Veriff               — https://www.veriff.com/
    //       6  trulioo          Trulioo              — https://www.trulioo.com/
    //       7  shuftipro        Shufti Pro           — https://shuftipro.com/
    //       8  idenfy           iDenfy               — https://www.idenfy.com/
    //       9  complyadvantage  ComplyAdvantage      — https://complyadvantage.com/
    //      10  iproov           iProov               — https://www.iproov.com/
    //     11..199                (reserved for future built-in adapters)
    //     200..255               (per-project custom adapters)
    //
    /// @notice Third-party-registrar bridge provider ID (PSTPR).
    /// @dev    Read by ThirdPartyRegistrarBridge.php (refuses to mint Sig A
    ///         when zero) and by TSMU (decides whether to render the bridge
    ///         UI). NOT consulted by any on-chain check in this contract.
    ///         0 = bridge OFF for this project (direct-third-party path only).
    ///         1..255 = bridge ON; value indexes BridgeProviderRegistry.php's
    ///         BRIDGE_PROVIDER_TABLE.
    uint8 public thirdPartyBridgeProviderId;

    /// @notice TokenAdmin-only setter for the bridge provider ID.
    /// @dev    Setting != 0 enables the bridge UI in TSMU and unlocks
    ///         ThirdPartyRegistrarBridge.php for this project (server still
    ///         requires its own per-project config row in
    ///         TPR_projectConfig). Setting back to 0 immediately
    ///         disables both. No on-chain side effects beyond the storage write.
    function setThirdPartyBridgeProviderId(uint8 id) external {
        _requireTokenAdmin();
        thirdPartyBridgeProviderId = id;
    }

    /// @notice Set the manual-sale-approval flag for a single user.
    /// @dev v43106: caller gate widened to TokenAdmin OR any Official
    ///      SmartContract on this project's Controller via the shared
    ///      `_requireTokenAdminOrSmartContract` helper (also used by
    ///      setReferrerEmailHash — that v43105 widening was previously
    ///      inlined and is now folded into the same helper for bytecode +
    ///      runtime gas savings).
    ///      Rationale: lets project-side helpers (e.g.
    ///      BatchTransferAndExtrasManager.batchSetManualSaleApproval) push
    ///      bulk approvals without TokenAdmin needing to multicall this
    ///      function directly. The SmartContract caller is responsible for
    ///      its OWN role/bit gate before invoking us (BTM gates on
    ///      `onlyTokenAdmin` + projectFlags bit 24).
    function setManualSaleApproval(address user, bool approved) external {
        _requireTokenAdminOrSmartContract();
        if (user == address(0)) revert InvalidRecip();
        _salesApproved[user] = approved;
    }

    /// @notice Manual sale approval for benefits/stamp programs.
    /// @dev Encapsulates the approval-required flag (bit24):
    ///      - If bit24 is OFF, returns true (not required).
    ///      - If bit24 is ON, returns stored approval.
    function isManualSaleApprovedOrNotRequired(address user) public view returns (bool) {
        if (!_hasFlag(PF_MANUAL_SALES_APPROVAL_REQUIRED)) return true;
        return _salesApproved[user];
    }

    // ==================== REFERRAL HASHES (MINIMAL) ====================
    // No events (bytecode minimization). UI can poll via getReferrerTimesByEmailHash().
    // NOTE: Public function names retain the legacy "EmailHash" suffix so external
    // callers/ABIs are unaffected. The underlying storage was widened conceptually
    // (now keyed by hash of email + code/key combos); only the private storage
    // variable names were renamed.

    function setReferrerEmailHash(bytes32 hash, bool isActive) public {
        // v43105: admit TokenAdmin OR any Official SmartContract registered on
        // this project's Controller (e.g., IssueTokenDistributionManager — see
        // its addReferrerEmailHashAsExpander, which is the canonical SC caller
        // as of v43106 after the migration from BatchTransferAndExtrasManager).
        // The SC caller is responsible for its own platform-registrar signature
        // verification before invoking us.
        // v43106: gate folded into shared `_requireTokenAdminOrSmartContract`
        // helper (single STATICCALL via isOfficialDoubleEntityFast) — saves
        // ~180 bytes per call site vs the previous inlined 2-call form.
        _requireTokenAdminOrSmartContract();
        if (hash == bytes32(0)) revert ZeroHash();

        bool currentlyActive = isReferrerEmailHashActive(hash);
        if (isActive) {
            if (currentlyActive) revert ReferrerAlreadyActive();
            referrerEmailCombosPlusCodeOrKeyHashActiveTimes[hash].push(block.timestamp);
        } else {
            if (!currentlyActive) revert ReferrerAlreadyInactive();
            referrerEmailCombosPlusCodeOrKeyHashInactiveTimes[hash].push(block.timestamp);
        }
    }

    function isReferrerEmailHashActive(bytes32 hash) public view returns (bool) {
        uint256[] storage a = referrerEmailCombosPlusCodeOrKeyHashActiveTimes[hash];
        uint256[] storage d = referrerEmailCombosPlusCodeOrKeyHashInactiveTimes[hash];
        uint256 la = a.length > 0 ? a[a.length - 1] : 0;
        uint256 ld = d.length > 0 ? d[d.length - 1] : 0;
        return la > ld;
    }

    function getReferrerTimesByEmailHash(bytes32 hash)
        external
        view
        returns (uint256[] memory activeTimes, uint256[] memory inactiveTimes)
    {
        return (referrerEmailCombosPlusCodeOrKeyHashActiveTimes[hash], referrerEmailCombosPlusCodeOrKeyHashInactiveTimes[hash]);
    }

    /// @notice Set the per-referrer-hash max use count (TokenAdmin only). Default is 10.
    /// @dev    The default is intentionally generous: a single registrant may incur 2–4
    ///         gate hits (witness Range-GETs, CR.php verification GET, and an optional
    ///         pre-download) before they actually call selfRegisterForSales, and the
    ///         on-chain counter is only incremented by the registration call itself.
    ///         For typical projects 10 leaves room for ~5 referrals after subtracting
    ///         retry/abort attempts. Projects expecting heavy referral volume should
    ///         raise this proactively.
    ///
    /// @dev    CURRENT REALITY (audit note):
    ///         The use-count cap is enforced in TWO places:
    ///           1. Off-chain pre-flight in CR.php (cheap; reads referralUseCount() +
    ///              maxReferralUseCount() via eth_call, and now also consults the
    ///              `global.referralLinks` DB counter as a faster DOS-resilient mirror).
    ///           2. Inside selfRegisterForSales(...) itself — strict `>=` revert just
    ///              before atomically incrementing referralUseCount[hash].
    ///         The previously-external `increaseUseCount` was REMOVED to claw back
    ///         bytecode, so referralUseCount is now ONLY mutated by a complete
    ///         registration tx (line 2073). Consequence: the cap is *currently*
    ///         effectively unreachable via abuse — an attacker would have to sign,
    ///         pay gas for, AND broadcast a real selfRegisterForSales call for each
    ///         increment, and the platform itself never broadcasts user-generated
    ///         transactions on behalf of others. The off-chain DB counter is therefore
    ///         the primary abuse-detection surface today; the on-chain check is a
    ///         defense-in-depth backstop. A future `consumableHashCheck(hash)`
    ///         method (~100–200 bytes) would let gates increment the counter on each
    ///         download to make the on-chain backstop actually active — that addition
    ///         is deferred pending bytecode savings elsewhere in this contract.
    function setMaxReferralUseCount(uint256 newMax) external {
        _requireTokenAdmin();
        maxReferralUseCount = newMax;
    }

    // v43106 (bytecode-trim): manual `getMaxReferralUseCount()` getter removed.
    // The state variable is now `public maxReferralUseCount` so callers use the
    // Solidity-generated auto-getter (same ABI shape, ~40–60 bytes saved).

    /* ========== v43105: PROJECT-DEFINED CUSTOM QUESTIONNAIRE ========== */

    /// @notice Project-defined custom questionnaire (each entry rendered as a
    ///         separate question/disclaimer). Atomic replace only.
    ///
    /// @dev Per-entry encoding (UI-side convention; contract does NOT inspect):
    ///
    ///        char 0 (FORMAT):
    ///            'S'  — free-form String answer expected
    ///            'N'  — Number answer
    ///            'Y'  — Yes/No answer
    ///            'T'  — True/False (semantic alias of Y, different label)
    ///            'A'  — Assertion / disclaimer (no answer; just acknowledge)
    ///            'F'  — FLAG-ONLY entry: not displayed to the user; the
    ///                   project is asserting an internal sub-flag. The
    ///                   second character identifies WHICH sub-flag.
    ///
    ///        char 1 (SUB-FLAG, when char 0 is 'F'):
    ///            uppercase A-Z — 26 reserved project-defined sub-flags. Use
    ///            is purely UI/off-chain (CryptoRegistrar.php may interpret).
    ///
    ///        char 2..N (TEXT): the prompt (or empty for 'F' entries).
    ///
    ///      No event: TokenSaleModalUser sends questions+answers JSON to
    ///      CryptoRegistrar.php as part of the self-cert payload, and the
    ///      testamentHash includes them — off-chain has no need to subscribe.
    /// @dev Public auto-getter: customQuestions(uint256 index) returns one entry.
    ///      UI iterates indices until an out-of-bounds revert (no length getter).
    string[] public customQuestions;

    /// @notice Replace the entire questionnaire atomically. Token-admin only.
    ///         Pass an empty array to clear.
    function setCustomQuestions(string[] calldata entries) external {
        _requireTokenAdmin();
        customQuestions = entries;
    }

    function isSaleActive() public view returns (bool) {
        return saleActive && startSaleBlockNum > 0 && block.number >= startSaleBlockNum;
    }

    function setStartSaleBlockOffset(uint256 offset) external {
        _requireTokenAdmin();
        if (offset < 1) {
            saleActive = false;
            startSaleBlockNum = 0;
        } else {
            startSaleBlockNum = block.number + offset;
        }
        emit StartSaleBlockNumChanged(startSaleBlockNum);
    }

    function getStartSaleTimeInBlocks() external view returns (uint256) {
        return startSaleBlockNum > block.number ? startSaleBlockNum - block.number : 0;
    }

    /// @notice Set the base purchase price, expressed in the currently-active fiat.
    /// @param newPrice Price per token in the contract's selected fiat (18 decimals).
    /// @dev v43105 rename: was setPurchasePriceInUSD() in v43103. The new name is
    ///      semantically honest — when fiatSymbol is "USD" the price IS in USD;
    ///      when fiatSymbol is "EUR" (after setFiat) the price IS in EUR.
    ///      ABI selector is therefore new in v43105 (no continuity with v43103).
    function setPurchasePriceInFIAT(uint256 newPrice) external {
        _requireTokenAdmin();
        if (newPrice == 0) revert PriceZero();
        purchasePriceInFIAT = newPrice;

        // Base price and staggers are INDEPENDENT — setting base does not clear staggers.
        // Base price is used as fallback when no stagger triggers are met.

        emit PurchasePriceChanged(newPrice);
    }

    /* ========== v43105: FIAT SWITCHING ========== */

    /// @notice Switch the contract's pricing fiat. Default is USD.
    /// @param symbol  Display symbol for receipts / UI, ASCII right-padded with 0x00
    ///                in bytes8 (e.g. "USD" → 0x5553440000000000). Must be non-zero.
    /// @param usdToFiatFeed_  Chainlink-compatible "fiat / USD" feed (e.g. EUR/USD on
    ///                mainnet ≈ 1.08e8 means 1 EUR = $1.08). Pass address(0) to set
    ///                fiat back to USD (no bridge oracle needed).
    /// @dev `purchasePriceInFIAT` is NOT rewritten here. The number is reinterpreted
    ///      under the new fiat from the next buy onwards. If you want EUR pricing,
    ///      call setPurchasePriceInFIAT(newEurAmount) AFTER setFiat(bytes8("EUR"), feed).
    function setFiat(bytes8 symbol, address usdToFiatFeed_) external {
        _requireTokenAdmin();
        if (symbol == bytes8(0)) revert FiatSymbolEmpty();

        // A5 fix: enforce symbol/feed coherence — either it's USD with no bridge
        // oracle, or it's a non-USD fiat WITH a bridge oracle. The two combos
        // (`"USD" + nonzero feed` and `"non-USD" + zero feed`) silently break
        // pricing math by either applying USD/USD ≡ 1 redundantly or skipping
        // a required conversion. Reused FiatSymbolEmpty for bytecode economy.
        if ((symbol == bytes8("USD")) != (usdToFiatFeed_ == address(0))) revert FiatSymbolEmpty();

        if (usdToFiatFeed_ == address(0)) {
            // Switch back to USD: no bridge oracle; clear cached decimals.
            usdToFiatFeed = AggregatorV3Interface(address(0));
            _usdToFiatFeedDecimals = 0;
        } else {
            // v43105 (Tier-2 dedup): validate via _getValidatedPrice so we share
            // the same staleness / round / sign checks used at every buy. Return
            // value is intentionally discarded — we only care that the feed is
            // healthy at config time; the cached decimals are read separately.
            AggregatorV3Interface feed = AggregatorV3Interface(usdToFiatFeed_);
            _getValidatedPrice(feed);
            usdToFiatFeed = feed;
            _usdToFiatFeedDecimals = feed.decimals();
        }
        fiatSymbol = symbol;
        emit FiatChanged(symbol, usdToFiatFeed_);
    }

    /* ========== v43105: PAYMENT-TOKEN ALLOWLIST ========== */

    /// @notice Allow an additional ERC20 to be used to pay for token purchases.
    /// @param token     The ERC20 contract address (e.g. USDC, DAI, BUSD, EUROC).
    /// @param priceFeed Chainlink-compatible "token / USD" feed for that ERC20.
    /// @param usePermit Pass `true` for EIP-2612 tokens (USDC, DAI v2, EUROC, …).
    ///                  Pass `false` for tokens that don't implement permit
    ///                  (mainnet USDT, older non-permit tokens) — caller must
    ///                  approve(this, amount) in a prior tx.
    /// @dev   Saves runtime decimals() / decimals() calls by caching them now.
    ///        Reverts if `token` is already registered (note: saleStable and
    ///        USDT are pre-registered by the constructor, so re-adding them
    ///        is rejected here). Token-admin only.
    ///
    ///        N4 (open, addressed UI-side): we cannot verify on-chain that
    ///        `priceFeed` is actually for `token / USD`. AggregatorV3Interface
    ///        does NOT expose the base/quote asset addresses (Chainlink feeds
    ///        are price-only contracts). The closest signal is `description()`
    ///        which returns a string like "USDC / USD" — but matching by symbol
    ///        is fuzzy (USDC vs USDC.e collisions, formatting variants). The
    ///        admin UI MUST read feed.description() and human-confirm the
    ///        "<TOKEN_SYMBOL> / USD" pairing before submitting this tx. A wrong
    ///        feed silently mis-prices every buy/fee paid in `token`.
    function addPaymentToken(address token, address priceFeed, bool usePermit) external {
        _requireTokenAdmin();
        if (token == address(0) || priceFeed == address(0)) revert InvalidRecip();
        // v43105 (bytecode-trim): registered sentinel is `feed != address(0)`.
        if (address(paymentTokenInfo[token].feed) != address(0)) revert PaymentTokenAlreadyRegistered();

        // v43105 (Tier-2 dedup): same shared health check as setFiat /
        // syncStableCoin.
        AggregatorV3Interface feed = AggregatorV3Interface(priceFeed);
        _getValidatedPrice(feed);

        paymentTokenInfo[token] = PaymentTokenInfo({
            feed:          feed,
            feedDecimals:  feed.decimals(),
            tokenDecimals: ITokenDecimals(token).decimals(),
            usePermit:     usePermit
        });
        registeredPaymentTokens.push(token);
        emit PaymentTokenAdded(token, priceFeed);
    }

    /// @notice Remove a previously-allowlisted payment token. Token-admin only.
    /// @dev Tokens still held by the contract from prior purchases are unaffected;
    ///      this only blocks NEW purchases paid in `token`.
    ///
    ///      N3 fix: saleStable and USDT cannot be removed. They are
    ///      constructor-wired payment paths and removing them would silently
    ///      half-brick the contract (saleStable is also the unit of fee
    ///      distribution via _convertFiatToPaymentToken). To rotate the
    ///      saleStable feed/address use syncStableCoin instead.
    function removePaymentToken(address token) external {
        _requireTokenAdmin();
        if (token == stableCoinAddress || token == usdtAddress) revert PaymentTokenAlreadyRegistered();
        if (address(paymentTokenInfo[token].feed) == address(0)) revert PaymentTokenNotRegistered();
        delete paymentTokenInfo[token];
        // Compact the array (swap-and-pop to keep gas linear in worst case)
        uint256 len = registeredPaymentTokens.length;
        for (uint256 i = 0; i < len; i++) {
            if (registeredPaymentTokens[i] == token) {
                if (i != len - 1) registeredPaymentTokens[i] = registeredPaymentTokens[len - 1];
                registeredPaymentTokens.pop();
                break;
            }
        }
        emit PaymentTokenRemoved(token);
    }

    /// @notice Number of registered ERC20 payment tokens (INCLUDES saleStable + USDT,
    ///         excludes ETH which is keyed off address(0) and uses ethUsdPriceFeed).
    /// @dev v43105 unification: saleStable + USDT now live in the same registry as
    ///      admin-added tokens, so iterating registeredPaymentTokens(0..count-1) is
    ///      the canonical way to enumerate ALL ERC20 payment options.
    function getRegisteredPaymentTokenCount() external view returns (uint256) {
        return registeredPaymentTokens.length;
    }

    /**
     * @notice Set staggered pricing tiers.
     * @param prices Array of prices in the active fiat (18 decimals).
     * @param amountSoldTriggers Array of total sold amounts at which each price activates.
     * @dev - First tier should have amountSoldTrigger = 0 (from the beginning).
     *      - Arrays must be sorted by amountSoldTrigger ascending.
     *      - Setting this overwrites any previous pricing (single or staggered).
     *      - If you want a single price, use setPurchasePriceInFIAT() instead.
     *
     * Example (fiat==USD): first 1M tokens at $0.10, next 2M at $0.15, rest at $0.20:
     *   prices = [100000000000000000, 150000000000000000, 200000000000000000]
     *   amountSoldTriggers = [0, 1000000e18, 3000000e18]
     */
    function setStaggeredPrice(uint256[] calldata prices, uint256[] calldata amountSoldTriggers) external {
        _requireTokenAdmin();
        if (prices.length != amountSoldTriggers.length) revert LenMismatch();
        if (prices.length == 0) revert EmptyArr();
        if (amountSoldTriggers[0] != 0) revert Trigger0();

        // Verify sorting and valid prices.
        // A2 fix: every non-zero trigger MUST be > totalTokensSold. The trigger==0
        // tier is the "from-the-beginning" base — its price is what the next buyer
        // pays, and admin is allowed to repoint it (same as setPurchasePriceInFIAT).
        // Any trigger that is BOTH non-zero AND <= totalTokensSold would silently
        // re-price tokens that have already been sold, which is what the deleted
        // addPriceTier explicitly forbade.
        for (uint256 i = 0; i < prices.length; i++) {
            if (prices[i] == 0) revert PriceInvalid();
            if (i > 0) {
                if (amountSoldTriggers[i] <= amountSoldTriggers[i - 1]) revert TriggerOrder();
                if (amountSoldTriggers[i] <= totalTokensSold) revert TriggerOrder();
            }
        }

        // Clear existing tiers
        delete priceTiers;

        // Add new tiers
        for (uint256 i = 0; i < prices.length; i++) {
            priceTiers.push(PriceTier({
                priceInFIAT:       prices[i],
                amountSoldTrigger: amountSoldTriggers[i]
            }));
        }

        // v43105 (bytecode-trim): the previous `purchasePriceInFIAT = getCurrentPrice()`
        // sync was vestigial. The walker (`_tokensForFiat`) only falls back to
        // `purchasePriceInFIAT` when `priceTiers.length == 0`, and we just pushed
        // tiers — so the fallback is unreachable until tiers are cleared again.
        // The dropped `getCurrentPrice()` public function (see further below)
        // makes this sync moot anyway.

        emit StaggeredPriceSet(prices.length);
    }

    /// @notice Walk the staggered price tiers and compute how many tokens a
    ///         given fiat-18 payment buys, spending into successive tiers as
    ///         each one fills up. Single-tx multi-tier purchase.
    ///
    /// @dev v43105 (B2 redesign): replaces the old "cap at next boundary +
    ///      partial-fill / second-tx" approach. Doing the walk on-chain in a
    ///      single transaction makes `minTokensOut` a correct floor under all
    ///      conditions (including the race where another buyer fills the rest
    ///      of the current tier between the user's quote and execution): the
    ///      contract delivers exactly the tokens the math produces given live
    ///      `totalTokensSold`, no partial fill, no refund.
    ///
    ///      Algorithm: locate the active tier (highest tier whose trigger is
    ///      ≤ totalTokensSold, exploiting the ascending-sorted invariant from
    ///      setStaggeredPrice). Then, while remaining fiat > 0, fill the
    ///      capacity of the active tier; if remaining fiat is less than the
    ///      cap, finish at the current tier price and stop. The last tier has
    ///      no upper boundary.
    ///
    ///      No tiers configured (`priceTiers.length == 0`) ⇒ flat purchase
    ///      at `purchasePriceInFIAT`.
    function _tokensForFiat(uint256 fiatValue18) internal view returns (uint256 tokens) {
        uint256 len = priceTiers.length;
        if (len == 0) {
            // Flat-price sale.
            return (fiatValue18 * 1e18) / purchasePriceInFIAT;
        }

        uint256 sold = totalTokensSold;
        uint256 remaining = fiatValue18;
        uint256 i = 0;

        // Single merged loop. Each iteration either:
        //   (a) skips a tier whose trigger is fully behind us (sold already
        //       exceeded it — happens at most once at the start, walking from
        //       i=0 to the active tier), or
        //   (b) spends into the active tier — fully consuming its capacity
        //       and advancing, or finishing within it.
        // setStaggeredPrice enforces priceTiers[0].trigger == 0, so the
        // (a)-path is well-defined for sold == 0 (no skip needed).
        while (remaining > 0) {
            // (a) skip behind-us tier.
            if (i + 1 < len && priceTiers[i + 1].amountSoldTrigger <= sold) {
                i++;
                continue;
            }
            // (b) spend into the active tier.
            uint256 price = priceTiers[i].priceInFIAT;
            if (i + 1 >= len) {
                // Last tier — no upper boundary; spend everything here.
                tokens += (remaining * 1e18) / price;
                return tokens;
            }
            uint256 cap = priceTiers[i + 1].amountSoldTrigger - (sold + tokens);
            uint256 fiatToFillCap = (cap * price) / 1e18;
            if (remaining >= fiatToFillCap) {
                tokens += cap;
                remaining -= fiatToFillCap;
                i++;
            } else {
                tokens += (remaining * 1e18) / price;
                return tokens;
            }
        }
    }

    /// @dev v43105 (Tier-2 consolidation): both buyWith* paths share the same
    ///      four CHECK preconditions. Centralising them shaves the duplicated
    ///      bytecode at each call site and keeps the policy in one place.
    function _validateBuyPreconditions() internal view {
        if (!isSaleActive()) revert SaleInactive();
        if (!IIssueToken(issueTokenAddress).isActivated()) revert TokenInactive();
        if (!_isRegisteredForSales(msg.sender)) revert RegReq();
        if (stableCoinAddress != IIssueToken(issueTokenAddress).stableCoinAddress()) revert PriceFeedNotFresh();
    }

    // v43105 (bytecode-trim): `getCurrentPrice()` was DROPPED.
    //   - On-chain: the buy path now uses `_tokensForFiat()` (the walker),
    //     which reads tier prices directly. No internal caller remains.
    //   - Off-chain: UIs compute the active price client-side from
    //     `getPriceTiers()` + `totalTokensSold()` (highest tier whose trigger
    //     is ≤ totalTokensSold; fall back to `purchasePriceInFIAT()` when
    //     priceTiers is empty). This is exactly what the deleted function did.
    //   - Saving: ~80 bytes (function body + public selector + dispatch + ABI
    //     encoder for uint256 return).

    // v43105: addPriceTier() removed. Adding a single tier costs ~250 bytes of
    // bytecode (insertion sort + duplicate check). Admin UI now reads existing
    // tiers, splices the new one, and calls setStaggeredPrice(prices, triggers)
    // — which already validates ordering and the >= totalTokensSold rule via
    // the natural setStaggeredPrice path.

    function setStableCoinAddress(address) public pure override {
        revert StablecoinChangeRequiresFeedUpdate();
    }
    /**
     * @notice Sync this contract to IssueToken's current sale stablecoin (the
     *         quote / denomination currency) and update its USD price feed.
     * @param feedAddress New saleStable/USD price feed (token/USD oracle).
     * @dev Call whenever IssueToken's stableCoinAddress changes OR the feed
     *      itself needs rotating. The PREVIOUS sale-stable (if any) is left
     *      in paymentTokenInfo / registeredPaymentTokens — it remains a valid
     *      payment method. Admin can call removePaymentToken() to stop
     *      accepting it. Only the quote/denomination role moves.
     */
    function syncStableCoin(address feedAddress) external {
        _requireTokenAdmin();

        // TRUST MODEL — DO NOT add address(0) / isPlatformAdmin / 6-decimal
        // re-checks here. They are intentionally absent:
        //
        //   • address(0) feed: _getValidatedPrice(feed) below calls
        //     latestRoundData() and reverts loudly on a zero address
        //     before any state is written. No silent path.
        //
        //   • Stablecoin already platform-vetted: IssueToken's
        //     stableCoinAddress can ONLY have been installed via
        //     ExecutivePeerTreasury.setStableCoinAddress(), which enforces
        //     != address(0) AND isPlatformAdmin(addr,
        //     KECCAK_OFFICIAL_STABLECOIN). A token not on the Controller's
        //     official stablecoin list cannot be here.
        //
        //   • 6-decimal invariant: enforced by platform policy at
        //     Controller-listing time. KECCAK_OFFICIAL_STABLECOIN tokens
        //     are 6-dec by convention (see FeeManager — MAX_VALUE comment
        //     and the 6-dec storage convention throughout). FeeManager has
        //     NO runtime decimals check; it assumes 6-dec everywhere.
        //     SaleManager's constructor backstops once at deploy time
        //     (StablecoinNot6Dec).
        //
        // Why no re-check here, even for "safety":
        //   The genuine failure mode is a WRONG oracle — correct shape,
        //   correct decimals, but pointed at the wrong asset (e.g. a EUR
        //   feed when the stablecoin is USD-pegged). That failure is
        //   SILENT and indistinguishable from a healthy feed at this
        //   layer; a decimals or 6-dec re-check provides ZERO incremental
        //   protection against it. Only TokenAdmin diligence at
        //   syncStableCoin call time prevents it. Adding decimals checks
        //   here would be false comfort, not safety.
        //
        // TL;DR: address(0) already reverts loudly downstream; wrong-asset
        // oracle is unprotectable at this layer regardless of any check
        // we could add. TokenAdmin is the only line of defense and is
        // trusted per the contract's trust model. Re-checks here would be
        // wasted bytecode.

        AggregatorV3Interface feed = AggregatorV3Interface(feedAddress);
        _getValidatedPrice(feed);
        address newStable = IIssueToken(issueTokenAddress).stableCoinAddress();
        if (stableCoinAddress != newStable) {
            stableCoinAddress = newStable;
            if (address(paymentTokenInfo[newStable].feed) == address(0)) {
                registeredPaymentTokens.push(newStable);
            }
        }
        paymentTokenInfo[newStable] = PaymentTokenInfo({
            feed:          feed,
            feedDecimals:  feed.decimals(),
            tokenDecimals: ITokenDecimals(newStable).decimals(),
            usePermit:     true
        });
    }

    // v43105: clearAllFuturePriceTiers() removed. Admin UI rebuilds the desired
    // tier list (typically: keep already-triggered tiers, drop the rest) and
    // calls setStaggeredPrice() to atomically replace all tiers.

    /**
     * @notice Get all price tiers (Not needed but returns as arrays instead of custom tuple)
     * @return prices Array of prices
     * @return triggers Array of amount sold triggers
     */
    function getPriceTiers() external view returns (uint256[] memory prices, uint256[] memory triggers) {
        uint256 length = priceTiers.length;
        prices = new uint256[](length);
        triggers = new uint256[](length);

        for (uint256 i = 0; i < length; i++) {
            prices[i] = priceTiers[i].priceInFIAT;
            triggers[i] = priceTiers[i].amountSoldTrigger;
        }

        return (prices, triggers);
    }

    /* ========== CORE SALE FUNCTIONS ========== */

    /**
     * @notice Buy issue tokens with USDC or USDT, fees distributed automatically
     * @param amount Amount of stablecoin to spend
     * @param isUSDC true for USDC, false for USDT
     * @dev Two independent security checks:
     *      1. Token's getUserRegistrationStatus (gating check if active)
     *      2. SalesManager's isSalesRegistered (if isSalesRegistrationRequired=true)
     */

    /**
     * @notice Buy tokens with any allow-listed ERC20 (uses EIP-2612 permit when supported).
     * @param paymentToken Address of the ERC20 to pay with. Three categories accepted:
     *                       - the project's saleStable (stableCoinAddress)
     *                       - usdtAddress
     *                       - any token previously registered via addPaymentToken()
     *                     Anything else reverts with PaymentTokenNotRegistered.
     * @param amount    Payment amount in `paymentToken`'s native decimals (e.g. 6 for USDC).
     * @param deadline  Permit deadline. Ignored for USDT (USDT isn't EIP-2612 compliant
     *                  on most mainnets and requires a separate approve() tx).
     * @param v,r,s     EIP-2612 permit signature. Ignored for USDT.
     * @param minTokensOut Minimum IssueToken units (18-dec) the caller will accept.
     *                     Pass 0 to opt out of the front-run / mid-block reordering
     *                     guard. The UI is expected to set this to the live oracle
     *                     estimate minus a safety margin (e.g. -10%) so that an
     *                     ETH/stable price spike between quote and execution does
     *                     NOT cost the buyer significantly fewer tokens than they
     *                     saw quoted. This is an ABSOLUTE floor — not a percentage.
     *
     * @dev v43105: replaces the prior `(uint256 amount, uint8 mode, ...)` signature.
     *      `mode` is gone — the caller passes the actual token address. This is
     *      cleaner ABI-wise and removes the special-cased USDC mode.
     */
    function buyWithStableCoinPermit(
        address paymentToken,
        uint256 amount,
        uint256 deadline,
        uint8   v,
        bytes32 r,
        bytes32 s,
        uint256 minTokensOut
    ) external {
        _validateBuyPreconditions();

        // ------------------------------------------------------------
        // 1. v43105 unified lookup. saleStable, USDT and admin-added tokens
        //    all resolve through the same mapping; ETH is on a separate path
        //    (buyWithETH). Anything else fails closed.
        // ------------------------------------------------------------
        PaymentTokenInfo memory pti = paymentTokenInfo[paymentToken];
        if (address(pti.feed) == address(0)) revert PaymentTokenNotRegistered();

        // Execute permit when the token implements EIP-2612 (e.g. USDC, DAI v2,
        // EUROC, the project saleStable). Tokens flagged usePermit=false (e.g.
        // mainnet USDT) require a prior approve(this, amount).
        //
        // A7 fix (permit-grief): a watcher can copy the signed permit out of the
        // mempool, call permit() directly to consume the nonce, and the user's
        // tx would otherwise revert. We try/catch the permit; on failure we fall
        // through to the normal allowance check (the front-runner's permit also
        // wrote the same allowance, so the buy still succeeds).
        if (pti.usePermit) {
            try IERC20Permit(paymentToken).permit(msg.sender, address(this), amount, deadline, v, r, s) {}
            catch {
                if (IERC20(paymentToken).allowance(msg.sender, address(this)) < amount) revert XferFail();
            }
        }

        // ------------------------------------------------------------
        // 2. Convert payment → USD-18 → fiat-18. USD is the pivot.
        // ------------------------------------------------------------
        uint256 amount18    = amount * (10 ** (18 - pti.tokenDecimals));
        uint256 usdValue18  = (amount18 * _getValidatedPrice(pti.feed)) / (10 ** pti.feedDecimals);
        uint256 fiatValue18 = _usdToFiat(usdValue18);

        // 3. Walk the staggered tiers in a single tx. The walker spends ALL of
        //    fiatValue18 — there's no partial-fill / no second-tx workflow.
        //    minTokensOut now floors the FULL purchase under any race outcome.
        uint256 tokenAmount = _tokensForFiat(fiatValue18);
        if (tokenAmount < minTokensOut) revert UnderMin();

        // 4. Complete purchase (CEI: state already updated, then external calls).
        _completePurchase(paymentToken, fiatValue18, amount, pti.tokenDecimals, tokenAmount);
    }

    /**
     * @notice Purchase tokens with ETH.
     * @dev ETH → USD via ethUsdPriceFeed; USD → fiat via usdToFiatFeed (skipped if USD).
     *      The full msg.value is converted into fiat and walked across tiers
     *      by `_tokensForFiat`. There is no partial fill, no boundary refund,
     *      and no second-transaction workflow — a single buy may span any
     *      number of stagger tiers in one go.
     *
     *      A9 (intentional non-fix): integer division in the per-tier
     *      tokenAmount math can leave the buyer with a few wei worth of "dust"
     *      tokens fewer than a perfect fractional buy. We do NOT refund ETH
     *      for this — refunding a few wei costs orders of magnitude more in
     *      gas than the dust itself. Same applies to stablecoin buys
     *      (rounding loss is symmetric). Treat it as a small platform service
     *      fee. If a user genuinely overpays (e.g. fat-finger), the SaleManager
     *      IS an ExecutivePeerTreasury so a treasurer can refund manually via
     *      the executive transfer path.
     *
     * @param minTokensOut Absolute minimum tokens (18-dec) the caller accepts.
     *                     Pass 0 to disable. NOT a percentage. Floors the
     *                     FULL multi-tier purchase, so it remains a meaningful
     *                     guard even when other in-block buyers shift the
     *                     active tier between quote and execution.
     */
    function buyWithETH(uint256 minTokensOut) external payable {
        _validateBuyPreconditions();

        // ETH-18 * (USD/ETH * 1e10 to lift to 18-dec USD price) / 1e18 = USD-18.
        uint256 usdValue18  = (msg.value * _getValidatedPrice(ethUsdPriceFeed) * 1e10) / 1e18;
        uint256 fiatValue18 = _usdToFiat(usdValue18);

        uint256 tokenAmount = _tokensForFiat(fiatValue18);
        if (tokenAmount < minTokensOut) revert UnderMin();

        _completePurchase(address(0), fiatValue18, msg.value, 18, tokenAmount);
    }

    /**
     * @notice Complete a token purchase (shared logic for ETH and stablecoin purchases).
     * @param paymentToken Address of payment token (address(0) for ETH).
     * @param fiatValue18  Payment amount expressed in the contract's selected fiat
     *                     (18 decimals). Used as the basis for FeeManager percentages.
     *                     v43105: was `usdValue18` in v43103. (v43104 was never deployed.)
     *                     The unit is consistent end-to-end with how price is stored
     *                     (purchasePriceInFIAT).
     * @param paymentAmount Amount paid in payment token's native decimals.
     * @param paymentDecimals Decimals of the payment token.
     * @param tokenAmount Amount of tokens to transfer to buyer.
     */
    function _completePurchase(
        address paymentToken,
        uint256 fiatValue18,
        uint256 paymentAmount,
        uint8 paymentDecimals,
        uint256 tokenAmount
    ) internal {
        // MAX_DECIMALS alignment — policy & math documented at the immutable
        // declaration (_MAX_DEC_STEP). Floor buyer down, ceil fees up (below),
        // buyer-net stays aligned by construction.
        uint256 _step = _MAX_DEC_STEP;
        tokenAmount   = (tokenAmount / _step) * _step;

        // 🔒 CHECKS-EFFECTS-INTERACTIONS PATTERN
        // 1. CHECKS: Sale-active, registration done in callers; token min/max/purchasers here.
        if (tokenAmount == 0) revert AmtZero();
        if (minTokensPerPurchase > 0 && tokenAmount < minTokensPerPurchase) revert UnderMin();
        if (maxTokensPerPurchase > 0 && userPurchases[msg.sender] + tokenAmount > maxTokensPerPurchase) revert OverMax();
        if (maxPurchasers > 0 && userPurchases[msg.sender] == 0 && totalPurchaserCount >= maxPurchasers) revert MaxBuyers();

        // 2. EFFECTS: Update state BEFORE external calls to prevent reentrancy
        totalTokensSold += tokenAmount;
        tokensSoldByPaymentToken[paymentToken] += tokenAmount;

        // Track first-time purchasers for holder fee optimization
        if (userPurchases[msg.sender] == 0) {
            totalPurchaserCount += 1;
        }
        userPurchases[msg.sender] += tokenAmount;

        // 3. INTERACTIONS: External calls happen AFTER state is updated
        // Pull stablecoin payment (ETH already in contract via msg.value)
        if (paymentToken != address(0)) {
            IERC20(paymentToken).safeTransferFrom(msg.sender, address(this), paymentAmount);
        }
        // Distribute fees (external calls to fee recipients). Return value
        // dropped — TokenSold no longer carries totalFees (see event docstring).
        _distributeFees(paymentToken, fiatValue18, paymentAmount, paymentDecimals);

        // TokenPurchase fee distribution (token-denominated, in IssueToken units).
        // Convention: FeeManager returns 6-decimal units; for TokenPurchase those units are interpreted as micro-tokens.
        // We cap at 50% of purchased tokenAmount (totalVal > 0 path enforces this).
        uint256 tokenAmount6 = tokenAmount / 1e12; // floor: acceptable micro-token quantization
        (IFeeManager.CalculatedEntityAmount[] memory tokenFees6, /* totalTokenFee6 — recomputed after step-up-rounding below */) =
            IFeeManager(feeManager).calculateChainedAmounts(
                tokenAmount6,              // totalVal: token amount in 6 decimals (micro-tokens)
                5000,                     // maxPct: 50% cap
                KECCAK_FEE_TOKENPURCHASE
            );

        // Add timelock if manager is set (external call to timelock manager)
        address timeLockMgr = IIssueToken(issueTokenAddress).timeLockManager();

        // Distribute token fees to each entity, then timelock recipients equally.
        // Each fee is CEIL-rounded to `_step` so it satisfies MAX_DECIMALS on the
        // downstream IIssueToken.transfer() call. We track the rounded total so
        // the post-loop "fee > purchase" sanity check uses the actual amount
        // about to leave the SaleManager's balance.
        uint256 totalTokenFee18 = 0;
        for (uint256 i = 0; i < tokenFees6.length; i++) {
            uint256 raw18 = tokenFees6[i].amount * 1e12;
            if (raw18 == 0) continue;
            uint256 fee18 = ((raw18 + _step - 1) / _step) * _step; // ceil to MAX_DECIMALS grid
            if (!IIssueToken(issueTokenAddress).transfer(tokenFees6[i].entityAddress, fee18)) revert XferFail();
            if (timeLockMgr != address(0)) {
                IIssueTokenTimeLock(timeLockMgr).addTimeLockedAllocation(tokenFees6[i].entityAddress, fee18);
            }
            totalTokenFee18 += fee18;
        }
        // Guard: ceiling rounding could push the fee total above the purchase
        // (only possible when the un-rounded total was already near tokenAmount
        // — e.g., the 50% maxPct cap is hit and MAX_DECIMALS < 6).
        if (totalTokenFee18 > tokenAmount) revert XferFail();

        // Transfer net tokens to buyer (external call to token contract).
        // tokenAmount and totalTokenFee18 are both multiples of `_step`, so
        // buyerNet is too — the IssueToken precision check trivially passes.
        uint256 buyerNet = tokenAmount - totalTokenFee18;
        if (!IIssueToken(issueTokenAddress).transfer(msg.sender, buyerNet)) revert XferFail();

        // Add timelock if manager is set (external call to timelock manager)
        if (timeLockMgr != address(0)) {
            IIssueTokenTimeLock(timeLockMgr).addTimeLockedAllocation(msg.sender, buyerNet);
        }

        emit TokenSold(msg.sender, paymentToken, paymentAmount, tokenAmount);
    }

    /* ========== HELPER FUNCTIONS ========== */

    /**
     * @notice Check if user is registered for sales
     *     EITHER self OR (third-party OR manually) whitelisted AND self-registered
     *     or completely unlocked NO REG NEEDED.
     *  WARNING!  if unlcoked no doc at URL guarantee by platform Registrar nor user self-cert attestation
     * @param user User address to check
     * @return bool True if user can purchase
     * @dev Checks TWO places (OR logic):
     *      1. Token.whitelistedUsers (manual admin approval via addWhitelistedUsers)
     *      2. ContentManager.isUserRegistered (user self-certification with wallet signature)
     *      Note: Uses SAME whitelist database as token gating, but independent control
     */
    /**
     * @notice Check if user is registered for sales
     * @param user Address to check
     * @return True if user can purchase tokens
     * @dev NEW PARADIGM (self-cert is ALWAYS required):
     *      1. ContentManager registration (self-cert) - ALWAYS required if registration is enabled
     *      2. Token whitelist (ADD-ON) - required if manual OR third-party mode is enabled
     *
     * MODES:
     * - isSalesRegistrationRequired == false → Everyone can buy (open sales)
     * - ContentManager ONLY → Self-cert alone is sufficient
     * - ContentManager + Manual → Self-cert + Token whitelist (admin/project registrar)
     * - ContentManager + Third-Party → Self-cert + Token whitelist (third-party KYC)
     */
    function _isRegisteredForSales(address user) internal view returns (bool) {
        // RULE 2: NO sale may proceed if user does not SELF-CERT.
        // Self-cert is ALWAYS required even if no registrar whitelist is required and/or gating is off.
        address contentMgr = IIssueToken(issueTokenAddress).contentManager();
        bool isInContentMgr = IIssueTokenContentManager(contentMgr).isUserRegistered(user, issueTokenAddress);
        if (!isInContentMgr) return false; // ❌ Not self-certified

        // Optional: require manual sales approval (does NOT whitelist in IssueToken).
        if (!isManualSaleApprovedOrNotRequired(user)) return false; // ❌ Not approved for purchase (or approval required but missing)

        // Registrar Whitelist Required (byte1 bit3): require token whitelist entry.
        // NOTE: manual registration is "direct whitelist" (no signature), and is satisfied by being whitelisted.
        if (_hasFlag(PF_REGISTRAR_WHITELIST_REQUIRED)) {
            // getUserRegistrationStatus: 0=not whitelisted, 1=US, 2=Non-US, 3=gating off
            uint8 registrationStatus = IIssueToken(issueTokenAddress).getUserRegistrationStatus(user, false);

            // registrationStatus > 0 means user is whitelisted (by admin/manual OR key-based registrar OR third-party registrar)
            if (registrationStatus == 0) return false; // ❌ Not whitelisted
        }

        // ✅ All requirements met
        return true;
    }

    // v43106 (bytecode-trim): `canUserBuy(address)` external wrapper removed
    // (~40–60 bytes saved). It was a thin pass-through to the internal
    // `_isRegisteredForSales`. UI callers must use `getPurchaseEligibility(address)`
    // and treat any non-zero `statusMode` as "can buy" (see status-code legend
    // on that function). `_isRegisteredForSales` remains `internal` — there is
    // no external selector for it.

    /**
     * @notice Get detailed purchase eligibility status for a user
     * @param user Address to check
     * @return canBuy True if user can purchase
     * @return reason Human-readable reason string
     * @return isInContentMgr True if registered in ContentManager
     * @return isInTokenWhitelist True if in Token whitelist
     * @dev This function provides comprehensive status for UI display
     *      Uses the same logic as buyWithStablecoinPermit() for accurate pre-flight checks
     */
    /**
     * @notice Get detailed purchase eligibility status for a user
     * @param user Address to check
     * @return statusMode Numeric status code:
     *         0 = Not eligible
     *         1 = Open sales (no registration required)
     *         2 = Registered (self-cert only)
     *         3 = Fully registered (self-cert + whitelist)
     * @return isInContentMgr True if registered in ContentManager
     * @return isInTokenWhitelist True if in Token whitelist
     * @dev Uses the same logic as _isRegisteredForSales() for accurate pre-flight checks
     *
     * Status code meanings (for UI/frontend):
     *   0: Not eligible - various reasons (check flags for details)
     *   1: Open sales - no registration required
     *   2: Registered (self-cert only)
     *   3: Fully registered (self-cert + whitelist)
     */
    function getPurchaseEligibility(address user) external view returns (
        uint8 statusMode,
        bool isInContentMgr,
        bool isInTokenWhitelist
    ) {
        // Self-cert is ALWAYS required for purchase eligibility.
        address contentMgr = IIssueToken(issueTokenAddress).contentManager();
        isInContentMgr = IIssueTokenContentManager(contentMgr).isUserRegistered(user, issueTokenAddress);

        if (!isInContentMgr) {
            return (0, false, false);
            // return (false, "Registration required - self-certification not found", false, false);
        }

        // Optional sales-approval requirement (independent from token whitelist).
        if (!isManualSaleApprovedOrNotRequired(user)) {
            return (0, true, false);
        }

        // Check Token whitelist only if Registrar Whitelist Required (byte1 bit3)
        if (_hasFlag(PF_REGISTRAR_WHITELIST_REQUIRED)) {
            uint8 whitelistStatus = IIssueToken(issueTokenAddress).getUserRegistrationStatus(user, false);
            isInTokenWhitelist = whitelistStatus > 0;

            if (!isInTokenWhitelist) {
                return (0, true, false);
                // return (false, "Registration required - token whitelist approval needed", true, false);
            }

            return (3, true, true);
            // return (true, "Fully registered (self-cert + whitelist)", true, true);
        }

        // Self-cert alone is sufficient
        return (2, true, false);
        // return (true, "Registered (self-cert only)", true, false);
    }

    /* ========== FEE DISTRIBUTION ========== */

    /**
     * @notice Distribute fees to all active chained entities using FeeManager's calculation engine.
     * @param paymentToken Address of payment token (address(0) for ETH).
     * @param fiatValue18  Payment amount expressed in the contract's selected fiat
     *                     (18 decimals).
     *
     * @dev v43105 fee-bug fix: in v43103 this function fed FeeManager `usdValue18 / 1e12`
     *      (USD-6) and then ran the result through `_convertStablecoinToPaymentToken`
     *      whose Step 1 multiplied by the saleStable/USD oracle — silently mis-pricing
     *      fees on non-USD-pegged saleStables (EUROC over-paid by ~18%, XSGD under-paid
     *      by ~26%). This version feeds FeeManager fiat-6 and uses the renamed
     *      `_convertFiatToPaymentToken` which composes fiat→USD→token cleanly.
     *
     *      v43105 bytecode-trim: return value dropped. TokenSold no longer carries
     *      totalFees, so accumulating it here would be dead code. FeeManager emits
     *      its own per-recipient events for off-chain reconstruction.
     */
    function _distributeFees(
        address paymentToken,
        uint256 fiatValue18,
        uint256 /* paymentAmount */,
        uint8 /* paymentDecimals */
    ) internal {
        // FeeManager works in 6-dec basis points. Whatever unit we feed it, it
        // returns fees in the same unit. Here we feed fiat-6, get fiat-6 back.
        (IFeeManager.CalculatedEntityAmount[] memory calculatedFees, uint256 totalFeeAmount) =
            IFeeManager(feeManager).calculateChainedAmounts(
                fiatValue18 / 1e12,   // Payment in fiat (6 decimals)
                10000,                // maxPct (100% in basis points)
                KECCAK_FEE_PURCHASE   // feeTypeHash: resolved internally by FeeManager
            );

        if (calculatedFees.length == 0 || totalFeeAmount == 0) {
            return; // No fees to distribute
        }

        // Distribute purchase fees to each entity, converted to payment token
        for (uint256 i = 0; i < calculatedFees.length; i++) {
            if (calculatedFees[i].amount == 0) {
                continue; // Skip entities with zero fees
            }

            // Convert fee from 6-dec FIAT units to payment token
            uint256 feeInPaymentToken = _convertFiatToPaymentToken(
                calculatedFees[i].amount,  // fiat-6
                paymentToken
            );

            // Transfer fee in payment token
            bool success;
            if (paymentToken == address(0)) {
                // ETH: Try receiveFee() for contracts, fallback to raw call
                if (calculatedFees[i].entityAddress.code.length > 0) {
                    // Contract detected - try receiveFee() for treasury compatibility
                    try ExecutivePeerTreasury(calculatedFees[i].entityAddress).receiveFee{value: feeInPaymentToken}() {
                        // Success via receiveFee()
                    } catch {
                        // Fallback to raw call (for contracts without receiveFee)
                        (success, ) = calculatedFees[i].entityAddress.call{value: feeInPaymentToken}("");
                        if (!success) revert FeeTransferFail();
                    }
                } else {
                    // EOA - use raw call
                    (success, ) = calculatedFees[i].entityAddress.call{value: feeInPaymentToken}("");
                    if (!success) revert FeeTransferFail();
                }
            } else {
                // ERC20
                IERC20(paymentToken).safeTransfer(calculatedFees[i].entityAddress, feeInPaymentToken);
            }

            // emit FeeDistributed(calculatedFees[i].entityAddress, paymentToken, feeInPaymentToken, true); // REMOVED: wasteful gas/bytecode
        }

        // NOTE: PRT notification is triggered by the token transfer that follows this fee distribution
        // in _completePurchase() (IssueToken -> DistributionManager -> ProjectRevenueTreasury).
        // Calling FeeManager.triggerNotify() here is redundant and may double-trigger processing.
        // IFeeManager(feeManager).triggerNotify();
    }

    /**
     * @notice Convert a fiat amount (6 decimals) into the payment token's native decimals.
     * @param fiatAmount6  Fee amount in fiat (6 decimals), as returned by FeeManager when
     *                     fed a fiat-6 totalVal in _distributeFees().
     * @param paymentToken Payment token address (address(0) for ETH; otherwise saleStable,
     *                     usdtAddress, or any admin-allowlisted token).
     * @return Amount in payment token's native decimals.
     *
     * @dev v43105: replaces the buggy `_convertStablecoinToPaymentToken`. The pipeline is:
     *
     *      fiat-6  →  fiat-18  →  USD-18  →  payment token (native decimals)
     *
     *      The "fiat → USD" leg is `_fiatToUsd`, an identity when fiatSymbol=="USD".
     *      The "USD → token" leg uses each token's USD oracle (from constructor for
     *      saleStable + USDT, from the allowlist for everything else). The earlier bug
     *      came from using the saleStable/USD feed for ALL tokens regardless of which
     *      token was being paid out — fixed by per-token oracle resolution.
     */
    function _convertFiatToPaymentToken(
        uint256 fiatAmount6,
        address paymentToken
    ) internal view returns (uint256) {
        // Lift fiat-6 → fiat-18 (no oracle), then fiat-18 → USD-18 (skipped if fiat==USD).
        uint256 usdAmount18 = _fiatToUsd(fiatAmount6 * 1e12);

        // ETH is on a separate path (not in paymentTokenInfo).
        if (paymentToken == address(0)) {
            return (usdAmount18 * 1e8) / _getValidatedPrice(ethUsdPriceFeed);
        }

        // v43105 unified lookup: saleStable, USDT, and admin-added tokens all
        // resolve through the same mapping. The earlier (v43103) bug used the
        // saleStable/USD feed for ALL tokens regardless of which token was
        // actually being paid out — now each token uses its own USD oracle.
        PaymentTokenInfo memory pti = paymentTokenInfo[paymentToken];
        if (address(pti.feed) == address(0)) revert PaymentTokenNotRegistered();

        // tokenAmount = USD / tokenUsdPrice; both lifted to 18 dec then scaled to native.
        return (usdAmount18 * (10 ** pti.feedDecimals) * (10 ** pti.tokenDecimals))
               / (_getValidatedPrice(pti.feed) * 1e18);
    }

    /* ========== TREASURY WITHDRAWAL ========== */
    // Treasurers Use executivePeerTreasuryTransfer() and
    // ExecutivePeerTreasuryWithdrawal() functions to withdraw unsold tokens.

    /* ========== SALES REGISTRATION FUNCTIONS (SEC COMPLIANCE) ========== */

    /**
     * ===========================================================================
     * SALES REGISTRATION vs TOKEN GATING - TWO INDEPENDENT SECURITY LAYERS
     * ===========================================================================
     *
     * This system is SEPARATE from IssueToken's gating/whitelist system:
     *
     * PURPOSE DISTINCTION:
     * +- IssueToken Gating: Controls token TRANSFERS (who can hold/receive)
     * +- SalesManager Registration: Controls PURCHASES from THIS SalesManager
     *
     * ARCHITECTURE:
     * +- Manual Registration: Uses IssueToken.whitelistedUsers mapping
     * |  +- SAME database as token gating, but DIFFERENT purpose/control
     * +- Self-Registration: Uses IssueTokenContentManager.isUserRegistered mapping
     *    +- Wallet signature-based, court-verifiable proof
     *
     * REGISTRATION CHECK (_isRegisteredForSales):
     * 1. If isSalesRegistrationRequired == false → Allow all purchases
     * 2. Check IssueToken.whitelistedUsers (manual admin approval) → Allow if found
     * 3. If isSalesSelfRegister == true → Check ContentManager.isUserRegistered → Allow if found
     * 4. Otherwise → REVERT (not registered in either place)
     *
     * TOKEN TRANSFER GATING (happens AFTER purchase):
     * - Checked automatically during IssueToken.transfer() call
     * - If gatingActive == true → recipient must be in whitelistedUsers
     * - This is INDEPENDENT of sales registration check above
     *
     * CONFIGURATION MODES:
     * +---------------------+--------------+------------------------------------+
     * | Mode                | Flags        | Effect                             |
     * +---------------------+--------------+------------------------------------+
     * | Open Purchase       | RegReq=false | Anyone can buy (no check)          |
     * | Manual Only         | RegReq=true  | Check Token.whitelistedUsers only  |
     * |                     | SelfReg=false|                                    |
     * | Self-Reg Only       | RegReq=true  | Check ContentManager only          |
     * |                     | SelfReg=true |                                    |
     * | Manual OR Self-Reg  | RegReq=true  | Check BOTH (OR logic)              |
     * |                     | SelfReg=true |                                    |
     * +---------------------+--------------+------------------------------------+
     *
     * NOTE: Officers should use RestrictedSaleManager.sol for secondary sales with
     * custom pricing and escrow. This contract is for primary sales only.
     * ===========================================================================
     */



    /* ========== SALES REGISTRATION FUNCTIONS (SEC COMPLIANCE) ========== */

    /**
     * ===========================================================================
     * SALES REGISTRATION vs TOKEN GATING - TWO INDEPENDENT SECURITY LAYERS
     * ===========================================================================
     *
     * This system is SEPARATE from IssueToken's gating/whitelist system:
     *
     * 1. SALES REGISTRATION (this contract):
     *    - Controlled by: isSalesRegistrationRequired + isSalesSelfRegister flags
     *    - Controls: Who can PURCHASE tokens from THIS SalesManager
     *    - Managed by: TreasuryAdmin (via setRegistrationConfig, adminApproveUser)
     *    - Mapping: isSalesRegistered[address] → bool
     *    - Used in: buyWithETH(), buyWithStablecoinPermit()
     *
     * 2. TOKEN GATING (IssueToken contract):
     *    - Controlled by: gatingActive flag in IssueToken
     *    - Controls: ALL token transfers (transfer, transferFrom, etc.)
     *    - Managed by: TokenAdmin (via IssueToken.setGatingActive)
     *    - Mapping: IssueToken.whitelistedUsers[address] → bool
     *    - Used in: IssueToken.isRestricted() → checked on every transfer
     *
     * ===========================================================================
     * SECURITY MODES (can be combined):
     * ===========================================================================
     *
     * MODE A: Open Sales + Open Transfers
     *   - isSalesRegistrationRequired = false
     *   - IssueToken.gatingActive = false
     *   → Anyone can buy, anyone can transfer (utility token, post-lockup)
     *
     * MODE B: Restricted Sales + Open Transfers
     *   - isSalesRegistrationRequired = true
     *   - IssueToken.gatingActive = false
     *   → Only registered users can buy, but ALL holders can transfer freely
     *   → Use case: Initial sale period with accreditation, then unrestricted secondary
     *
     * MODE C: Open Sales + Restricted Transfers
     *   - isSalesRegistrationRequired = false
     *   - IssueToken.gatingActive = true
     *   → Anyone can buy, but only whitelisted users can transfer
     *   → Use case: Open sale but want to control who can hold/trade
     *
     * MODE D: Restricted Sales + Restricted Transfers (MAXIMUM SECURITY)
     *   - isSalesRegistrationRequired = true
     *   - IssueToken.gatingActive = true
     *   → Only registered users can buy, only whitelisted users can transfer
     *   → Use case: Reg D offering with ongoing transfer restrictions
     *
     * ===========================================================================
     * TYPICAL WORKFLOW (Reg D → Rule 144):
     * ===========================================================================
     *
     * PHASE 1 (Initial Offering - Months 0-12):
     *   - isSalesRegistrationRequired = true, isSalesSelfRegister = true
     *   - IssueToken.gatingActive = true
     *   - TimeLock = 12 months
     *   → Only certified investors can buy, transfers restricted, 12-month hold
     *
     * PHASE 2 (Post-Lockup - Month 12+):
     *   - isSalesRegistrationRequired = false (no new sales OR keep restricted)
     *   - IssueToken.gatingActive = false (unrestricted transfers)
     *   - TimeLock expired = true
     *   → Secondary market opens, Rule 144 compliance complete
     *
     * ===========================================================================
     */

    /**
     * @notice Configure sales registration requirements
     * @param _required Whether registration is required to purchase
     * @param _selfRegister Whether users can self-register via wallet signature
     * @dev Only TreasuryAdmin can configure this (controls who can buy from SalesManager)
     *
     * REGISTRATION MODES:
     * 1. required=false, selfReg=false → No registration needed (open sales)
     * 2. required=true, selfReg=true  → Self-service: Users sign certification message
     * 3. required=true, selfReg=false → Admin-only: TreasuryAdmin must call adminApproveUser()
     * 4. required=false, selfReg=true → Optional: Users can register but not required
     *
     * ⚠️ IMPORTANT: Sales registration is INDEPENDENT of token gating (IssueToken.gatingActive).
     * These are TWO SEPARATE security layers:
     *   - Sales Registration (here) → Controls who can BUY from this SalesManager
     *   - Token Gating (IssueToken) → Controls who can TRANSFER tokens (all transfers)
     *
     * Both can be active simultaneously for maximum security, or independently.
     */
    /**
     * @notice Configure sales registration requirements
     * @param _required Whether registration is required for purchases
     * @param _manualRegister Enable manual mode (direct whitelist, no registrar signature validation)
     * @param _thirdPartyRegister Enable third-party KYC mode (e.g., Chainalysis, SumSub)
     * @param _platformVerifyBypassed Bypass platform registrar signature requirement (true = not required, false = required)
     *
     * ===========================================================================
     * 🚨 CRITICAL: EMAIL/CONTACT COLLECTION FOR SEC COMPLIANCE
     * ===========================================================================
     *
     * `isPlatformVerifyBypassed = false` (DEFAULT) is the ONLY way projects automatically
     * capture user email/contact details through the platform, UNLESS:
     *
     * 1. `isThirdPartyRegistrar = true` → Third-party KYC provider collects contact info
     * 2. `isManualRegisterEnabled = true` → Project manually collects contact info off-chain
     *
     * If ALL THREE are off/bypassed:
     * - ❌ NO email collection
     * - ❌ NO contact details
     * - ❌ NO way to reach investors
     * - ⚠️ ONLY appropriate for:
     *   • Public registered funds (no contact requirement)
     *   • Utility tokens (non-securities)
     *   • Tokens with no regulatory contact obligations
     *
     * For Reg D 506(b), Reg D 506(c), Reg CF, Reg A+, or any offering requiring investor
     * contact records: You MUST enable at least ONE of:
     * - Platform verification (isPlatformVerifyBypassed = false) ← RECOMMENDED
     * - Third-party KYC (isThirdPartyRegistrar = true)
     * - Manual registration (isManualRegisterEnabled = true)
     *
     * ===========================================================================
     *
     * @dev NEW PARADIGM: Self-cert (ContentManager) is ALWAYS required if registration is enabled
     *      Manual and third-party are ADD-ON requirements that also require Token whitelist
     *      Platform verify bypass controls whether platform registrar signature can be skipped
     *
     * DEPRECATED (vNext): Prefer configuring policy via:
     *   - setProjectFlags(uint24 newFlags)
     * and reading via:
     *   - projectFlags()
     */
    // NOTE (legacy admin UI only):
    // This contract no longer exposes setRegistrationConfig(...) or the legacy boolean toggles.
    // Configuration should be done via:
    //   - setProjectFlags(uint24 newFlags)
    // and read via:
    //   - projectFlags()

    /* ========== THIRD-PARTY REGISTRAR MANAGEMENT (KYC PROVIDERS) ========== */

    /**
     * @notice Add a third-party KYC provider (e.g., Chainalysis, SumSub, Persona)
     * @param registrarAddress Address of the third-party KYC provider's signing key
     * @param registrarURL URL endpoint for the KYC service (stored as entity "name" in Controller)
     * @param registrarName Human-readable name (stored as entity "id" in Controller)
     * @dev ALL storage is in Controller - SalesManager has ZERO storage overhead!
     *      Controller.addOfficialEntity("ThirdPartyRegistrar", address, registrarURL, registrarName)
     * DO tHIS in CONTROLLER DIRECTLY!
     */


    /**
     * @notice Third-party KYC provider approves user (whitelists in Token)
     * @param isUS Whether user is US-based (AND accredited if required to be.)
     *   Exactly where the user is from is an off-chain contact issue anyway.
     * @param registrarSignature Signature from third-party KYC provider
     * @param registrationNote User info/KYC reference for whitelist
     * @dev Validates KYC provider signature and whitelists user in IssueToken
     * @dev User identified via msg.sender passed to Token.whitelistUserWithRegKey() (supports AA/multisig)
     *
     * DOES:
     * - Validates third-party registrar signature
     * - Whitelists user in Token (enables transfers if gating active)
     *
     * DOES NOT:
     * - Register in ContentManager (that's handled separately via selfRegisterForSales)
     * - Check platform registrar doc URL (third-party handles their own docs)
     */
    // v43105: third-party only. Platform no longer signs Sig A; the bool
    // dispatch is gone. IssueToken.whitelistUserWithRegKey itself still accepts
    // project-local Registrar signers — this wrapper only gates the third-party
    // path coming through selfRegisterForSales.
    //
    // v43200: the recovered signer may be either a direct third-party registrar
    // OR the platform's bridge address — but ONLY because the PROJECT ADMIN has
    // registered that address as KECCAK_THIRD_PARTY_REGISTRAR on this project's
    // Controller. From the chain's perspective the two cases are identical and
    // pass through the same single-tag check below. The PSTPR storage byte
    // (`thirdPartyBridgeProviderId`) is a server/modal switch and is NOT
    // consulted here.
    function whitelistRegister(
        bool isUS,
        bytes calldata registrarSignature,
        string calldata registrationNote,
        uint64 expiry
    ) public {
        // Token.whitelistUserWithRegKey() returns the recovered signer.
        // v43200: expiry now ALWAYS required > 0 by the token (legacy 3-field
        // payload retired alongside the rawMessage upgrade that binds
        // keccak256(bytes(registrationNote))).
        address recoveredRegistrar = IIssueToken(issueTokenAddress).whitelistUserWithRegKey(
            msg.sender,  // User calling this function (supports EOAs and smart accounts)
            isUS,
            registrarSignature,
            registrationNote,
            expiry
        );

        // Validate recovered signer is a ThirdPartyRegistrar registered on this
        // project's Controller. Both direct third-party signers and the platform
        // bridge address (when the project admin has listed it here) pass this
        // check.
        if (!IController(peerTreasuryController).isOfficialEntityFast(KECCAK_THIRD_PARTY_REGISTRAR, recoveredRegistrar)) {
            revert TokenNotRegistered(); // Reuse error for "not a registered third-party"
        }
    }


    /**
     * @notice Check if ContentManager has at least one active email with string (not hash-only)
     * @dev Required for automated registration flow (CryptoRegistrar needs email to send confirmations)
     * @return hasActiveEmail True if at least one active email string exists
     * CHECK IssueToken's ContentManager directly!
     */


    /**
     * @notice Self-register for sales by signing certification message
     *
     * ⚠️ CRITICAL LEGAL DEFENSE:
     * The wallet (MetaMask, WalletConnect, Ledger, etc.) displays the FULL certification
     * message in plain text BEFORE the user signs. The user MUST explicitly read and
     * approve the message by clicking "Sign" in their wallet interface.
     *
     * This creates an IRON-CLAD legal defense against "I didn't know what I was signing":
     *   1. Wallet UI forces user to see full message
     *   2. User must actively click "Sign" button
     *   3. Signature cryptographically proves user owns private key
     *   4. Message is reconstructable in court via getRegistrationProof()
     *   5. On-chain data (emails, subscription hash, timestamp) verifies authenticity
     *
     * JavaScript example (frontend):
     *   const contentManager = await salesManager.getIssueTokenContentManager();
     *   const subscriptionHash = await contentManager.subscriptionAgreementHash();
     *   const chainName = "ETH"; // or derived from chainId like the UI does
     *   const message = await contentManager.buildCertificationMessage(
     *     userAddress,
     *     tokenAddress,
     *     timestamp,
     *     subscriptionHash,
     *     chainName
     *   );
     *   // MetaMask popup shows full message to user here ↓
     *   const signature = await ethereum.request({
     *     method: 'personal_sign',
     *     params: [message, userAddress]
     *   });
     *   await salesManager.selfRegisterForSales(signature, timestamp);
     *
     * DUAL REGISTRATION:
     * 1. ContentManager.registerUser() - Validates user's certification signature
     *    • USER PROVES: They read the token document and certification terms
     *    • Stores: User's signature, document hash, timestamp (for court verification)
     *    • Enables: Purchase eligibility (if isSalesRegistrationRequired)
     *
     * 2. IssueToken.whitelistUserWithRegKey() - Validates Registrar's authorization signature
     *    • REGISTRAR PROVES: They received an email from user containing:
     *      - Token address (in email title for tracking)
     *      - User's name, city, and identity details
     *      - Either the full terms document OR the document hash + URL
     *      - User's statement that they are accredited/eligible
     *    • Registrar signs: hash(userAddress + tokenAddress + isUS)
     *    • Enables: Token transfers (if gatingActive)
     *
     * SECURITY: Both signatures required, transaction reverts if either is invalid
     *
     * @dev Enforces isSalesSelfRegister policy, then registers in one or more systems
     * @notice Self-register for sales (user-initiated registration)
     * @param certificationSignature User's wallet signature certifying document review
     * @param timestamp Certification timestamp
     * @param isUS Whether user is US-based (for Token whitelist)
     * @param platformRegistrarQuestionnaireAndEmailVerifierSignature Platform Sig B (questionnaire
     *        attestation; mode 1 iff bit 6 ON). Empty when bit 4 AND bit 6 both OFF.
     * @param thirdPartyRegistrarSignature Third-party KYC registrar Sig A (or empty).
     * @param registrationNote User info for whitelist.
     *
     * @dev v43105: STEP 1 always registers in ContentManager (self-cert + optional
     *      Sig B). STEP 2 dispatches whitelist via bit 5 (third-party Sig A) or
     *      bit 22 (SaleManager-as-SmartContract auto-whitelist); else no write.
     */
    // v43105 ABI CHANGE: `platformWhitelistSignature` parameter REMOVED (platform
    // Sig A deprecated). Whitelist paths: third-party Sig A (bit 5), auto-whitelist
    // (bit 22), or admin Manual Whitelist.
    function selfRegisterForSales(
        bytes calldata certificationSignature,
        uint256 timestamp,
        bool isUS,
        bytes calldata platformRegistrarQuestionnaireAndEmailVerifierSignature,
        bytes calldata thirdPartyRegistrarSignature,
        bytes32 referredByEmailHash,
        bytes32 registrantEmailHash,
        bytes32 testamentHash,
        string calldata registrationNote,
        uint64 whitelistRegKeyExpiry
    ) public {
        // STEP 0: Optional referral allowlist enforcement
        // If referral is required (bit1), the referrer hash MUST be present, active,
        // AND its referral-use counter must be strictly below the configured max.
        // Atomic, paid by the registrant's own gas:
        //   1. Check active
        //   2. Check count < max  (or revert ReferralCapReached)
        //   3. Increment count    (so the 6th attempt sees count == max and reverts)
        // This is the ONLY place referralUseCount is mutated. View functions stay
        // view (eth_call cannot increment); the cap is reset only by TokenAdmin
        // raising maxReferralUseCount via setMaxReferralUseCount().
        if (_hasFlag(PF_REFERRAL_EMAIL_REQUIRED)) {
            if (referredByEmailHash == bytes32(0)) revert ReferrerRequired();
            if (!isReferrerEmailHashActive(referredByEmailHash)) revert ReferrerNotActive();
            if (referralUseCount[referredByEmailHash] >= maxReferralUseCount) revert ReferralCapReached();
            referralUseCount[referredByEmailHash] += 1;
        }
        // If referral expansion is allowed (bit2), auto-add registrant hash (if provided).
        if (_hasFlag(PF_REFERRAL_EXPANSION_ALLOWED) && registrantEmailHash != bytes32(0)) {
            if (!isReferrerEmailHashActive(registrantEmailHash)) {
                referrerEmailCombosPlusCodeOrKeyHashActiveTimes[registrantEmailHash].push(block.timestamp);
            }
        }

        // STEP 1: ContentManager registration (self-cert always required).
        // Sig B is the platform's questionnaire attestation; mode 1 iff bit 6 ON.
        address contentMgr = IIssueToken(issueTokenAddress).contentManager();
        bool questionnaireRequired              = _hasFlag(PF_QUESTIONNAIRE_REQUIRED);
        bool platformQuestionnaireEmailVerifier = _hasFlag(PF_PLATFORM_QUESTIONNAIRE_EMAIL_VERIFIER);

        // (bit 4 OR bit 6) forces non-empty Sig B. Both OFF = click-through mode
        // (Sig B empty, testamentHash = keccak256("")).
        if ((questionnaireRequired || platformQuestionnaireEmailVerifier)
            && platformRegistrarQuestionnaireAndEmailVerifierSignature.length == 0) revert NoRegistrarSignature();

        IIssueTokenContentManager(contentMgr).registerUser(
            msg.sender,
            issueTokenAddress,
            certificationSignature,
            timestamp,
            platformQuestionnaireEmailVerifier,
            platformRegistrarQuestionnaireAndEmailVerifierSignature,
            referredByEmailHash,
            testamentHash
        );

        // STEP 2: Whitelist dispatch (LAST behavior — PSTPR is server/modal-only).
        //   bit 5 + Sig A present  → third-party Sig A whitelist (platform-bridge
        //                            and direct-third-party signers BOTH flow
        //                            through this path; project admin's Controller
        //                            config decides which addresses qualify under
        //                            KECCAK_THIRD_PARTY_REGISTRAR).
        //   bit 22 + (bit 4 OR 6)  → SaleManager auto-whitelists via addWhitelistedUsers
        //   else                   → no write here (admin Manual Whitelist path)
        //
        // +- NOTE on the recovered Sig A signer (the ecRecover happens DOWNSTREAM
        // |   in IssueToken.whitelistUserWithRegKey; see L1297 there. SaleManager
        // |   does NOT call ecrecover directly — `whitelistRegister` consumes the
        // |   returned `recoveredSigner` and checks Controller membership): |
        // |                                                                 |
        // |   The only on-chain check applied to the recovered signer is    |
        // |     isOfficialEntityFast(KECCAK_THIRD_PARTY_REGISTRAR, signer)  |
        // |   on the PROJECT's own Controller. The platform's central       |
        // |   Registrar address (the one that satisfies                     |
        // |     Controller.isPlatformAdmin(signer, KECCAK_REGISTRAR) == true)|
        // |   IS NOT auto-trusted here. If the recovered Sig A signer were  |
        // |   the platform Registrar AND thirdPartyBridgeProviderId == 0    |
        // |   (PSTPR off) AND the project admin had not explicitly added    |
        // |   the platform address to their own Controller as a             |
        // |   KECCAK_THIRD_PARTY_REGISTRAR, the call would revert with      |
        // |   TokenNotRegistered (in whitelistRegister below).              |
        // |                                                                 |
        // |   This is by design and matches the deployment state on every   |
        // |   live project at the time of this revision: the platform       |
        // |   Registrar is NOT its own project-level THIRD_PARTY_REGISTRAR. |
        // |   It signs Sig A ONLY in bridge mode (PSTPR != 0), and only     |
        // |   then will a project admin have a reason to register the       |
        // |   platform-bridge address on their Controller as a              |
        // |   KECCAK_THIRD_PARTY_REGISTRAR. The provider context that       |
        // |   justifies the platform signing is embedded in `registrationNote`|
        // |   (`TPR:<providerId>:<slug>:<providerConfirmationId>:<utc>`),   |
        // |   whose keccak256 is part of the rawMessage signed by Sig A —   |
        // |   so the platform's attestation is cryptographically pinned to  |
        // |   the exact provider it consulted.                              |
        // +-----------------------------------------------------------------+
        // v43207 — gate restructure (~30–50 bytes vs the previous flat-and-bool
        // form). The earlier shape stored `thirdPartyPermitted`, `autoWhitelist`,
        // and `sigAPresent` as three locals, then guarded with redundant
        // compound checks (`!perm && sigA`, `perm && sigA`, `auto && (qReq || pQEV)`).
        // The branching tree below collapses to exactly two top-level cases —
        // "Sig A present" vs "no Sig A" — and inlines each `_hasFlag` lookup
        // at the one site where it matters. The behavior is provably identical
        // across all 8 input combinations of (permitted, sigAPresent, PSTPR≠0);
        // see the v43206 PSTPR rationale block above for the gating semantics.
        if (thirdPartyRegistrarSignature.length > 0) {
            // Sig A path — must be allowed by bit 5 (covers both directly-
            // attested third-party signers AND the platform-bridge address
            // when the project admin has listed it as KECCAK_THIRD_PARTY_REGISTRAR
            // on their Controller). PSTPR != 0 implicitly succeeds here too,
            // since the bridge endpoint only mints Sig A when PSTPR is set.
            if (!_hasFlag(PF_THIRD_PARTY_REGISTRAR_PERMITTED)) revert ThirdPartyWhitelistNotPermitted();
            whitelistRegister(isUS, thirdPartyRegistrarSignature, registrationNote, whitelistRegKeyExpiry);
        } else {
            // No Sig A — but if the TokenAdmin opted into platform-bridge KYC
            // (PSTPR != 0), Sig A IS required and we revert. Replaces the
            // pre-v43206 off-chain Sig-B hold in CryptoRegistrar.php STEP 6.65b.
            if (thirdPartyBridgeProviderId != 0) revert ThirdPartyBridgeSigRequired();
            // Manual auto-whitelist path: bit 22 + (bit 4 OR bit 6) required.
            if (_hasFlag(PF_AUTO_WHITELIST_ON_QUESTIONNAIRE_VALID)
                && (questionnaireRequired || platformQuestionnaireEmailVerifier)) {
                IIssueToken.WhitelistEntry[] memory entries = new IIssueToken.WhitelistEntry[](1);
                entries[0] = IIssueToken.WhitelistEntry({
                    user: msg.sender,
                    note: registrationNote,
                    isUS: isUS
                });
                IIssueToken(issueTokenAddress).addWhitelistedUsers(entries);
            }
        }
    }

    // ===========================================================================
    // DEPRECATED: adminApproveUser() and ContentManager.adminRegisterUser()
    // ===========================================================================
    // Reason: Self-cert is now MANDATORY for legal compliance (signature + fee + audit trail)
    // Manual mode: User self-certifies in ContentManager, then admin separately whitelists in IssueToken
    // This preserves legal protection while giving projects control over token transfers
    // ===========================================================================

    /**  getCertificationPreview(msg.sender,isueTokenAddress)
     * @notice Get certification message preview for current user
     * @return Certification message that would need to be signed
     * @dev Delegates to ContentManager   contenntMgs = IIsueToken(issueTokenAddress).contentManager()
     * USE IIssueTokenContentManager(ContentMgr).getCertificationPreview from IssueToken for this!
     */


    /**     CALl CONTENTMNAAGER dirctly to get registration proof!
     * @notice Get registration proof for court verification (delegates to ContentManager)
     * @param user User address to get proof for
     * @dev This function provides COMPLETE court-verifiable proof:
     *
     * 🏛️ COURT RECONSTRUCTION PROCESS:
     * 1. Contract retrieves stored signature + messageHash + timestamp from blockchain
     * 2. Contract queries ContentManager for emails active at that timestamp
     * 3. Contract rebuilds certification message using:
     *    - User's address (from function parameter)
     *    - Chain symbol (from block.chainid → _getChainName())
     *    - Active emails at timestamp (from ContentManager.officialEmailHistory)
     *    - Subscription hash (from ContentManager.subscriptionAgreementHash)
     *    - Original timestamp (from stored record)
     * 4. Rebuilt message is hashed and compared to stored hash (hashMatches)
     * 5. Signature is verified via ecrecover (isValid)
     *
     * If isValid=true AND hashMatches=true, this PROVES in court:
     *   ✓ User saw and approved the exact certification message
     *   ✓ User cryptographically signed with their private key
     *   ✓ Message content is verifiable via on-chain data
     *   ✓ User cannot claim "I didn't know what I signed"
     *
     * Example court usage:
     *   (msg, sig, valid, match) = salesManager.getRegistrationProof(defendant);
     *   // Display 'msg' to judge - shows what defendant certified
     *   // Show 'valid=true' - proves defendant's wallet signed it
     *   // Show 'match=true' - proves message hasn't been altered
     */
    /**
     * @notice Get registration proof for court verification
     * @param user User address to get proof for
     * @return message Reconstructed certification message
     * @return signature User's original signature
     * @return signatureValid Whether signature validates
     * @return tokenBindingValid Whether token→contentManager binding is valid
     * @return subscriptionHashValid Whether subscription hash is in ContentManager history
     *
     * Court verification process:
     * 1. Validates token.contentManager() matches expected ContentManager (IMMUTABLE)
     * 2. Confirms subscriptionHash was active at registration timestamp
     * 3. Reconstructs exact message user signed using STORED values
     * 4. Verifies signature against user's address
     *
     * ⚖️ TAMPER-PROOF: Even if malicious admin removes token from Controller,
     * this proof remains valid because it checks IMMUTABLE token→contentManager binding.
     */

    // ❌ COMMENTED OUT: receive() function removed for security
    //
    // REASON: This function allowed ETH to be sent directly to the contract without
    // triggering any purchase logic. This creates several problems:
    //
    // 1. SECURITY: Users could accidentally send ETH and NOT receive tokens
    // 2. CONFUSION: Users might think they purchased tokens when they didn't
    // 3. RISK: ETH could accumulate in contract without proper accounting
    // 4. UNNECESSARY: buyWithETH() is already payable and handles ETH correctly
    //
    // CORRECT USAGE: All ETH purchases MUST go through buyWithETH() which:
    // - Checks registration status
    // - Calculates token amount based on current price
    // - Distributes fees properly
    // - Transfers tokens to buyer
    // - Emits proper events
    // - Adds timelock if configured
    //
    // If a user sends ETH directly to this contract address, the transaction will
    // REVERT, protecting them from losing funds without receiving tokens.
    //
    // receive() external payable {}
}

// ============================================================================
//  IssueTokenSaleManagerInitializer — INITIALIZER SIDECAR (PROXY BUILD)
// ============================================================================
//  Carries the former constructor body of IssueTokenSaleManager so those
//  bytes count against THIS contract's EIP-170 budget, not the model's.
//  Deployed by the model's own constructor (`new` in IssueTokenSaleManager's
//  constructor), so its address is an immutable inside the model and NO
//  factory / PPAM / UI change is required. The model's initialize() stub
//  forwards msg.data here via delegatecall: the body executes against the
//  CLONE's storage with address(this) = clone and msg.sender = factory —
//  byte-identical semantics to the pre-sidecar build.
//
//  ⚠️ STORAGE LAYOUT CONTRACT (verified via solc storageLayout diff):
//  Same bases in the same order as the parent (ExecutivePeerTreasury slots
//  0..8, then CloneInitializable's _initState at slot 9), then a VERBATIM
//  prefix of the parent's own declarations up to the last slot the init body
//  touches (maxReferralUseCount, slot 31) — including the untouched fillers
//  in between, which are required for alignment:
//      slot 10        _MAX_DEC_STEP
//      slot 11        usdtAddress
//      slot 12        ethUsdPriceFeed (off 0) + fiatSymbol (off 20, packed)
//      slot 13        usdToFiatFeed
//      slots 14..30   paymentTokenInfo .. referralUseCount
//      slot 31        maxReferralUseCount
//  NEVER reorder, retype, or insert declarations here without re-diffing the
//  storage layouts of parent and sidecar.
contract IssueTokenSaleManagerInitializer is ExecutivePeerTreasury, CloneInitializable {

    /* ===== storage prefix (mirror of parent slots 10..31 after bases) ===== */
    uint256 private _MAX_DEC_STEP;
    address public usdtAddress;
    AggregatorV3Interface public ethUsdPriceFeed;
    bytes8 public fiatSymbol;
    AggregatorV3Interface public usdToFiatFeed;                               // filler — alignment only
    mapping(address => IssueTokenSaleManager.PaymentTokenInfo) public paymentTokenInfo;
    address[] public registeredPaymentTokens;
    uint32 public projectFlags;
    uint8 internal _usdToFiatFeedDecimals;                                    // filler — alignment only
    bool public saleActive;
    uint256 public startSaleBlockNum = 0;                                     // filler — alignment only
    uint256 public purchasePriceInFIAT;
    uint256 public totalTokensSold;                                           // filler — alignment only
    uint256 public totalPurchaserCount;                                       // filler — alignment only
    uint256 public minTokensPerPurchase;                                      // filler — alignment only
    uint256 public maxTokensPerPurchase;                                      // filler — alignment only
    uint256 public maxPurchasers;                                             // filler — alignment only
    IssueTokenSaleManager.PriceTier[] private priceTiers;                     // filler — alignment only
    mapping(address => uint256) public tokensSoldByPaymentToken;              // filler — alignment only
    mapping(address => uint256) public userPurchases;                         // filler — alignment only
    mapping(address => bool) private _salesApproved;                          // filler — alignment only
    mapping(bytes32 => uint256[]) private referrerEmailCombosPlusCodeOrKeyHashActiveTimes;   // filler
    mapping(bytes32 => uint256[]) private referrerEmailCombosPlusCodeOrKeyHashInactiveTimes; // filler
    mapping(bytes32 => uint256) public referralUseCount;                      // filler — alignment only
    uint256 public maxReferralUseCount;

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

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

    // ===== CLONE CONSTRUCTOR-EQUIVALENT (former constructor, verbatim) =====
    // Reached ONLY via the model stub's delegatecall (one-shot: the stub's
    // `initializer` modifier runs before delegating, so NO `initializer`
    // modifier here — the flag is already 1 in clone storage).
    /// @param _purchasePriceInUSD Initial price per token, IN USD, 18 decimals.
    ///        The deployer specifies USD because the contract boots in USD
    ///        (fiatSymbol="USD", usdToFiatFeed=address(0)). Internally this is
    ///        immediately written to the FIAT-named storage slot
    ///        (`purchasePriceInFIAT`) since at runtime the same number is
    ///        interpreted under whatever fiat is currently active.
    /// @dev v43105: removed `_usdcAddress` parameter. USDC payments (and any
    ///      other ERC20) are added post-deploy via addPaymentToken().
    function initialize(
        address _controller,
        address _issueTokenAddress,
        uint256 _purchasePriceInUSD,
        address _ethUsdPriceFeed,
        address _usdtUsdPriceFeed,
        address _stablecoinUsdPriceFeed,
        address _usdtAddress,
        address _feeManager
    ) external {
        if (address(this) == __SELF) revert DirectCallForbidden();

        // Parent constructor-equivalent (self-registers with Controller via init()):
        __ExecutivePeerTreasury_init(_controller, _feeManager, _issueTokenAddress, "IssueTokenSaleManager");

        maxReferralUseCount = 10; // ex-inline initializer (see declaration)

        // Validate token is registered as SmartContract in Controller
        if (!IController(_controller).isOfficialEntityFast(keccak256(bytes("SmartContract")), _issueTokenAddress)) {
            revert TokenNotRegistered();
        }
        if (_purchasePriceInUSD == 0) revert PriceZero();
        if (_feeManager == address(0)) revert FeeManagerZero();

        // NOTE: feeManager and issueTokenAddress already set by __ExecutivePeerTreasury_init

        // Cache the MAX_DECIMALS grid step at deploy-time. IssueToken's constructor
        // has already run (it's registered as a SmartContract entity in the
        // Controller above, which happens AFTER its constructor), so MAX_DECIMALS
        // is final. This single deploy-time read+EXP eliminates the runtime
        // external call + EXP inside _completePurchase, saving ~150-200 bytes off
        // the EIP-170 budget (constructor code is uncapped).
        {
            uint256 _md = IIssueToken(_issueTokenAddress).MAX_DECIMALS();
            _MAX_DEC_STEP = _md >= 18 ? 1 : 10 ** (18 - _md);
        }

        IController(_controller).addOfficialEntity("SalesTargetToken", _issueTokenAddress, "", "");
        ethUsdPriceFeed = AggregatorV3Interface(_ethUsdPriceFeed);
        // saleTokenStableCoin is set in PARENT to match issueToken
        usdtAddress = _usdtAddress;

        // CRITICAL: stableCoinAddress MUST be 6-decimal (USDC/USDT/EUROC) for fee distribution
        uint8 stableDecimals = ITokenDecimals(stableCoinAddress).decimals();
        if (stableDecimals != 6) revert StablecoinNot6Dec();

        // --- v43105 unified payment-token registry ---
        // saleStable is registered with usePermit=true (it MUST be EIP-2612 — issued by
        // the project's IssueToken which itself extends ERC20Permit).
        paymentTokenInfo[stableCoinAddress] = IssueTokenSaleManager.PaymentTokenInfo({
            feed:          AggregatorV3Interface(_stablecoinUsdPriceFeed),
            feedDecimals:  8, // Chainlink standard for X/USD feeds wired in constructor
            tokenDecimals: stableDecimals,
            usePermit:     true
        });
        registeredPaymentTokens.push(stableCoinAddress);

        // USDT is registered with usePermit=false (mainnet USDT is NOT EIP-2612).
        paymentTokenInfo[_usdtAddress] = IssueTokenSaleManager.PaymentTokenInfo({
            feed:          AggregatorV3Interface(_usdtUsdPriceFeed),
            feedDecimals:  8,
            tokenDecimals: ITokenDecimals(_usdtAddress).decimals(),
            usePermit:     false
        });
        registeredPaymentTokens.push(_usdtAddress);

        // Deployer specifies USD; contract stores it in the FIAT-named slot
        // because at runtime that number is reinterpreted under the active fiat.
        purchasePriceInFIAT = _purchasePriceInUSD;
        saleActive = false;
        // Default fiat = USD (right-padded ASCII in bytes8). usdToFiatFeed stays
        // address(0), which means "fiat IS USD; skip the bridge oracle".
        fiatSymbol = bytes8("USD");

        // Default policy flags (Reg D 506(b)-leaning, strictest posture):
        //   ON:  bits 0,1,3,4,6,7,9,14,15,16,18  => 0x0005C2DB
        //   OFF (admin must opt in): 5 (third-party Sig A), 22 (auto-whitelist),
        //                            24, 25, 26, 30 (no platform-side private
        //                            data retention by default), 31.
        // Mirrored client-side as the legacy default for SaleManagers that don't
        // expose projectFlags(). See flags.js for flag-by-flag semantics.
        projectFlags =
            (uint32(1) << 0)  |
            (uint32(1) << 1)  |
            (uint32(1) << 3)  |
            (uint32(1) << 4)  |
            (uint32(1) << 6)  |
            (uint32(1) << 7)  |
            (uint32(1) << 9)  |
            (uint32(1) << 14) |
            (uint32(1) << 15) |
            (uint32(1) << 16) |
            (uint32(1) << 18);
    }
}

@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 ⚠️ 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);
    function isOfficialEntityPlusNotEntityFast(bytes32, address, bytes32, address, bool) external view returns (bool);
    function isOfficialDoubleEntityFast(bytes32, address, bytes32, address, bool) external view returns (bool);
    function isOfficialTripleEntityFast(bytes32, address, bytes32, address, bytes32, address, bool) external view returns (bool);
    function isOfficialQuadrupleEntityFast(bytes32, address,  bytes32, address, bytes32, address, bytes32, address, bool) external view returns (bool);
    function getOfficialEntity(string calldata, address) external view returns (OfficialEntityStruct memory);
    function getAllOfficialEntities(string calldata, bool) external view returns (OfficialEntityStruct[] memory);
    function init(address, string calldata) external;
    function openInit() external returns (bool);
    function closeInit() external returns (bool);
    function getEntityCount(bytes32) external view returns (uint256);

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

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

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

interfaces/IFeeManager.sol

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

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

    struct CalculatedEntityAmount {
        address entityAddress;
        uint256 amount;
    }

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

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

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

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

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.