Skip to content
Verified contractExactMPL-2.0

GiudasSovereignCoreV2

Address0x4c9856f54375398ac2d232839b17ed5719dc9f4e
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 999 runs
EVM version
osaka
License
MPL-2.0
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,338,181
Creation transaction
0x57c648709f…c84a25aed3

GiudasSovereignCoreV2.sol

// SPDX-License-Identifier: MPL-2.0
// © Mergim Nishori - GIUDAS v8.0 Sovereign Hedge Fund, RWA Vault & Algorithmic Central Bank
// V2.1 (Audited & Fixed) - Contabilità unificata Base + Hyperliquid a prova di errore
pragma solidity ^0.8.20;

interface IERC20 {
    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address recipient, uint256 amount) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}

interface IUniswapV2Router02 {
    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
}

interface GoldPriceFeed {
    function latestRoundData() external view returns (
        uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound
    );
}

// ============================================================================
// 1. GIUDAS DYNAMIC NFC (Certificati di Proprietà Quota & Auto-Compound)
// ============================================================================
contract GiudasNFC {
    string public constant name = "Giudas Sovereign Certificate";
    string public constant symbol = "gNFC";
    address public coreVault;
    uint256 public nextTokenId = 1001;

    struct Certificate {
        uint256 stakedShares;
        uint256 allocatedSilverWei;
        uint256 compoundedSharesEarned;
        uint64 stakedAtTs;
        bool autoCompound;
        bool active;
    }

    mapping(uint256 => address) public ownerOf;
    mapping(address => uint256[]) public certificatesOf;
    mapping(uint256 => Certificate) public certificates;

    event NfcMinted(address indexed owner, uint256 indexed nfcId, uint256 shares, bool autoCompound);
    event NfcYieldCredited(uint256 indexed nfcId, uint256 addedShares, uint256 addedSilverWei);
    event NfcUnstaked(address indexed owner, uint256 indexed nfcId, uint256 returnedShares, uint256 claimedSilverWei);
    event CoreVaultUpdated(address indexed oldCore, address indexed newCore);

    error NotCore();
    error NfcInactive();
    error NotOwner();
    error ZeroShares();
    error ZeroAddress();

    modifier onlyCore() {
        if (msg.sender != coreVault) revert NotCore();
        _;
    }

    constructor() {
        coreVault = msg.sender;
    }

    /// @notice Permette di migrare il puntatore al nuovo Core senza rideployare l'NFC
    function setCoreVault(address _newCore) external onlyCore {
        if (_newCore == address(0)) revert ZeroAddress();
        emit CoreVaultUpdated(coreVault, _newCore);
        coreVault = _newCore;
    }

    function mint(address to, uint256 shares, bool autoCompound) external onlyCore returns (uint256 nfcId) {
        if (shares == 0) revert ZeroShares();
        if (to == address(0)) revert ZeroAddress();
        nfcId = nextTokenId++;
        ownerOf[nfcId] = to;
        certificatesOf[to].push(nfcId);

        Certificate storage c = certificates[nfcId];
        c.stakedShares = shares;
        c.stakedAtTs = uint64(block.timestamp);
        c.autoCompound = autoCompound;
        c.active = true;

        emit NfcMinted(to, nfcId, shares, autoCompound);
    }

    function getLoyaltyMultiplierBps(uint256 nfcId) public view returns (uint256) {
        Certificate storage c = certificates[nfcId];
        if (!c.active) revert NfcInactive();
        uint256 age = block.timestamp - uint256(c.stakedAtTs);
        if (age >= 180 days) return 20000;
        if (age >= 90 days)  return 15000;
        return 12500;
    }

    function creditYield(uint256 nfcId, uint256 addedShares, uint256 addedSilverWei) external onlyCore {
        _creditYield(nfcId, addedShares, addedSilverWei);
    }

    function creditYieldBatch(
        uint256[] calldata nfcIds,
        uint256[] calldata addedShares,
        uint256[] calldata addedSilverWei
    ) external onlyCore {
        uint256 len = nfcIds.length;
        for (uint256 i; i < len; ) {
            _creditYield(nfcIds[i], addedShares[i], addedSilverWei[i]);
            unchecked { ++i; }
        }
    }

    function _creditYield(uint256 nfcId, uint256 addedShares, uint256 addedSilverWei) internal {
        Certificate storage c = certificates[nfcId];
        if (!c.active) revert NfcInactive();
        unchecked {
            c.stakedShares += addedShares;
            c.compoundedSharesEarned += addedShares;
            c.allocatedSilverWei += addedSilverWei;
        }
        emit NfcYieldCredited(nfcId, addedShares, addedSilverWei);
    }

    function burnAndRedeem(uint256 nfcId, address caller)
        external
        onlyCore
        returns (uint256 returnedShares, uint256 claimedSilverWei)
    {
        if (ownerOf[nfcId] != caller) revert NotOwner();
        Certificate storage c = certificates[nfcId];
        if (!c.active) revert NfcInactive();

        returnedShares = c.stakedShares;
        claimedSilverWei = c.allocatedSilverWei;

        c.active = false;
        c.stakedShares = 0;
        c.allocatedSilverWei = 0;
        c.compoundedSharesEarned = 0;
        ownerOf[nfcId] = address(0);

        emit NfcUnstaked(caller, nfcId, returnedShares, claimedSilverWei);
    }
}

// ============================================================================
// 2. GIUDAS SOVEREIGN CORE V2 (Hedge Fund Vault + XAUT Scudi + gUSD + Hyperliquid)
// ============================================================================
contract GiudasSovereignCoreV2 {
    string public constant name = "Giudas Sovereign Gold Dollar";
    string public constant symbol = "gUSD";
    uint8 public constant decimals = 6;

    uint256 public constant ENTRY_EXIT_FEE_BPS = 300;
    uint256 public constant PERFORMANCE_TAX_BPS = 1000;
    uint256 public constant TG_COMMODITIES_FEE_BPS = 25;
    uint256 public constant XAUT_YIELD_REINVEST_BPS = 2000;
    uint256 public constant MAX_GUSD_MINT_RATIO_BPS = 2000;
    uint256 public constant INTERNAL_POOL_SWAP_FEE_BPS = 10;
    uint256 public constant BPS = 10000;

    uint256 public constant MAX_SLIPPAGE_BPS = 1000;
    uint256 public constant MAX_DEADLINE_WINDOW = 10 minutes;
    uint256 public constant MAX_PATH_LENGTH = 4;

    IERC20 public immutable usdcToken;
    IERC20 public immutable usdtToken;
    IERC20 public immutable silverRwaToken;
    GiudasNFC public nfcContract;

    address public immutable giudasRustEngine;
    address public immutable xautFortressTreasury;

    // Prezzo Oro (USD, 6 dec): inizializzato a $3932.00 di default per evitare revert al boot
    uint256 public goldPriceUsd = 3932000000;
    GoldPriceFeed public goldPriceFeed;

    uint256 public activeTradingTvlUsdc;
    uint256 public totalSharesSupply;
    uint256 public totalSilverVaultWei;
    uint256 public cyclesCompleted;

    mapping(address => uint256) public freeShares;

    uint256 public xautFortressScudi;
    uint256 public fastCashUsdt;
    uint256 public totalSupplyGusd;
    uint256 public polPoolUsdt;
    uint256 public polPoolGusd;

    mapping(address => uint256) public balanceOfGusd;

    // Contabilità ibrida Base + Hyperliquid (importi USDC a 6 decimali).
    uint256 public hlUsedMarginUsdc;
    uint256 public hlFreeMarginUsdc;
    uint256 public activePerpPositionsCount;
    uint256 public maxPerpAllocationBps = 8000;
    bool public perpCircuitBreaker = false;

    // Valorizzazione delle posizioni Base aperte (es. WETH acquistati via swap).
    uint256 public reserveValuationUsdc;

    // Tassa performance maturata su Hyperliquid in attesa di rientro USDC su Base
    uint256 public pendingHlTaxUsdc;

    address public silverGkagContract;
    address public botExecutor;

    mapping(address => bool) public isRouterApproved;
    mapping(address => bool) public isTokenApproved;

    int256 public cumulativeNetPnlUsdc;
    int256 public lastSwapPnlUsdc;
    int256 public lastSettledPnlUsdc;

    event Deposited(address indexed user, uint256 grossUsdc, uint256 netUsdc, uint256 sharesMinted, uint256 scudiAdded);
    event Withdrawn(address indexed user, uint256 sharesBurned, uint256 netUsdcOut, uint256 scudiAdded);
    event FortressFed(string source, uint256 grossUsd, uint256 netAfterTgFee, uint256 scudiMinted, uint256 totalScudi);
    event YieldHarvested(uint256 grossUsdt, uint256 scudiCompounded, uint256 fastCashAdded, uint256 newGusdMinted);
    event PegKeeperExecuted(uint256 usdtDeployed, uint256 gusdBurned, uint256 newPoolUsdt, uint256 newPoolGusd);
    event InternalSwap(address indexed user, bool gusdToUsdt, uint256 amountIn, uint256 amountOut, uint256 scudiFee);
    event GoldPriceUpdated(uint256 oldPrice, uint256 newPrice);
    event GoldPriceFeedUpdated(address indexed oldFeed, address indexed newFeed);
    event OrphanedFundsRescued(uint256 amountUsdc, uint256 amountUsdt, uint256 amountSilverWei);

    event RouterApprovalUpdated(address indexed router, bool approved);
    event TokenApprovalUpdated(address indexed token, bool approved);
    event RouterAllowanceSet(address indexed token, address indexed router, uint256 amount);
    event ManagedSwap(
        address indexed router,
        address indexed tokenIn,
        address indexed tokenOut,
        uint256 amountIn,
        uint256 amountOut,
        uint256 minAmountOut,
        int256 pnlUsdc
    );
    event PnlSettled(int256 pnlUsdc, uint256 taxToFortress, uint256 newTvlUsdc, uint256 cyclesCompleted);
    event HyperliquidStateSynced(uint256 usedMargin, uint256 freeMargin, uint256 openTrades, int256 netPnl, uint256 totalTvl);
    event HyperliquidAllocated(address indexed destination, uint256 amountUsdc, uint256 freeMarginUsdc);
    event HyperliquidReturned(uint256 amountUsdc, uint256 freeMarginUsdc);
    event LegacyStateMigrated(address indexed beneficiary, uint256 legacyShares, uint256 legacyScudiXaut, uint256 legacyCycles, uint256 activeTvlUsdc);
    event EcosystemLinksUpdated(address indexed nfc, address indexed silver, address indexed executor);
    event EmergencySweep(address indexed token, address indexed to, uint256 amount);
    event ReserveValuationUpdated(uint256 oldValueUsdc, uint256 newValueUsdc);
    event MaxPerpAllocationUpdated(uint256 oldBps, uint256 newBps);
    event PerpCircuitBreakerUpdated(bool enabled);

    error NotGiudas();
    error ZeroAmount();
    error InsufficientShares();
    error InvalidArrays();
    error InsufficientGusd();
    error InsufficientPoolUsdt();
    error InsufficientPoolGusd();
    error InsufficientSilverVault();
    error InvalidPrice();
    error ZeroAddress();
    error RouterNotApproved();
    error TokenNotApproved();
    error InvalidPath();
    error InvalidDeadline();
    error MinOutRequired();
    error InsufficientContractBalance();
    error SwapAmountOutTooLow();
    error SlippageTooHigh();
    error NotAuthorized();
    error PerpCircuitBreakerActive();
    error PerpAllocationLimitExceeded();
    error InsufficientHyperliquidMargin();
    error NativeTransferFailed();
    error LegacyStateAlreadyMigrated();

    modifier onlyGiudas() {
        if (msg.sender != giudasRustEngine) revert NotGiudas();
        _;
    }

    modifier onlyOwner() {
        if (msg.sender != giudasRustEngine) revert NotAuthorized();
        _;
    }

    modifier onlyExecutorOrOwner() {
        if (msg.sender != giudasRustEngine && msg.sender != botExecutor) revert NotAuthorized();
        _;
    }

    constructor(
        address _usdc,
        address _usdt,
        address _silverRwa,
        address _giudasRustEngine,
        address _xautFortressTreasury
    ) {
        if (
            _usdc == address(0) ||
            _usdt == address(0) ||
            _silverRwa == address(0) ||
            _giudasRustEngine == address(0) ||
            _xautFortressTreasury == address(0)
        ) revert ZeroAddress();

        usdcToken = IERC20(_usdc);
        usdtToken = IERC20(_usdt);
        silverRwaToken = IERC20(_silverRwa);
        giudasRustEngine = _giudasRustEngine;
        xautFortressTreasury = _xautFortressTreasury;
        nfcContract = new GiudasNFC();
        silverGkagContract = _silverRwa;
        botExecutor = _giudasRustEngine;

        // Pre-approvazione automatica token principali Base (USDC, WETH e quelli passati)
        isTokenApproved[_usdc] = true;
        isTokenApproved[_usdt] = true;
        isTokenApproved[_silverRwa] = true;
        isTokenApproved[0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913] = true; // Base USDC
        isTokenApproved[0x4200000000000000000000000000000000000006] = true; // Base WETH

        // Pre-approvazione automatica Router Uniswap V2 su Base
        isRouterApproved[0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24] = true; // Uniswap V2 Router Base
        isRouterApproved[0x88A43bbDF9D098eEC7bCEda4e2494615dfD9bB9C] = true; // Base Swap Router usato nei log

        emit TokenApprovalUpdated(0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913, true);
        emit TokenApprovalUpdated(0x4200000000000000000000000000000000000006, true);
        emit RouterApprovalUpdated(0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24, true);
    }

    receive() external payable {}

    function _safeTransfer(IERC20 token, address to, uint256 amount) internal {
        if (!token.transfer(to, amount)) revert("TRANSFER_FAILED");
    }

    uint256 public constant MIN_GOLD_PRICE_USD_6DEC = 1e6;
    uint256 public constant MAX_GOLD_PRICE_USD_6DEC = 1e11;
    uint256 public constant FEED_MAX_STALENESS = 24 hours;

    function setGoldPrice(uint256 newPriceUsd6Dec) external onlyExecutorOrOwner {
        if (newPriceUsd6Dec < MIN_GOLD_PRICE_USD_6DEC || newPriceUsd6Dec > MAX_GOLD_PRICE_USD_6DEC) {
            revert InvalidPrice();
        }
        emit GoldPriceUpdated(goldPriceUsd, newPriceUsd6Dec);
        goldPriceUsd = newPriceUsd6Dec;
    }

    function setGoldPriceFeed(address feed) external onlyOwner {
        if (feed == address(0)) revert ZeroAddress();
        emit GoldPriceFeedUpdated(address(goldPriceFeed), feed);
        goldPriceFeed = GoldPriceFeed(feed);
    }

    function _currentGoldPriceUsd6Dec() internal view returns (uint256) {
        GoldPriceFeed feed = goldPriceFeed;
        if (address(feed) != address(0)) {
            try feed.latestRoundData() returns (
                uint80, int256 answer, uint256, uint256 updatedAt, uint80 answeredInRound
            ) {
                if (answer > 0 && answeredInRound >= 1 && block.timestamp - updatedAt <= FEED_MAX_STALENESS) {
                    uint256 p6 = (uint256(answer) * 1e6) / 1e8;
                    if (p6 >= MIN_GOLD_PRICE_USD_6DEC && p6 <= MAX_GOLD_PRICE_USD_6DEC) {
                        return p6;
                    }
                }
            } catch {}
        }
        return goldPriceUsd;
    }

    function getGoldPriceUsd() external view returns (uint256) {
        return _currentGoldPriceUsd6Dec();
    }

    // ========================================================================
    // LETTURA UNIFICATA: TVL REALE, NAV, FORTEZZA XAUT & gUSD
    // ========================================================================
    function getTotalTvlUsdc() public view returns (uint256) {
        return usdcToken.balanceOf(address(this)) + hlUsedMarginUsdc + hlFreeMarginUsdc + reserveValuationUsdc;
    }

    function getShareNavUsdc() public view returns (uint256) {
        uint256 supply = totalSharesSupply;
        uint256 tvl = getTotalTvlUsdc();
        if (supply == 0 || tvl == 0) return 1e6;
        return (tvl * 1e18) / supply;
    }

    function getFortressValueUsd() public view returns (uint256) {
        return (xautFortressScudi * _currentGoldPriceUsd6Dec()) / (1000 * 1e6);
    }

    function getMaxAllowedGusdCap() public view returns (uint256) {
        return (getFortressValueUsd() * MAX_GUSD_MINT_RATIO_BPS) / BPS;
    }

    function getGusdCollateralRatioBps() public view returns (uint256) {
        uint256 supply = totalSupplyGusd;
        if (supply == 0) return 0;
        return (getFortressValueUsd() * BPS) / supply;
    }

    /// @dev Alimenta la Fortezza XAUT. Se `transferPhysical` è false (es. fondi su HL),
    ///      accredita gli Scudi contabili e segna la tassa in `pendingHlTaxUsdc`.
    function _feedXautFortress(
        IERC20 token,
        uint256 feeAmount6Dec,
        string memory source
    ) internal returns (uint256 scudiMinted) {
        if (feeAmount6Dec == 0) return 0;
        uint256 price = _currentGoldPriceUsd6Dec();
        if (price == 0) revert InvalidPrice();
        uint256 netAfterTg = (feeAmount6Dec * (BPS - TG_COMMODITIES_FEE_BPS)) / BPS;
        scudiMinted = (netAfterTg * 1000 * 1e6) / price;

        uint256 newScudi = xautFortressScudi + scudiMinted;
        xautFortressScudi = newScudi;

        uint256 localBal = token.balanceOf(address(this));
        if (localBal >= feeAmount6Dec) {
            _safeTransfer(token, xautFortressTreasury, feeAmount6Dec);
        } else {
            // I fondi sono su Hyperliquid: segna la tassa da saldare al rientro senza mandare in revert!
            pendingHlTaxUsdc += feeAmount6Dec;
        }
        emit FortressFed(source, feeAmount6Dec, netAfterTg, scudiMinted, newScudi);
    }

    // ========================================================================
    // MODULO PERPETUAL HYPERLIQUID (margine isolato 2x gestito off-chain)
    // ========================================================================
    function allocateToHyperliquid(uint256 amountUsdc, address hlBridgeOrAgent) external onlyOwner {
        if (amountUsdc == 0) revert ZeroAmount();
        if (hlBridgeOrAgent == address(0)) revert ZeroAddress();
        if (perpCircuitBreaker) revert PerpCircuitBreakerActive();

        uint256 tvl = getTotalTvlUsdc();
        uint256 newHlAllocation = hlUsedMarginUsdc + hlFreeMarginUsdc + amountUsdc;
        if (newHlAllocation * BPS > tvl * maxPerpAllocationBps) revert PerpAllocationLimitExceeded();
        if (usdcToken.balanceOf(address(this)) < amountUsdc) revert InsufficientContractBalance();

        _safeTransfer(usdcToken, hlBridgeOrAgent, amountUsdc);
        hlFreeMarginUsdc += amountUsdc;
        activeTradingTvlUsdc = getTotalTvlUsdc();
        emit HyperliquidAllocated(hlBridgeOrAgent, amountUsdc, hlFreeMarginUsdc);
    }

    /// @notice Registra il rientro di USDC dal bridge/agent al Core e salda eventuali tasse pendenti.
    function returnFromHyperliquid(uint256 amountUsdc) external onlyOwner {
        if (amountUsdc == 0) revert ZeroAmount();
        if (amountUsdc > hlFreeMarginUsdc) revert InsufficientHyperliquidMargin();
        hlFreeMarginUsdc -= amountUsdc;

        // Se c'erano tasse Fortezza maturate mentre gli USDC erano su Hyperliquid, le salda ora
        uint256 pending = pendingHlTaxUsdc;
        if (pending > 0 && usdcToken.balanceOf(address(this)) >= pending) {
            pendingHlTaxUsdc = 0;
            _safeTransfer(usdcToken, xautFortressTreasury, pending);
        }

        activeTradingTvlUsdc = getTotalTvlUsdc();
        emit HyperliquidReturned(amountUsdc, hlFreeMarginUsdc);
    }

    function syncHyperliquidState(
        uint256 _usedMargin,
        uint256 _freeMargin,
        uint256 _openPositions,
        int256 _realizedNetPnlUsdc
    ) external onlyExecutorOrOwner {
        hlUsedMarginUsdc = _usedMargin;
        hlFreeMarginUsdc = _freeMargin;
        activePerpPositionsCount = _openPositions;

        if (_realizedNetPnlUsdc > 0) {
            uint256 netProfit = uint256(_realizedNetPnlUsdc);
            uint256 taxToFortress = (netProfit * PERFORMANCE_TAX_BPS) / BPS;
            if (taxToFortress > 0) {
                _feedXautFortress(usdcToken, taxToFortress, "HYPERLIQUID_PROFIT_TAX_10%");
            }
        }

        activeTradingTvlUsdc = getTotalTvlUsdc();
        cumulativeNetPnlUsdc += _realizedNetPnlUsdc;
        lastSettledPnlUsdc = _realizedNetPnlUsdc;
        unchecked { cyclesCompleted++; }
        emit HyperliquidStateSynced(_usedMargin, _freeMargin, _openPositions, _realizedNetPnlUsdc, activeTradingTvlUsdc);
    }

    function getVaultFullTelemetry()
        external
        view
        returns (
            uint256 totalTvlUsdc,
            uint256 baseLiquidUsdc,
            uint256 hlUsedUsdc,
            uint256 hlFreeUsdc,
            uint256 openTrades,
            uint256 navPerShare,
            uint256 scudiXaut
        )
    {
        return (
            getTotalTvlUsdc(),
            usdcToken.balanceOf(address(this)),
            hlUsedMarginUsdc,
            hlFreeMarginUsdc,
            activePerpPositionsCount,
            getShareNavUsdc(),
            xautFortressScudi
        );
    }

    function setReserveValuationUsdc(uint256 newValueUsdc) external onlyExecutorOrOwner {
        uint256 oldValue = reserveValuationUsdc;
        reserveValuationUsdc = newValueUsdc;
        activeTradingTvlUsdc = getTotalTvlUsdc();
        emit ReserveValuationUpdated(oldValue, newValueUsdc);
    }

    function setMaxPerpAllocationBps(uint256 newBps) external onlyOwner {
        if (newBps > BPS) revert PerpAllocationLimitExceeded();
        emit MaxPerpAllocationUpdated(maxPerpAllocationBps, newBps);
        maxPerpAllocationBps = newBps;
    }

    function setPerpCircuitBreaker(bool enabled) external onlyOwner {
        perpCircuitBreaker = enabled;
        emit PerpCircuitBreakerUpdated(enabled);
    }

    // ========================================================================
    // CRUSCOTTO TRADING V2 (allowlist router/token, swap dal saldo del vault)
    // ========================================================================
    function setRouterApproval(address router, bool approved) external onlyGiudas {
        if (router == address(0)) revert ZeroAddress();
        isRouterApproved[router] = approved;
        emit RouterApprovalUpdated(router, approved);
    }

    function setTokenApproval(address token, bool approved) external onlyGiudas {
        if (token == address(0)) revert ZeroAddress();
        isTokenApproved[token] = approved;
        emit TokenApprovalUpdated(token, approved);
    }

    function approveRouterForToken(address token, address router, uint256 amount) external onlyGiudas {
        if (token == address(0) || router == address(0)) revert ZeroAddress();
        if (!isTokenApproved[token] || !isRouterApproved[router]) revert TokenNotApproved();
        if (!IERC20(token).approve(router, amount)) revert("APPROVE_FAILED");
        emit RouterAllowanceSet(token, router, amount);
    }

    function _validatePath(address[] calldata path, address tokenIn, address tokenOut) internal view {
        uint256 len = path.length;
        if (len < 2 || len > MAX_PATH_LENGTH) revert InvalidPath();
        if (path[0] != tokenIn) revert InvalidPath();
        if (path[len - 1] != tokenOut) revert InvalidPath();
        for (uint256 i; i < len; ) {
            if (!isTokenApproved[path[i]]) revert TokenNotApproved();
            unchecked { ++i; }
        }
    }

    function _swapPnlUsdc(uint256 usdcBefore, uint256 usdcAfter) internal pure returns (int256) {
        return int256(usdcAfter) - int256(usdcBefore);
    }

    function executeManagedSwap(
        address router,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        uint256 deadline
    ) external onlyExecutorOrOwner returns (uint256 amountOut, int256 pnlUsdc) {
        _checkSwapParams(router, tokenIn, tokenOut, amountIn, amountOutMin, deadline);
        _validatePath(path, tokenIn, tokenOut);

        if (IERC20(tokenIn).balanceOf(address(this)) < amountIn) revert InsufficientContractBalance();

        amountOut = _runSwap(router, tokenIn, tokenOut, amountIn, amountOutMin, path, deadline);
        if (amountOut < amountOutMin) revert SwapAmountOutTooLow();

        // Se abbiamo comprato un token diverso da USDC usiamo l'importo speso come riserva contabile temporanea
        if (tokenIn == address(usdcToken) && tokenOut != address(usdcToken)) {
            reserveValuationUsdc += amountIn;
            activeTradingTvlUsdc = getTotalTvlUsdc();
        } else if (tokenOut == address(usdcToken) && tokenIn != address(usdcToken)) {
            reserveValuationUsdc = amountOut >= reserveValuationUsdc ? 0 : reserveValuationUsdc - amountOut;
            activeTradingTvlUsdc = getTotalTvlUsdc();
        }

        emit ManagedSwap(router, tokenIn, tokenOut, amountIn, amountOut, amountOutMin, lastSwapPnlUsdc);
        pnlUsdc = lastSwapPnlUsdc;
    }

    function _checkSwapParams(
        address router,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 amountOutMin,
        uint256 deadline
    ) internal view {
        if (amountIn == 0) revert ZeroAmount();
        if (amountOutMin == 0) revert MinOutRequired();
        if (!isRouterApproved[router]) revert RouterNotApproved();
        if (!isTokenApproved[tokenIn] || !isTokenApproved[tokenOut]) revert TokenNotApproved();
        if (deadline < block.timestamp || deadline > block.timestamp + MAX_DEADLINE_WINDOW) revert InvalidDeadline();
    }

    function _runSwap(
        address router,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        uint256 deadline
    ) internal returns (uint256 amountOut) {
        uint256 usdcBefore = usdcToken.balanceOf(address(this));
        uint256 outBefore = IERC20(tokenOut).balanceOf(address(this));

        if (!IERC20(tokenIn).approve(router, amountIn)) revert("APPROVE_FAILED");
        IUniswapV2Router02(router).swapExactTokensForTokens(amountIn, amountOutMin, path, address(this), deadline);

        uint256 outAfter = IERC20(tokenOut).balanceOf(address(this));
        if (outAfter < outBefore) revert("BALANCE_UNDERFLOW");
        amountOut = outAfter - outBefore;

        int256 pnl = _swapPnlUsdc(usdcBefore, usdcToken.balanceOf(address(this)));
        lastSwapPnlUsdc = pnl;
        cumulativeNetPnlUsdc += pnl;
    }

    function suggestedMinOut(uint256 expectedOutWei, uint256 slippageBps) external pure returns (uint256) {
        if (slippageBps > MAX_SLIPPAGE_BPS) revert SlippageTooHigh();
        return (expectedOutWei * (BPS - slippageBps)) / BPS;
    }

    /// @notice Settlement del ciclo: include correttamente sia Base che Hyperliquid e le riserve!
    function harvestRealPnl() external onlyExecutorOrOwner returns (int256 pnlUsdc, uint256 taxToFortress) {
        uint256 tvl = activeTradingTvlUsdc;
        uint256 recognizedTotalValue = getTotalTvlUsdc();

        if (recognizedTotalValue > tvl) {
            uint256 surplus = recognizedTotalValue - tvl;
            pnlUsdc = int256(surplus);
            taxToFortress = (surplus * PERFORMANCE_TAX_BPS) / BPS;
            if (taxToFortress > 0) {
                _feedXautFortress(usdcToken, taxToFortress, "PROFIT_TAX_10%");
            }
            activeTradingTvlUsdc = getTotalTvlUsdc();
        } else if (recognizedTotalValue < tvl) {
            pnlUsdc = -int256(tvl - recognizedTotalValue);
            activeTradingTvlUsdc = recognizedTotalValue;
            taxToFortress = 0;
        } else {
            pnlUsdc = 0;
            taxToFortress = 0;
        }

        lastSettledPnlUsdc = pnlUsdc;
        unchecked { cyclesCompleted++; }
        emit PnlSettled(pnlUsdc, taxToFortress, activeTradingTvlUsdc, cyclesCompleted);
    }

    // ========================================================================
    // SEZIONE A: HEDGE FUND VAULT
    // ========================================================================
    function deposit(uint256 usdcAmount) external returns (uint256 sharesMinted) {
        if (usdcAmount == 0) revert ZeroAmount();
        uint256 tvlBefore = getTotalTvlUsdc();
        if (!usdcToken.transferFrom(msg.sender, address(this), usdcAmount)) revert("TRANSFER_FROM_FAILED");

        uint256 fee3Pct = (usdcAmount * ENTRY_EXIT_FEE_BPS) / BPS;
        uint256 netCapital = usdcAmount - fee3Pct;

        uint256 supply = totalSharesSupply;
        if (supply == 0 || tvlBefore == 0) {
            sharesMinted = netCapital * 1e12;
        } else {
            sharesMinted = (netCapital * supply) / tvlBefore;
        }

        uint256 scudiAdded = _feedXautFortress(usdcToken, fee3Pct, "DEPOSIT_FEE_3%");

        unchecked {
            totalSharesSupply = supply + sharesMinted;
        }
        activeTradingTvlUsdc = getTotalTvlUsdc();
        freeShares[msg.sender] += sharesMinted;

        emit Deposited(msg.sender, usdcAmount, netCapital, sharesMinted, scudiAdded);
    }

    function stakeSharesForNfc(uint256 sharesAmount, bool autoCompound) external returns (uint256 nfcId) {
        if (sharesAmount == 0) revert ZeroAmount();
        uint256 bal = freeShares[msg.sender];
        if (bal < sharesAmount) revert InsufficientShares();
        unchecked {
            freeShares[msg.sender] = bal - sharesAmount;
        }
        nfcId = nfcContract.mint(msg.sender, sharesAmount, autoCompound);
    }

    function unstakeNfcAndClaimSilver(uint256 nfcId) external {
        (uint256 returnedShares, uint256 silverToClaim) = nfcContract.burnAndRedeem(nfcId, msg.sender);
        freeShares[msg.sender] += returnedShares;
        if (silverToClaim > 0) {
            if (silverToClaim > totalSilverVaultWei) revert InsufficientSilverVault();
            totalSilverVaultWei -= silverToClaim;
            if (silverRwaToken.balanceOf(address(this)) < silverToClaim) revert InsufficientSilverVault();
            _safeTransfer(silverRwaToken, msg.sender, silverToClaim);
        }
    }

    function withdraw(uint256 sharesToBurn) external returns (uint256 netUsdcOut) {
        if (sharesToBurn == 0) revert ZeroAmount();
        uint256 bal = freeShares[msg.sender];
        if (bal < sharesToBurn) revert InsufficientShares();
        uint256 tvl = getTotalTvlUsdc();
        uint256 supply = totalSharesSupply;
        if (supply == 0 || sharesToBurn > supply) revert InsufficientShares();
        uint256 grossUsdc = (sharesToBurn * tvl) / supply;
        if (usdcToken.balanceOf(address(this)) < grossUsdc) revert InsufficientContractBalance();

        uint256 exitFee3Pct = (grossUsdc * ENTRY_EXIT_FEE_BPS) / BPS;
        netUsdcOut = grossUsdc - exitFee3Pct;

        unchecked {
            freeShares[msg.sender] = bal - sharesToBurn;
            totalSharesSupply = supply - sharesToBurn;
        }

        uint256 scudiAdded = _feedXautFortress(usdcToken, exitFee3Pct, "EXIT_FEE_3%");
        _safeTransfer(usdcToken, msg.sender, netUsdcOut);
        activeTradingTvlUsdc = getTotalTvlUsdc();

        emit Withdrawn(msg.sender, sharesToBurn, netUsdcOut, scudiAdded);
    }

    // ========================================================================
    // SEZIONE B: BANCA CENTRALE gUSD, POOL POL & PEG-KEEPER
    // ========================================================================
    function _runPegKeeper() internal returns (uint256 burnedGusd) {
        uint256 poolGusd = polPoolGusd;
        uint256 poolUsdt = polPoolUsdt;
        uint256 cash = fastCashUsdt;

        if (poolGusd <= poolUsdt || cash == 0) return 0;

        uint256 gap = poolGusd - poolUsdt;
        uint256 idealInjection = gap / 2;
        burnedGusd = cash < idealInjection ? cash : idealInjection;

        if (burnedGusd > 0) {
            unchecked {
                fastCashUsdt = cash - burnedGusd;
                polPoolUsdt = poolUsdt + burnedGusd;
                polPoolGusd = poolGusd - burnedGusd;
                totalSupplyGusd -= burnedGusd;
            }
            emit PegKeeperExecuted(burnedGusd, burnedGusd, poolUsdt + burnedGusd, poolGusd - burnedGusd);
        }
    }

    function triggerManualPegKeeper() external onlyGiudas returns (uint256) {
        return _runPegKeeper();
    }

    function harvestXautYieldAndExpandPool(uint256 usdtYieldAmount) external onlyGiudas {
        if (usdtYieldAmount == 0) revert ZeroAmount();
        if (usdtToken.balanceOf(address(this)) < usdtYieldAmount) revert InsufficientContractBalance();

        uint256 toXautUsdt = (usdtYieldAmount * XAUT_YIELD_REINVEST_BPS) / BPS;
        uint256 toFastCashUsdt = usdtYieldAmount - toXautUsdt;

        uint256 scudiCompounded = _feedXautFortress(usdtToken, toXautUsdt, "XAUT_YIELD_COMPOUND_20%");
        fastCashUsdt += toFastCashUsdt;

        _runPegKeeper();

        uint256 maxGusdCap = getMaxAllowedGusdCap();
        uint256 newGusdMinted = 0;

        uint256 supply = totalSupplyGusd;
        if (maxGusdCap > supply) {
            uint256 remainingCap = maxGusdCap - supply;
            uint256 cash = fastCashUsdt;
            if (cash > 0) {
                newGusdMinted = cash < remainingCap ? cash : remainingCap;
                unchecked {
                    fastCashUsdt = cash - newGusdMinted;
                    totalSupplyGusd = supply + newGusdMinted;
                    polPoolUsdt += newGusdMinted;
                    polPoolGusd += newGusdMinted;
                }
            }
        }

        emit YieldHarvested(usdtYieldAmount, scudiCompounded, toFastCashUsdt, newGusdMinted);
    }

    function swapInInternalPool(uint256 amountIn, bool gusdToUsdt) external returns (uint256 amountOut) {
        if (amountIn == 0) revert ZeroAmount();
        uint256 fee = (amountIn * INTERNAL_POOL_SWAP_FEE_BPS) / BPS;
        amountOut = amountIn - fee;

        if (gusdToUsdt) {
            uint256 bal = balanceOfGusd[msg.sender];
            if (bal < amountIn) revert InsufficientGusd();
            uint256 poolUsdt = polPoolUsdt;
            if (poolUsdt < amountIn) revert InsufficientPoolUsdt();
            unchecked {
                balanceOfGusd[msg.sender] = bal - amountIn;
                polPoolGusd += amountOut;
                totalSupplyGusd -= fee;
                polPoolUsdt = poolUsdt - amountIn;
            }
            _safeTransfer(usdtToken, msg.sender, amountOut);
        } else {
            uint256 poolGusd = polPoolGusd;
            if (poolGusd < amountOut) revert InsufficientPoolGusd();
            if (!usdtToken.transferFrom(msg.sender, address(this), amountIn)) revert("TRANSFER_FROM_FAILED");
            unchecked {
                polPoolUsdt += amountOut;
                polPoolGusd = poolGusd - amountOut;
                balanceOfGusd[msg.sender] += amountOut;
            }
        }

        uint256 scudiFee = _feedXautFortress(usdtToken, fee, "INTERNAL_POOL_SWAP_FEE_0.1%");
        _runPegKeeper();

        emit InternalSwap(msg.sender, gusdToUsdt, amountIn, amountOut, scudiFee);
    }

    // ========================================================================
    // SEZIONE C: MIGRAZIONE, COLLEGAMENTI ECOSISTEMA E RECUPERO FONDI
    // ========================================================================
    /// @notice Importazione una tantum dello stato del vecchio Core + accredito quote al chiamante.
    function migrateLegacyState(
        uint256 _legacyShares,
        uint256 _legacyScudiXaut,
        uint256 _legacyCycles,
        uint256 _activeTvlUsdc
    ) external onlyOwner {
        if (totalSharesSupply != 0 || cyclesCompleted != 0 || activeTradingTvlUsdc != 0 || xautFortressScudi != 0) {
            revert LegacyStateAlreadyMigrated();
        }
        totalSharesSupply = _legacyShares;
        freeShares[msg.sender] = _legacyShares; // <-- FIX CRITICO: assegna le 14.55 quote al tuo wallet!
        xautFortressScudi = _legacyScudiXaut;
        cyclesCompleted = _legacyCycles;
        activeTradingTvlUsdc = _activeTvlUsdc;
        emit LegacyStateMigrated(msg.sender, _legacyShares, _legacyScudiXaut, _legacyCycles, _activeTvlUsdc);
    }

    function setEcosystemLinks(address _nfc, address _silver, address _executor) external onlyOwner {
        if (_nfc == address(0) || _silver == address(0) || _executor == address(0)) revert ZeroAddress();
        nfcContract = GiudasNFC(_nfc);
        silverGkagContract = _silver;
        botExecutor = _executor;
        emit EcosystemLinksUpdated(_nfc, _silver, _executor);
    }

    /// @notice Recupero totale owner-only: qualsiasi ERC20 (USDC, WETH, ecc.) o ETH nativo (_token = address(0)).
    function emergencySweep(address _token, uint256 _amount, address _to) external onlyOwner {
        if (_to == address(0)) revert ZeroAddress();
        if (_amount == 0) revert ZeroAmount();
        if (_token == address(0)) {
            (bool ok, ) = _to.call{value: _amount}("");
            if (!ok) revert NativeTransferFailed();
        } else {
            _safeTransfer(IERC20(_token), _to, _amount);
        }
        activeTradingTvlUsdc = getTotalTvlUsdc();
        emit EmergencySweep(_token, _to, _amount);
    }

    // ========================================================================
    // SEZIONE D: RECUPERO FONDI ORFANI (Rescue)
    // ========================================================================
    function getProtectedAmounts() public view returns (uint256 usdcProtected, uint256 usdtProtected) {
        usdcProtected = activeTradingTvlUsdc;
        usdtProtected = polPoolUsdt + fastCashUsdt;
    }

    function rescueOrphanedFunds() external onlyGiudas {
        (uint256 usdcProtected, uint256 usdtProtected) = getProtectedAmounts();

        uint256 silverBalance = silverRwaToken.balanceOf(address(this));
        uint256 silverProtected = totalSilverVaultWei;

        uint256 usdcBalance = usdcToken.balanceOf(address(this));
        uint256 usdtBalance = usdtToken.balanceOf(address(this));

        uint256 rescueableUsdc = usdcBalance > usdcProtected ? usdcBalance - usdcProtected : 0;
        uint256 rescueableUsdt = usdtBalance > usdtProtected ? usdtBalance - usdtProtected : 0;
        uint256 rescueableSilver = silverBalance > silverProtected ? silverBalance - silverProtected : 0;

        if (rescueableUsdc == 0 && rescueableUsdt == 0 && rescueableSilver == 0) revert ZeroAmount();

        if (rescueableUsdc > 0) _safeTransfer(usdcToken, giudasRustEngine, rescueableUsdc);
        if (rescueableUsdt > 0) _safeTransfer(usdtToken, giudasRustEngine, rescueableUsdt);
        if (rescueableSilver > 0) _safeTransfer(silverRwaToken, giudasRustEngine, rescueableSilver);

        emit OrphanedFundsRescued(rescueableUsdc, rescueableUsdt, rescueableSilver);
    }
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 999,
    "enabled": true
  },
  "evmVersion": "osaka",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.