Skip to content
Verified contractPartialUNLICENSED

PlatformChainTreasury

Address0x375df084b744ea578df310336256269ca481be95
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 7,000 runs
Via IR
yes
License
UNLICENSED
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
23,910,015
Creation transaction
0x22c6d40c02…9c4bb51560

contracts/PlatformChainTreasury.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright 2025 US Fintech LLC and DelNorte Holdings.
// 
// Permission to use, copy, modify, or distribute this software is strictly prohibited
// without prior written consent from either copyright holder.
// 
// 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.
// OFFICIAL DEL NORTE NETWORK COMPONENT
// Platform Chain Treasury - Accumulates platform fees and coordinates liquidity provisioning + buybacks
// Designed by Ken Silverman as part of the EquityMint tokenomics model
// @author Ken Silverman
pragma solidity 0.8.30;

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

/**
 * @title PlatformChainTreasury
 * @notice Special treasury that accumulates platform fees and coordinates:
 *         Phase 1: Liquidity provisioning (via LiquidityProvider) to stabilize price
 *         Phase 2: Token buybacks to push price higher
 * @dev This contract should be added to the Controller as PLATFORM_CHAIN_TREASURY entity
 *      It implements automatic buyback without requiring tokens to be aware of the mechanism
 *      Only registered SmartContracts in Controller can send fees to this treasury
 *      Uses "fresh pool" tracking - buyback percentage applies to fees since last buyback
 *      Uses CEI (Checks-Effects-Interactions) pattern for reentrancy safety
 */
contract PlatformChainTreasury is ExecutivePeerTreasury {
    using SafeERC20 for IERC20;

    /* ========== CUSTOM ERRORS ========== */
    
    error InvalidTokenAddress();
    error InvalidController();
    error ThresholdMustBePositive();
    error ThresholdTooLow();
    error InvalidPercentage();
    error InvalidAddress();
    error LPNotRegistered();
    error LPQueryFailed();
    error InternalOnly();
    error NoPoolConfigured();
    error NoFreshPool();
    error PoolNotRegistered();
    error InvalidPoolTokens();
    error InsufficientOutput();
    error NoTokensReceived();
    error ETHNotImplemented();
    error NotApprovedStablecoin();
    error InvalidPoolToken0();
    error InvalidPoolToken1();
    error FeeStructureUpdateFailed();

    /* ========== STATE VARIABLES ========== */
    
    address public immutable targetTokenAddress; // Token to buy back (e.g., EMINT)
    
    // LP coordination for two-phase liquidity + buyback
    address public liquidityProviderAddress; // Optional LP coordinator
    
    // Hysteresis threshold - triggers when "fresh pool" exceeds this
    uint256 public buybackThreshold = 5000e18; // $5,000 in 18 decimals
    
    // Buyback percentage (30% = 3000 basis points) - applies to FRESH POOL only
    uint256 public buybackPercentageBps = 3000; // 30%
    uint256 public constant BASIS_POINTS = 10000;
    uint256 public constant MAX_BUYBACK_PCT = 5000; // Max 50%
    
    // Approved stablecoin symbols (works across all chains)
    mapping(bytes32 => bool) public approvedStablecoinSymbols;
    
    // Common stablecoin symbol hashes (keccak256)
    bytes32 public constant USDC_HASH = keccak256(bytes("USDC"));
    bytes32 public constant USDT_HASH = keccak256(bytes("USDT"));
    bytes32 public constant DAI_HASH = keccak256(bytes("DAI"));
    bytes32 public constant BUSD_HASH = keccak256(bytes("BUSD"));
    bytes32 public constant FRAX_HASH = keccak256(bytes("FRAX"));
    bytes32 public constant TUSD_HASH = keccak256(bytes("TUSD"));
    
    // Fee cycle tracking and "fresh pool" management
    uint256 public feeReceivedCounter;              // Total number of fee receipts
    uint256 public lastBuybackCounter;              // feeReceivedCounter when last buyback occurred
    uint256 public freshPoolAmount;                 // "Fresh pool" - fees accumulated since last buyback
    uint256 public constant MIN_FEE_CYCLES_BEFORE_BUYBACK = 3; // Wait 3 cycles if LP stuck

    // LP coordination state
    uint256 public lastLPPoolTotal;                 // Last known LP total liquidity provided
    uint256 public lastLPCheckCounter;              // Last time we checked LP pool total
    
    /* ========== EVENTS ========== */
    
    event FeeReceived(address indexed from, address indexed token, uint256 amount);
    event FeeReceivedCycle(uint256 cycle, uint256 amount, uint256 freshPool);
    event LiquidityProvisioningTriggered(bool success, uint256 lpTotal);
    event BuybackConditionsMet(string reason, uint256 amount, uint256 cycles);
    event BuybackExecuted(
        address indexed token,
        uint256 amountIn,
        uint256 tokensReceived,
        uint256 remaining
    );
    event FreshPoolReset(uint256 used, uint256 remaining);
    event BuybackThresholdUpdated(uint256 newThreshold);
    event BuybackPercentageUpdated(uint256 newPercentageBps);
    event BuybackFailed(address indexed token, uint256 amount, string reason);
    event StablecoinApproved(string symbol, bool approved);
    event LiquidityProviderSet(address indexed liquidityProvider);
    
    /* ========== MODIFIERS ========== */
    
    modifier onlySmartContract() {
        if (!IController(peerTreasuryController).isOfficialEntity("SmartContract", msg.sender))
            revert PoolNotRegistered();
        _;
    }
    
    /* ========== CONSTRUCTOR ========== */
    
    constructor(
        address _controller,
        address _targetTokenAddress,
        address _liquidityProvider // NEW: Optional LP address for two-phase coordination
    ) ExecutivePeerTreasury(_controller, "PlatformChainTreasury") {
        if (_targetTokenAddress == address(0)) revert InvalidTokenAddress();
        targetTokenAddress = _targetTokenAddress;
        liquidityProviderAddress = _liquidityProvider; // Can be address(0) if no LP
        
        // Initialize approved stablecoins (works across all chains)
        approvedStablecoinSymbols[USDC_HASH] = true;
        approvedStablecoinSymbols[USDT_HASH] = true;
        approvedStablecoinSymbols[DAI_HASH] = true;
        approvedStablecoinSymbols[BUSD_HASH] = true;
        approvedStablecoinSymbols[FRAX_HASH] = true;
        approvedStablecoinSymbols[TUSD_HASH] = true;
        
        // Note: Liquidity pool is now fetched dynamically from LiquidityProvider via getTokenLiquidityPool()
    }
    
    /* ========== ADMIN FUNCTIONS ========== */
    
    /**
     * @notice Set the threshold for automatic buyback trigger
     * @param newThreshold New threshold in 18 decimals (e.g., 5000e18 = $5,000)
     */
    function setBuybackThreshold(uint256 newThreshold) external onlyTreasuryAdmin {
        if (newThreshold == 0) revert ThresholdMustBePositive();
        if (newThreshold < 1000e18) revert ThresholdTooLow();
        buybackThreshold = newThreshold;
        emit BuybackThresholdUpdated(newThreshold);
    }
    
    /**
     * @notice Set the percentage of fresh pool to use for buyback
     * @param newPercentageBps New percentage in basis points (3000 = 30%)
     */
    function setBuybackPercentage(uint256 newPercentageBps) external onlyTreasuryAdmin {
        if (newPercentageBps == 0 || newPercentageBps > MAX_BUYBACK_PCT) revert InvalidPercentage();
        buybackPercentageBps = newPercentageBps;
        emit BuybackPercentageUpdated(newPercentageBps);
    }
    
    /**
     * @notice Add or remove approved stablecoin symbol
     * @param symbol Stablecoin symbol (e.g., "USDC", "USDT")
     * @param approved true to approve, false to remove
     * @dev Works across all chains - symbols are universal
     */
    function setApprovedStablecoin(string calldata symbol, bool approved) external onlyTreasuryAdmin {
        bytes32 symbolHash = keccak256(bytes(symbol));
        approvedStablecoinSymbols[symbolHash] = approved;
        emit StablecoinApproved(symbol, approved);
    }
    
    /**
     * @notice Set or update LP coordinator address
     * @param _liquidityProvider LP address (address(0) to disable coordination)
     */
    function setLiquidityProvider(address _liquidityProvider) external onlyTreasuryAdmin {
        if (_liquidityProvider != address(0)) {
            if (!IController(peerTreasuryController).isOfficialEntity("SmartContract", _liquidityProvider))
                revert LPNotRegistered();
        }
        liquidityProviderAddress = _liquidityProvider;
        emit LiquidityProviderSet(_liquidityProvider);
    }
    
    /**
     * @notice Sync LP pool total to current value
     * @dev Useful for initialization or reset after manual operations
     */
    function syncLPPoolTotal() external onlyTreasuryAdmin {
        if (liquidityProviderAddress != address(0)) {
            try ILiquidityProvider(liquidityProviderAddress).totalLiquidityProvided() returns (uint256 total) {
                lastLPPoolTotal = total;
                lastLPCheckCounter = feeReceivedCounter;
            } catch {
                revert LPQueryFailed();
            }
        }
    }
    
    /**
     * @notice Reset fresh pool counter (emergency use)
     * @dev Useful if buyback needs to be skipped/reset
     */
    function resetFreshPool() external onlyTreasuryAdmin {
        uint256 oldAmount = freshPoolAmount;
        freshPoolAmount = 0;
        emit FreshPoolReset(oldAmount, 0);
    }
    
    
    /**
     * @notice Update this treasury's fee structure in an external Controller
     * @dev Allows platform treasury admin to adjust fees in token Controllers where this treasury is a root entity
     *      msg.sender becomes address(this), so the external Controller sees the treasury updating itself
     *      Works because root entities can always update their own values (Controller line ~564)
     * @param targetController The Controller contract where this treasury is registered
     * @param chainType The chain type (usually "PLATFORM_CHAIN_TREASURY")
     * @param type1 Fee type for type1 (0='V' value, 1='P' percentage)
     * @param val1 Value for type1
     * @param type2 Fee type for type2 (0='V' value, 1='P' percentage)
     * @param val2 Value for type2
     * @param type3 Fee type for type3 (0='V' value, 1='P' percentage)
     * @param val3 Value for type3
     * @param entityName Human-readable name for the entity
     * @param entityID Additional identifier (optional)
     */
    function updateMyFeeStructure(
        address targetController,
        string calldata chainType,
        uint8 type1,
        uint256 val1,
        uint8 type2,
        uint256 val2,
        uint8 type3,
        uint256 val3,
        string calldata entityName,
        string calldata entityID
    ) external onlyTreasuryAdmin {
        if (targetController == address(0)) revert InvalidController();
        
        // Call the external Controller as address(this) - the treasury contract itself
        // The external Controller will see: msg.sender == newEntity == root entity
        // This allows self-update per Controller's rules
        IController.EntityFeesWithNames memory entity;
        entity.entityAddress = address(this);
        entity.parent = address(0);  // Root node
        entity.val1 = val1;
        entity.val2 = val2;
        entity.val3 = val3;
        entity.valDetailFlags = type1 | (type2 << 2) | (type3 << 4);
        entity.locked = false;  // Default: not locked for updates
        entity.entityName = entityName;
        entity.entityID = entityID;
        
        if (!IController(targetController).addChainedEntity(chainType, entity)) 
            revert FeeStructureUpdateFailed();
    }
    
    /**
     * @notice Get current primary liquidity pool from LiquidityProvider
     * @return pool Primary liquidity pool address (or address(0) if none set)
     * @dev Fetches pool dynamically from LiquidityProvider each time
     */
    function getTokenLiquidityPool() public view returns (address pool) {
        if (liquidityProviderAddress == address(0)) {
            return address(0);
        }
        return ILiquidityProvider(liquidityProviderAddress).primaryLiquidityPool();
    }
    
    /* ========== CORE FUNCTIONALITY ========== */
    
    /**
     * @notice Receive fee payment in ETH or ERC20 from registered SmartContracts only
     * @param token Address of fee token (address(0) for ETH)
     * @param amount Amount of fee (ignored for ETH, uses msg.value)
     * @dev Only registered SmartContracts in Controller can call this
     *      Tracks "fresh pool" - fees accumulated since last buyback
     *      Does NOT automatically trigger buyback - call triggerBuybackCheck() externally
     */
    function receiveFee(address token, uint256 amount) external payable onlySmartContract {
        uint256 feeAmount;
        
        if (token == address(0)) {
            // ETH fee
            if (msg.value == 0) revert InvalidPercentage();
            feeAmount = msg.value;
        } else {
            // ERC20 fee
            if (amount == 0) revert InvalidPercentage();
            if (msg.value != 0) revert InvalidPercentage();
            
            // Transfer tokens from sender
            uint256 balanceBefore = IERC20(token).balanceOf(address(this));
            IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
            uint256 balanceAfter = IERC20(token).balanceOf(address(this));
            
            feeAmount = balanceAfter - balanceBefore; // Actual amount received (handles fee-on-transfer tokens)
        }
        
        // Track fee cycle and "fresh pool"
        feeReceivedCounter++;
        freshPoolAmount += feeAmount; // Accumulate in fresh pool
        
        emit FeeReceived(msg.sender, token, feeAmount);
        emit FeeReceivedCycle(feeReceivedCounter, feeAmount, freshPoolAmount);
        
        // ExecutivePeerTreasury will track this in its internal accounting
        // Note: We don't trigger buyback here - let external callers coordinate timing
    }
    
    /**
     * @notice Fallback to reject direct ETH sends
     * @dev Must use receiveFee() instead
     */
    receive() external payable {
        revert InvalidPercentage();
    }
    
    /**
     * @notice Manually trigger buyback check for a specific token
     * @param token Token address (address(0) for ETH)
     * @dev Can be called by ANYONE - useful for keeper bots or manual triggers
     *      This is the PUBLIC entry point for coordinated LP+buyback flow
     */
    function triggerBuybackCheck(address token) external {
        _coordinatedLiquidityAndBuyback(token);
    }
    
    /**
     * @notice Trigger buyback checks for multiple tokens
     * @param tokens Array of token addresses to process
     * @dev Can be called by ANYONE
     */
    function triggerBuybackChecks(address[] calldata tokens) external {
        for (uint256 i = 0; i < tokens.length; i++) {
            _coordinatedLiquidityAndBuyback(tokens[i]);
        }
    }
    
    /**
     * @notice Force buyback (bypasses threshold and LP coordination) - FOR TESTING
     * @param token Token to use for buyback
     * @dev Only TreasuryAdmin can force
     *      Uses current freshPoolAmount, then resets it
     *      Useful for testing or emergency situations
     */
    function forceBuyback(address token) external onlyTreasuryAdmin returns (bool success) {
        address tokenLiquidityPool = getTokenLiquidityPool();
        if (tokenLiquidityPool == address(0)) revert NoPoolConfigured();
        if (freshPoolAmount == 0) revert NoFreshPool();
        
        // Calculate buyback amount from fresh pool
        uint256 buybackAmount = (freshPoolAmount * buybackPercentageBps) / BASIS_POINTS;
        
        if (buybackAmount == 0) {
            return false;
        }
        
        // Verify sufficient balance
        uint256 currentBalance;
        if (token == address(0)) {
            currentBalance = address(this).balance;
        } else {
            currentBalance = IERC20(token).balanceOf(address(this));
        }
        
        if (currentBalance < buybackAmount) {
            return false; // Not enough balance
        }
        
        // Execute buyback (bypass LP coordination)
        try this.executeBuyback(token, buybackAmount) returns (uint256 emintReceived) {
            // Success - reset fresh pool
            uint256 usedFromFreshPool = freshPoolAmount;
            freshPoolAmount = 0; // RESET
            lastBuybackCounter = feeReceivedCounter;
            
            uint256 remainingBalance;
            if (token == address(0)) {
                remainingBalance = address(this).balance;
            } else {
                remainingBalance = IERC20(token).balanceOf(address(this));
            }
            
            emit BuybackExecuted(token, buybackAmount, emintReceived, remainingBalance);
            emit FreshPoolReset(usedFromFreshPool, remainingBalance);
            
            return true;
        } catch {
            return false;
        }
    }
    
    /* ========== INTERNAL FUNCTIONS ========== */
    
    /**
     * @notice Coordinated liquidity provisioning and buyback system
     * @param token Token address (address(0) for ETH)
     * @dev Phase 1: Trigger LP liquidity provisioning (if LP configured)
     *      Phase 2: Execute buyback using percentage of "fresh pool" ONLY IF:
     *        - LP provision succeeded, OR
     *        - LP hasn't increased pool total in 3+ fee cycles AND we're past threshold
     *      Buyback uses percentage (e.g., 30%) of freshPoolAmount (fees since last buyback)
     *      After buyback, freshPoolAmount resets to 0 while treasury continues to hold funds
     */
    function _coordinatedLiquidityAndBuyback(address token) internal {
        // Check if fresh pool meets threshold
        if (freshPoolAmount < buybackThreshold) {
            return; // Threshold not met
        }
        
        // Check if liquidity pool is set for buyback (fetch from LP dynamically)
        address tokenLiquidityPool = getTokenLiquidityPool();
        if (tokenLiquidityPool == address(0)) {
            return; // No pool configured
        }
        
        bool canProceedToBuyback = false;
        string memory buybackReason = "";
        
        // PHASE 1: Try to trigger LP liquidity provisioning first
        if (liquidityProviderAddress != address(0)) {
            // Verify LP is registered SmartContract
            if (IController(peerTreasuryController).isOfficialEntity("SmartContract", liquidityProviderAddress)) {
                try ILiquidityProvider(liquidityProviderAddress).triggerLiquidityCheck() {
                    // LP trigger succeeded - check if pool total increased
                    try ILiquidityProvider(liquidityProviderAddress).totalLiquidityProvided() returns (uint256 currentLPTotal) {
                        
                        if (currentLPTotal > lastLPPoolTotal) {
                            // LP successfully added liquidity - we can proceed to buyback
                            canProceedToBuyback = true;
                            buybackReason = "LP provision successful";
                            lastLPPoolTotal = currentLPTotal;
                            lastLPCheckCounter = feeReceivedCounter;
                            emit LiquidityProvisioningTriggered(true, currentLPTotal);
                        } else {
                            // LP didn't add liquidity - check if we're past 3 cycles
                            uint256 cyclesSinceLastLPIncrease = feeReceivedCounter - lastLPCheckCounter;
                            
                            if (cyclesSinceLastLPIncrease >= MIN_FEE_CYCLES_BEFORE_BUYBACK) {
                                // LP stuck for 3+ cycles - proceed to buyback anyway
                                canProceedToBuyback = true;
                                buybackReason = "LP stuck for 3+ cycles";
                                emit LiquidityProvisioningTriggered(false, currentLPTotal);
                            }
                        }
                    } catch {
                        // Can't read LP total - check cycles since last buyback
                        uint256 cyclesSinceLastBuyback = feeReceivedCounter - lastBuybackCounter;
                        if (cyclesSinceLastBuyback >= MIN_FEE_CYCLES_BEFORE_BUYBACK) {
                            canProceedToBuyback = true;
                            buybackReason = "LP query failed, 3+ cycles elapsed";
                        }
                    }
                } catch {
                    // LP trigger failed - check cycles
                    uint256 cyclesSinceLastBuyback = feeReceivedCounter - lastBuybackCounter;
                    if (cyclesSinceLastBuyback >= MIN_FEE_CYCLES_BEFORE_BUYBACK) {
                        canProceedToBuyback = true;
                        buybackReason = "LP trigger failed, 3+ cycles elapsed";
                    }
                }
            } else {
                // LP not registered - proceed without coordination
                canProceedToBuyback = true;
                buybackReason = "No LP coordination (not registered)";
            }
        } else {
            // No LP configured - proceed directly to buyback
            canProceedToBuyback = true;
            buybackReason = "No LP configured";
        }
        
        // PHASE 2: Execute buyback if conditions met
        if (!canProceedToBuyback) {
            return; // Wait for LP or more cycles
        }
        
        // Calculate buyback amount: percentage of FRESH POOL (not total treasury balance)
        uint256 buybackAmount = (freshPoolAmount * buybackPercentageBps) / BASIS_POINTS;
        
        if (buybackAmount == 0) {
            return;
        }
        
        // Verify we have sufficient balance for buyback
        uint256 currentBalance;
        if (token == address(0)) {
            currentBalance = address(this).balance;
        } else {
            currentBalance = IERC20(token).balanceOf(address(this));
        }
        
        if (currentBalance < buybackAmount) {
            return; // Not enough balance (shouldn't happen but safety check)
        }
        
        emit BuybackConditionsMet(
            buybackReason, 
            buybackAmount, 
            feeReceivedCounter - lastBuybackCounter
        );
        
        // Try to execute buyback
        try this.executeBuyback(token, buybackAmount) returns (uint256 emintReceived) {
            // Success - reset "fresh pool" and update counters
            uint256 usedFromFreshPool = freshPoolAmount; // Store for event
            freshPoolAmount = 0; // RESET fresh pool to zero
            lastBuybackCounter = feeReceivedCounter;
            
            // Treasury balance continues to hold remaining funds
            uint256 remainingBalance;
            if (token == address(0)) {
                remainingBalance = address(this).balance;
            } else {
                remainingBalance = IERC20(token).balanceOf(address(this));
            }
            
            emit BuybackExecuted(
                token,
                buybackAmount,
                emintReceived,
                remainingBalance
            );
            emit FreshPoolReset(usedFromFreshPool, remainingBalance);
        } catch Error(string memory reason) {
            emit BuybackFailed(token, buybackAmount, reason);
        } catch {
            emit BuybackFailed(token, buybackAmount, "Unknown error");
        }
    }
    
    /**
     * @notice Execute the actual buyback by swapping directly with the Uniswap V2 pool
     * @param token Token to use for buyback (address(0) for ETH, or stablecoin address)
     * @param amount Amount to use for buyback
     * @return tokensReceived Amount of target tokens received
     * @dev Must be external to use try/catch pattern
     *      Pool must be the registered tokenLiquidityPool and a SmartContract in Controller
     *      This uses Uniswap V2 pair.swap() directly for gas efficiency
     */
    function executeBuyback(address token, uint256 amount) external returns (uint256 tokensReceived) {
        if (msg.sender != address(this)) revert InternalOnly();
        address tokenLiquidityPool = getTokenLiquidityPool();
        if (tokenLiquidityPool == address(0)) revert NoPoolConfigured();
        
        // Verify pool is still registered as SmartContract
        if (!IController(peerTreasuryController).isOfficialEntity("SmartContract", tokenLiquidityPool))
            revert PoolNotRegistered();
        
        // Get pool token addresses
        IUniswapV2Pair pool = IUniswapV2Pair(tokenLiquidityPool);
        address token0 = pool.token0();
        address token1 = pool.token1();
        
        // Determine which token is target token and which is the payment token
        bool targetIsToken0 = (token0 == targetTokenAddress);
        if (!((targetIsToken0 && token1 == token) || (!targetIsToken0 && token0 == token)))
            revert InvalidPoolTokens();
        
        // Record target token balance before swap
        uint256 balanceBefore = IERC20(targetTokenAddress).balanceOf(address(this));
        
        // Transfer payment token to pool
        if (token == address(0)) {
            revert ETHNotImplemented();
        } else {
            IERC20(token).safeTransfer(tokenLiquidityPool, amount);
        }
        
        // Get reserves and calculate expected output
        (uint112 reserve0, uint112 reserve1,) = pool.getReserves();
        uint256 amountOut;
        
        if (targetIsToken0) {
            // Buying target token (token0) with payment token (token1)
            amountOut = getAmountOut(amount, uint256(reserve1), uint256(reserve0));
        } else {
            // Buying target token (token1) with payment token (token0)
            amountOut = getAmountOut(amount, uint256(reserve0), uint256(reserve1));
        }
        
        if (amountOut == 0) revert InsufficientOutput();
        
        // Execute swap
        if (targetIsToken0) {
            pool.swap(amountOut, 0, address(this), ""); // Get token0 (target)
        } else {
            pool.swap(0, amountOut, address(this), ""); // Get token1 (target)
        }
        
        // Calculate target tokens received
        uint256 balanceAfter = IERC20(targetTokenAddress).balanceOf(address(this));
        tokensReceived = balanceAfter - balanceBefore;
        
        if (tokensReceived == 0) revert NoTokensReceived();
        
        // ✅ Auto-transfer bought-back tokens to IssueToken contract (removes from circulation)
        // This is the cleanest way to track bought-back tokens - they're automatically verifiable
        // as "out of circulation" by checking IssueToken's own balance
        IERC20(targetTokenAddress).safeTransfer(targetTokenAddress, tokensReceived);
        
        return tokensReceived;
    }
    
    /**
     * @notice Calculate amount out for Uniswap V2 swap (x * y = k formula)
     * @param amountIn Amount of input token
     * @param reserveIn Reserve of input token
     * @param reserveOut Reserve of output token
     * @return amountOut Amount of output token
     */
    function getAmountOut(
        uint256 amountIn,
        uint256 reserveIn,
        uint256 reserveOut
    ) internal pure returns (uint256 amountOut) {
        if (amountIn == 0) revert InvalidPercentage();
        if (reserveIn == 0 || reserveOut == 0) revert InsufficientOutput();
        
        uint256 amountInWithFee = amountIn * 997; // 0.3% fee
        uint256 numerator = amountInWithFee * reserveOut;
        uint256 denominator = (reserveIn * 1000) + amountInWithFee;
        amountOut = numerator / denominator;
    }
    
    /* ========== VIEW FUNCTIONS ========== */
    
    /**
     * @notice Get fresh pool statistics
     * @return freshPool Current fresh pool amount
     * @return cyclesSinceLastBuyback Number of fee cycles since last buyback
     * @return canTriggerBuyback Whether buyback can be triggered now
     */
    function getFreshPoolStats() external view returns (
        uint256 freshPool,
        uint256 cyclesSinceLastBuyback,
        bool canTriggerBuyback
    ) {
        freshPool = freshPoolAmount;
        cyclesSinceLastBuyback = feeReceivedCounter - lastBuybackCounter;
        canTriggerBuyback = (freshPoolAmount >= buybackThreshold && getTokenLiquidityPool() != address(0));
        
        return (freshPool, cyclesSinceLastBuyback, canTriggerBuyback);
    }
    
    /**
     * @notice Check if a token has enough fresh pool to trigger buyback
     * @param token Token address to check (address(0) for ETH)
     * @return canBuyback true if threshold is met
     * @return currentFreshPool Current fresh pool amount
     * @return amountOver How much over the threshold
     */
    function canTriggerBuyback(address token) external view returns (
        bool canBuyback,
        uint256 currentFreshPool,
        uint256 amountOver
    ) {
        currentFreshPool = freshPoolAmount;
        
        if (currentFreshPool >= buybackThreshold) {
            return (true, currentFreshPool, currentFreshPool - buybackThreshold);
        }
        return (false, currentFreshPool, 0);
    }
    
    /**
     * @notice Get the amount that would be used for buyback if triggered now
     * @param token Token address
     * @return buybackAmount Amount that would be used for buyback (from fresh pool)
     * @return remainingFreshPool Amount that would remain in fresh pool
     */
    function getPendingBuybackAmount(address token) external view returns (
        uint256 buybackAmount,
        uint256 remainingFreshPool
    ) {
        if (freshPoolAmount < buybackThreshold) {
            return (0, freshPoolAmount);
        }
        
        buybackAmount = (freshPoolAmount * buybackPercentageBps) / BASIS_POINTS;
        remainingFreshPool = 0; // Fresh pool resets after buyback
    }
    
    /**
     * @notice Get current target token balance held by treasury
     * @return balance Target token balance
     */
    function getTargetTokenBalance() external view returns (uint256 balance) {
        return IERC20(targetTokenAddress).balanceOf(address(this));
    }
    
    /**
     * @notice Get current balance of a specific token
     * @param token Token address (address(0) for ETH)
     * @return balance Token balance
     */
    function getTokenBalance(address token) external view returns (uint256 balance) {
        if (token == address(0)) {
            return address(this).balance;
        }
        return IERC20(token).balanceOf(address(this));
    }
    
    /**
     * @notice Get held assets waiting for buyback (orphaned until buyback conditions met)
     * @return assets Array of token addresses with non-zero balances
     * @return balances Array of corresponding balances
     */
    function getOrphanedAssets() external view returns (
        address[] memory assets,
        uint256[] memory balances
    ) {
        // Returns known assets: targetToken + common stablecoins
        assets = new address[](2);
        balances = new uint256[](2);
        
        assets[0] = targetTokenAddress;
        assets[1] = address(0); // ETH
        
        balances[0] = targetTokenAddress != address(0) ? IERC20(targetTokenAddress).balanceOf(address(this)) : 0;
        balances[1] = address(this).balance;
        
        return (assets, balances);
    }
    
    /**
     * @notice Get pool for buyback (must contain targetToken)
     * @param assetToSell Token we're selling (USDC, ETH, etc)
     * @return pool Pool address for buyback (or address(0) if none)
     */
    function getBuybackPool(address assetToSell) public view returns (address pool) {
        // Query Controller for SmartContract entities (potential pools)
        IController.OfficialEntityStruct[] memory entities = IController(peerTreasuryController).getAllOfficialEntities("SmartContract", false);
        
        for (uint i = 0; i < entities.length; i++) {
            address entity = entities[i].pubAddress;
            try IUniswapV2Pair(entity).token0() returns (address token0) {
                try IUniswapV2Pair(entity).token1() returns (address token1) {
                    // Find pool with (assetToSell, targetToken)
                    if ((token0 == assetToSell && token1 == targetTokenAddress) ||
                        (token1 == assetToSell && token0 == targetTokenAddress)) {
                        return entity;
                    }
                } catch {}
            } catch {}
        }
        return address(0); // No pool found
    }
    
    /**
     * @notice Get all active pools that contain targetToken for buybacks
     * @return pools Array of pool addresses
     * @return token0Symbols Array of token0 symbols
     * @return token1Symbols Array of token1 symbols
     * @return token0Addresses Array of token0 addresses
     * @return token1Addresses Array of token1 addresses
     */
    function getActivePools() external view returns (
        address[] memory pools,
        string[] memory token0Symbols,
        string[] memory token1Symbols,
        address[] memory token0Addresses,
        address[] memory token1Addresses
    ) {
        // Query Controller for SmartContract entities (potential pools)
        IController.OfficialEntityStruct[] memory entities = IController(peerTreasuryController).getAllOfficialEntities("SmartContract", false);
        
        // First pass: Count valid pools
        uint256 count = 0;
        for (uint i = 0; i < entities.length; i++) {
            address entity = entities[i].pubAddress;
            try IUniswapV2Pair(entity).token0() returns (address token0) {
                try IUniswapV2Pair(entity).token1() returns (address token1) {
                    // Only count pools containing targetToken
                    if (token0 == targetTokenAddress || token1 == targetTokenAddress) {
                        count++;
                    }
                } catch {}
            } catch {}
        }
        
        // Allocate arrays
        pools = new address[](count);
        token0Symbols = new string[](count);
        token1Symbols = new string[](count);
        token0Addresses = new address[](count);
        token1Addresses = new address[](count);
        
        // Second pass: Fill arrays
        uint256 idx = 0;
        for (uint i = 0; i < entities.length && idx < count; i++) {
            address entity = entities[i].pubAddress;
            try IUniswapV2Pair(entity).token0() returns (address token0) {
                try IUniswapV2Pair(entity).token1() returns (address token1) {
                    // Only include pools containing targetToken
                    if (token0 == targetTokenAddress || token1 == targetTokenAddress) {
                        pools[idx] = entity;
                        token0Addresses[idx] = token0;
                        token1Addresses[idx] = token1;
                        
                        // Get symbols
                        try IERC20Metadata(token0).symbol() returns (string memory sym) {
                            token0Symbols[idx] = sym;
                        } catch {
                            token0Symbols[idx] = "UNKNOWN";
                        }
                        
                        try IERC20Metadata(token1).symbol() returns (string memory sym) {
                            token1Symbols[idx] = sym;
                        } catch {
                            token1Symbols[idx] = "UNKNOWN";
                        }
                        
                        idx++;
                    }
                } catch {}
            } catch {}
        }
        
        return (pools, token0Symbols, token1Symbols, token0Addresses, token1Addresses);
    }
}

/* ========== INTERFACES ========== */

interface IUniswapV2Pair {
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;
}

interface ILiquidityProvider {
    function isApprovedPool(address pool) external view returns (bool);
    function triggerLiquidityCheck() external; // Trigger LP provision check (SmartContract/TreasuryAdmin only)
    function totalLiquidityProvided() external view returns (uint256); // Get LP total
    function primaryLiquidityPool() external view returns (address); // Get primary pool address
}

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

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

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

// SPDX-License-Identifier: UNLICENSED
// ============================================================
//  EquityMint.org — Official Sovereign Issuance Contract
//  © Copyright 2025 US Fintech LLC, a New york Company
//  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.org On-Chain Registry (viewable via equitymint.org or equitymint.org/tokensale)
//  - Only deployments listed in the registry are recognized as
//    authentic sovereign issuances.
//
//  Contact:
//  - https://EquityMint.org
//  - [email protected]
// ============================================================
//
// Copyright 2017-2025 US Fintech LLC
// Permission to use, copy, modify, or distribute this software is strictly prohibited
// without prior written consent from US Fintech LLC.  Violators will be prosecuted to the fullest extent of the law.
// 
// THE SOFTWARE Sourcecode is listed only for verification purposes and may not be copied.
// It is not intended for use in production by any non-authorized parties.
// It 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.
//
// OFFICIAL Data Cloud OS and EquityMint.org components
// ExecutivePeerTreasury is a contract that allows for the transfer of ETH and ERC20 tokens between different contracts.
// Designed by Ken Silverman as part of his ExecutivePeerTreasury and Controller-based eco-system.   
// Permission to change metadata stored on blockchain explorers exclusively reserved to US Fintech, LLC.
pragma solidity 0.8.30;

import "../interfaces/IController.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);


    struct TreasuryEntry {
        uint256 totalReceived;
        uint256 totalWithdrawn;
    }

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

    address public immutable peerTreasuryController;

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

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

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

    constructor(address _controller, string memory _contractName) {
        peerTreasuryController = _controller;
        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) external onlyTreasuryAdmin {
        require(address(this).balance >= amt, "Insufficient ETH balance");
        (bool success, ) = payable(personAddress).call{value: amt}("");
        require(success, "ETH transfer failed");
        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) external onlyTreasuryAdmin {
        require(tokenSCAddress != address(0), "Invalid tok addr");
        IERC20 token = IERC20(tokenSCAddress);
        require(token.balanceOf(address(this)) >= amt, "Insuffic tok bal");
        IERC20(tokenSCAddress).safeTransfer(personAddress, 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 {
        require(msg.value > 0, "No ETH sent");
        require(IController(peerTreasuryController).isOfficialEntity("SmartContract", msg.sender), "Sender is not an official SmartContract");
        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 onlyTreasuryAdmin {
        require(address(this).balance >= amount, "Insufficient contract ETH balance");
        require(IController(peerTreasuryController).isOfficialEntity("SmartContract", to), "Recipient not an official SmartContract");

        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 {
        require(amount > 0, "Zero amount");
        require(IController(peerTreasuryController).isOfficialEntity("SmartContract", msg.sender), "Sender not official SC");
        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 onlyTreasuryAdmin {
        require(IERC20(token).balanceOf(address(this)) >= amount, "Insuffic token bal");
        require(IController(peerTreasuryController).isOfficialEntity("SmartContract", to), "recipient not official SC");
        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 onlyTreasuryAdmin {
        require(IERC20(token).balanceOf(address(this)) >= amount, "Low token bal");
        require(IController(peerTreasuryController).isOfficialEntity("SmartContract", to), "rcpnt !ofcl SC");
        // 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 {
        require(IController(peerTreasuryController).isOfficialEntity("SmartContract", msg.sender), "sender !ofcl SC");
        // Update received tracking (same as peerTreasuryReceiveTokens but no transferFrom)
        tokenPeerTreasury[token].totalReceived += amount;
        // tokenPeerTreasury[token].currentBalance += amount;
        emit PeerTreasuryReceivedTokens(msg.sender, token, amount);
    }

    
}

contracts/TreasuryConstants.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright 2025 US Fintech LLC
// 
// Permission to use, copy, modify, or distribute this software is strictly prohibited
// without prior written consent from either copyright holder.
// 
// 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.30;

/// @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 "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 "TokenAdmin" for gas-optimized entity checks
    bytes32 public constant KECCAK_REGISTRAR = keccak256(bytes("Registrar"));
    
    /// @notice Pre-computed keccak256 hash of "SwappableToken" for gas-optimized entity checks
    bytes32 public constant KECCAK_SWAPPABLE_TOKEN = keccak256(bytes("SwappableToken"));

    /// @notice Pre-computed keccak256 hash of "PLATFORM_TREASURER" for gas-optimized entity checks (official entity with special permissions)
    bytes32 public constant KECCAK_PLATFORM_TREASURER = keccak256(bytes("PLATFORM_TREASURER"));

    /// @notice Pre-computed keccak256 hash of "PLATFORM_FEE_CHAINED_ENTITY" for gas-optimized entity checks (fee distribution chain)
    bytes32 public constant KECCAK_PLATFORM_FEE_CHAINED_ENTITY = keccak256(bytes("PLATFORM_FEE_CHAINED_ENTITY"));
}

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.
//
// OFFICIAL DEL NORTE NETWORK COMPONENT 
// Provides immediate membership access to platform at different levels. 
// Required Non US or accredited US registration to swap for DTV token. Registration available within 180 days per terms.delnorte.io . 
// Minimally tested Controller Tree for world-wide government administration of, well, anything, including property ownership.
// Designed by Ken Silverman as part of his ElasticTreasury (HUB and SPOKE), PeerTreasury and Controller model. 
// @author Ken Silverman
// 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.30;

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

    struct ChainedEntityStruct {
        address entityAddress;
        address parent;
        uint256 val1;    // Value for type1 (absolute amount or percentage in basis points)
        uint256 val2;    // Value for type2 (absolute amount or percentage in basis points)
        uint256 val3;    // Value for type3 (absolute amount or percentage in basis points)
        uint8 valDetailFlags; // Packed: [type1|isTaker1|type2|isTaker2|type3|isTaker3|rsv|rsv]
        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 type1Amount;  // Calculated amount for type1 (e.g., transfer fee)
        uint256 type2Amount;  // Calculated amount for type2 (e.g., activation fee)
        uint256 type3Amount;  // Calculated amount for type3 (e.g., purchase fee)
    }

    // Entity with fees for addChainedEntity to avoid stack too deep
    struct EntityFees {
        address entityAddress;
        address parent;        // 0x0 = root, else = parent address
        uint256 val1;
        uint256 val2;
        uint256 val3;
        uint8 valDetailFlags;  // Packed: [type1|isTaker1|type2|isTaker2|type3|isTaker3] (only PLATFORM_TREASURER can set isTaker bits)
        bool locked;
    }
    
    struct EntityFeesWithNames {
        address entityAddress;
        address parent;
        uint256 val1;
        uint256 val2;
        uint256 val3;
        uint8 valDetailFlags;
        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 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;
    
    // Chained Entity Functions
    function addChainedEntity(string memory chainType, EntityFeesWithNames memory entity) external returns (bool);
    function removeChainedEntity(string calldata, address, bool) external returns (bool);
    function lockAllRootChainedEntities(string memory) external returns (uint256);
    function lockGlobalChainedEntityAddition() external returns (bool);
    function isChainedEntity(string calldata, address) external view returns (bool);
    function isChainedEntityFast(bytes32, address) external view returns (bool);
    function getChainedEntity(string calldata, address) external view returns (ChainedEntityStruct memory);
    function getActiveChainedEntities(string calldata) external view returns (ChainedEntityStruct[] memory);
    function calculateChainedAmounts(
        string calldata chainType,
        uint256 totalVal,
        uint256 maxPct,
        uint8 calculateType
    ) external view returns (
        CalculatedEntityAmount[] memory calculatedAmounts,
        uint256 totalType1,
        uint256 totalType2,
        uint256 totalType3
    );
    
    // Constants
    function BASIS_POINTS_DIVISOR() external view returns (uint256);
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 7000,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.