StrategyConvexCurve

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "contracts/giddyVaultV3/strategies/StrategyConvexCurve.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.19;

import "../interfaces/curve/ICurveStableSwapNG.sol";
import "../interfaces/convex/IConvex.sol";
import "../interfaces/curve/ICrvMinter.sol";
import "../interfaces/curve/IRewardsGauge.sol";
import "./GiddyBaseStrategyV3.sol";

/**
 * @title StrategyConvexCurve
 * @notice Convex Curve strategy for Giddy V3 vaults
 * @dev Implements Convex Curve LP token staking with reward claiming and compounding
 *      Inherits from GiddyBaseStrategyV3 for common functionality
 *      Handles LP token deposits, withdrawals, and reward processing
 */
contract StrategyConvexCurve is GiddyBaseStrategyV3 {
  using SafeERC20 for IERC20;

  uint256 private constant BASE_PERCENT = 1e6;
  
  // Hardcoded Ethereum mainnet addresses
  IConvexBooster public constant BOOSTER = IConvexBooster(0xF403C135812408BFbE8713b5A23a04b3D48AAE31);
  ICrvMinter public constant MINTER = ICrvMinter(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0);
  address private constant CRV_TOKEN = 0xD533a949740bb3306d119CC777fa900bA034cd52;
  
  address public rewardPool;
  uint256 public poolId;
  
  // Curve gauge support
  address public gauge;
  
  // Configuration flags
  bool public isCrvMintable;
  bool public isCurveRewardsClaimable;

  function initialize(StrategyInitParams memory _params, address _rewardPool, uint256 _poolId) external initializer {
    __BaseStrategy_init(_params);

    rewardPool = _rewardPool;
    poolId = _poolId;
    
    // Initialize gauge as address(0) - can be set later via setGauge
    gauge = address(0);
    
    // Default configuration
    isCrvMintable = true;
    isCurveRewardsClaimable = true;

    IERC20(vaultToken).approve(address(BOOSTER), type(uint256).max);
    IERC20(vaultToken).approve(rewardPool, type(uint256).max);
  }

  function _deposit(uint256 amount) internal override {
    if (amount > 0) {
      if (rewardPool != address(0)) {
        // Use Convex
        IERC20(vaultToken).approve(address(BOOSTER), amount);
        BOOSTER.deposit(poolId, amount, true);
      } else {
        // Use Curve gauge directly
        IERC20(vaultToken).approve(gauge, amount);
        IRewardsGauge(gauge).deposit(amount);
      }
    }
  }

  function _withdraw(uint256 amount) internal override {
    if (amount > 0) {
      if (rewardPool != address(0)) {
        // Use Convex
        IConvexRewardPool(rewardPool).withdrawAndUnwrap(amount, false);
      } else {
        // Use Curve gauge directly
        IRewardsGauge(gauge).withdraw(amount);
      }
    }
  }

  function _balanceInDefiStrategy() internal view override returns (uint256 balance) {
    if (rewardPool != address(0)) {
      // Use Convex - check balance in reward pool
      return IERC20(rewardPool).balanceOf(address(this));
    } else {
      // Use Curve gauge - check balance in gauge
      return IRewardsGauge(gauge).balanceOf(address(this));
    }
  }

  function _claimAllRewards() internal override {
    if (rewardPool != address(0)) {
      // Use Convex
      IConvexRewardPool(rewardPool).getReward(address(this));
    } else {
      // Use Curve gauge
      if (isCrvMintable) MINTER.mint(gauge);
      if (isCurveRewardsClaimable) IRewardsGauge(gauge).claim_rewards(address(this));
    }
  }

  function _getClaimableBalance(address token) internal view override returns (uint256 claimable) {
    if (rewardPool != address(0)) {
      // Use Convex L1 - check main pool and extra rewards
      // Check if requesting CRV from main pool
      try IConvexRewardPool(rewardPool).rewardToken() returns (address mainRewardToken) {
        if (token == mainRewardToken) {
          // This is the main reward (CRV) - query main pool
          try IConvexRewardPool(rewardPool).earned(address(this)) returns (uint256 amount) {
            return amount;
          } catch {
            return 0;
          }
        }
      } catch {}
      // Check extra rewards (CVX, BOLD, etc.)
      try IConvexRewardPool(rewardPool).extraRewardsLength() returns (uint256 extraLen) {
        for (uint256 i = 0; i < extraLen; i++) {
          try IConvexRewardPool(rewardPool).extraRewards(i) returns (address extraRewardContract) {
            try IConvexVirtualRewardPool(extraRewardContract).rewardToken() returns (address extraToken) {
              if (extraToken == token) {
                // Found the token in extra rewards
                try IConvexVirtualRewardPool(extraRewardContract).earned(address(this)) returns (uint256 amount) {
                  return amount;
                } catch {
                  return 0;
                }
              }
            } catch {}
          } catch {}
        }
      } catch {}
      return 0;
    } else {
      // Use Curve gauge
      if (token == CRV_TOKEN) { 
        // CRV token - use claimable_tokens() as it's more reliable
        try IRewardsGauge(gauge).claimable_tokens(address(this)) returns (uint256 amount) {
          return amount;
        } catch {
          return 0;
        }
      } else {
        // For non-CRV tokens (BOLD, LUSD, etc.), use claimable_reward()
        try IRewardsGauge(gauge).claimable_reward(address(this), token) returns (uint256 amount) {
          return amount;
        } catch {
          return 0;
        }
      }
    }
  }

  function setConvexPid(uint256 _poolId) external onlyManager {
    setConvexPid(_poolId, false);
  }

  function setConvexPid(uint256 _poolId, bool claim) public onlyManager {
    if (poolId == _poolId) return;

    _withdraw(_balanceInDefiStrategy());
    if (claim) _claimAllRewards();

    // Update to new pool
    (address _lpToken,,, address _rewardPool,,) = BOOSTER.poolInfo(_poolId);
    require(vaultToken == _lpToken, "!lp");
    rewardPool = _rewardPool;
    poolId = _poolId;

    // Redeploy
    uint256 balance = IERC20(vaultToken).balanceOf(address(this));
    if (balance > 0) {
      _deposit(balance);
    }
  }

  function setGauge(address _gauge) external onlyManager {
    gauge = _gauge;
    if (_gauge != address(0)) {
      IERC20(vaultToken).approve(_gauge, type(uint256).max);
    }
  }

  function setCrvMintable(bool _isCrvMintable) external onlyManager {
    isCrvMintable = _isCrvMintable;
  }

  function setCurveRewardsClaimable(bool _isCurveRewardsClaimable) external onlyManager {
    isCurveRewardsClaimable = _isCurveRewardsClaimable;
  }

  function stratName() public pure override returns (string memory name) {
    return "StrategyConvexCurve";
  }

  function version() public pure override returns (string memory) {
    return "1.0";
  }
}
"
    },
    "contracts/giddyVaultV3/interfaces/curve/ICurveStableSwapNG.sol": {
      "content": "// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.9;

interface ICurveStableSwapNG {
  function N_COINS() external view returns (uint256);
  function coins(uint256 i) external view returns (address);
  function get_balances() external view returns (uint256[] memory);
  function stored_rates() external view returns (uint256[] memory);

  function totalSupply() external view returns (uint256);
  function get_virtual_price() external view returns (uint256);

  function add_liquidity(
    uint256[] calldata _amounts,
    uint256 _min_mint_amount,
    address _receiver
  ) external returns (uint256);

  function remove_liquidity(
    uint256 _burn_amount,
    uint256[] calldata _min_amounts,
    address _receiver,
    bool _claim_admin_fees
  ) external returns (uint256[] memory);
}
"
    },
    "contracts/giddyVaultV3/interfaces/convex/IConvex.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IConvexBooster {
    function deposit(uint256 pid, uint256 amount, bool stake) external returns (bool);
    function earmarkRewards(uint256 _pid) external;
    function poolInfo(uint256 pid) external view returns (
        address lptoken,
        address token,
        address gauge,
        address crvRewards,
        address stash,
        bool shutdown
    );
}

interface IConvexBoosterL2 {
    function deposit(uint256 _pid, uint256 _amount) external returns (bool);
    function poolInfo(uint256 pid) external view returns (
        address lptoken, //the curve lp token
        address gauge, //the curve gauge
        address rewards, //the main reward/staking contract
        bool shutdown, //is this pool shutdown?
        address factory //a reference to the curve factory used to create this pool (needed for minting crv)
    );
}

// L1 Mainnet Reward Pool Interface
// Documentation: https://docs.convexfinance.com/convexfinanceintegration/baserewardpool
interface IConvexRewardPool {
    function balanceOf(address account) external view returns (uint256);
    
    /**
     * @notice Get earned CRV rewards for an account
     * @param account The account to check
     * @return The amount of CRV tokens earned
     * @dev This only returns CRV from the main pool. Extra rewards must be queried separately.
     */
    function earned(address account) external view returns (uint256);
    
    /**
     * @notice Get the reward token address (CRV on L1)
     * @return The address of the main reward token
     */
    function rewardToken() external view returns (address);
    
    /**
     * @notice Get the number of extra reward contracts
     * @return The count of extra reward contracts
     */
    function extraRewardsLength() external view returns (uint256);
    
    /**
     * @notice Get extra reward contract at index
     * @param index The index of the extra reward contract
     * @return The address of the VirtualBalanceRewardPool contract
     */
    function extraRewards(uint256 index) external view returns (address);
    
    function periodFinish() external view returns (uint256);
    function getReward() external;
    function getReward(address _account, bool _claimExtras) external;
    function getReward(address _account) external;
    function withdrawAndUnwrap(uint256 _amount, bool claim) external;
    function withdrawAllAndUnwrap(bool claim) external;
}

// VirtualBalanceRewardPool - used for extra rewards on L1
interface IConvexVirtualRewardPool {
    function rewardToken() external view returns (address);
    function earned(address account) external view returns (uint256);
}

// L2 Sidechain Reward Pool Interface
// CRITICAL: earned() returns array of (token, amount) tuples on L2, not single uint256!
// Documentation: https://docs.convexfinance.com/convexfinanceintegration/side-chain-implemention
interface IConvexRewardPoolL2 {
    struct EarnedData {
        address token;
        uint256 amount;
    }
    
    function balanceOf(address account) external view returns (uint256);
    
    /**
     * @notice Get all earned rewards for an account
     * @param account The account to check rewards for
     * @return Array of EarnedData structs (token address, amount)
     * @dev CRITICAL: This is a MUTATIVE function on L2 - it claims from sources first
     *      When querying, use staticcall/view to prevent state changes
     *      Returns ALL reward tokens in one call (no separate extraRewards)
     */
    function earned(address account) external returns (EarnedData[] memory);
    
    /**
     * @notice Get number of reward tokens
     * @return The count of reward tokens for this pool
     */
    function rewardLength() external view returns (uint256);
    
    /**
     * @notice Get reward token info at index
     * @param index The index of the reward token
     * @return token The reward token address
     * @return integral The reward integral value
     * @return remaining The remaining rewards
     */
    function rewards(uint256 index) external view returns (address token, uint256 integral, uint256 remaining);
    
    function getReward(address _account) external;
    function withdraw(uint256 _amount, bool _claim) external;
    function emergencyWithdraw(uint256 _amount) external;
}
"
    },
    "contracts/giddyVaultV3/interfaces/curve/ICrvMinter.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0;

/**
 * @title ICrvMinter
 * @notice Interface for Curve CRV token minter contract
 * @dev Used to mint CRV rewards from gauges
 * 
 * NETWORK ADDRESSES:
 * - Ethereum L1: 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0 (hardcoded in StrategyConvexCurve)
 * - L2 Networks: Retrieved via IRewardsGauge(gauge).factory() (dynamic lookup)
 * 
 * USAGE:
 * - Call mint(gauge) to mint accumulated CRV rewards for a gauge
 * - Must be called before claiming rewards on some gauge types
 * - Not all gauges require minting (controlled by isCrvMintable flag)
 */
interface ICrvMinter {
    /**
     * @notice Mint CRV rewards for a specific gauge
     * @param _gauge The gauge address to mint CRV for
     * @dev Mints all accumulated CRV rewards to the gauge contract
     */
    function mint(address _gauge) external;
}
"
    },
    "contracts/giddyVaultV3/interfaces/curve/IRewardsGauge.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.9.0;

/**
 * @title IRewardsGauge
 * @notice Interface for Curve liquidity gauge contracts (matches Beefy naming)
 * @dev Handles LP token staking and reward claiming in Curve gauges
 * 
 * TESTING NOTES:
 * 
 * Test #1 - Arbitrum (Gauge 0x7611DDC8b5029184f900a5a1Dca5C1610684F71e):
 * - Has CRV emissions
 * - claimable_tokens() ✅ WORKS - Returns CRV rewards (tested: 0.000542 CRV)
 * - claimable_reward(user, CRV) ❌ Returns 0 for CRV token
 * - balanceOf() ✅ WORKS - Returns staked LP tokens (tested: 0.0457 LP)
 * - reward_count() returns 1 (CRV only)
 * 
 * Test #2 - Polygon (Gauge 0x41CB0cb61C11039459Dc81DB76BD64d3EdE704F2):
 * - NO CRV emissions, has miMATIC + WMATIC rewards
 * - claimable_tokens() ✅ Returns 0 (no CRV as expected)
 * - claimable_reward(user, miMATIC) ✅ WORKS - Returns 0.0000695 miMATIC
 * - claimable_reward(user, WMATIC) ✅ Returns 0 (no rewards yet)
 * - balanceOf() ✅ WORKS - Returns 97.57 LP tokens staked
 * - reward_count() ✅ Returns 2 (WMATIC + miMATIC)
 * - reward_tokens(0) ✅ Returns WMATIC address
 * - reward_tokens(1) ✅ Returns miMATIC address
 * 
 * RECOMMENDATION:
 * - Use claimable_tokens() for CRV rewards (when gauge has CRV emissions)
 * - Use claimable_reward(user, token) for extra/non-CRV rewards
 * - Use reward_count() + reward_tokens(i) to enumerate all reward tokens
 */
interface IRewardsGauge {
    // ============ Staking Functions ============
    
    /**
     * @notice Deposit (stake) LP tokens into the gauge
     * @param _value The amount of LP tokens to deposit
     */
    function deposit(uint256 _value) external;
    
    /**
     * @notice Withdraw (unstake) LP tokens from the gauge
     * @param _value The amount of LP tokens to withdraw
     */
    function withdraw(uint256 _value) external;
    
    /**
     * @notice Get the staked balance of LP tokens for an account
     * @param account The address to check
     * @return The amount of LP tokens staked in the gauge
     */
    function balanceOf(address account) external view returns (uint256);
    
    // ============ Reward Query Functions ============
    
    /**
     * @notice Get the number of reward tokens for this gauge
     * @return The count of reward tokens
     * @dev TESTED: Returns 1 for CRV-only gauges, 2+ for gauges with extra rewards
     */
    function reward_count() external view returns (uint256);
    
    /**
     * @notice Get the reward token address at a specific index
     * @param index The index of the reward token (0-based)
     * @return The address of the reward token
     * @dev TESTED: Use with reward_count() to enumerate all reward tokens
     */
    function reward_tokens(uint256 index) external view returns (address);
    
    /**
     * @notice Get claimable CRV tokens for an account
     * @param _addr The address to check rewards for
     * @return The claimable amount of CRV tokens
     * @dev TESTED: This is the reliable method for querying CRV rewards (Arbitrum test)
     */
    function claimable_tokens(address _addr) external view returns (uint256);
    
    /**
     * @notice Get claimable amount of a specific reward token
     * @param _addr The address to check rewards for
     * @param _token The reward token address to query
     * @return The claimable amount of the specified token
     * @dev TESTED: Works for non-CRV rewards (Polygon miMATIC test), returns 0 for CRV on some gauges
     */
    function claimable_reward(address _addr, address _token) external view returns (uint256);
    
    // ============ Reward Claiming Functions ============
    
    /**
     * @notice Claim all available rewards for an address
     * @param _addr The address to claim rewards for
     * @dev Claims both CRV and any extra reward tokens
     */
    function claim_rewards(address _addr) external;
    
    // ============ Helper/Utility Functions ============
    
    /**
     * @notice Get the factory address that deployed this gauge
     * @return The factory contract address
     * @dev Used to get the CRV minter on L2 networks
     */
    function factory() external view returns (address);
    
    /**
     * @notice Get the reward contract address (if applicable)
     * @return The address of the reward contract
     */
    function reward_contract() external view returns (address);
    
    /**
     * @notice Get the BAL pseudo minter address (for Balancer gauges)
     * @return The address of the BAL pseudo minter
     */
    function bal_pseudo_minter() external view returns (address);
}

"
    },
    "contracts/giddyVaultV3/strategies/GiddyBaseStrategyV3.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED

pragma solidity ^0.8.19;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";

import "../libraries/GiddyLibraryV3.sol";
import "../infra/GiddyAdapterManager.sol";
import "../infra/GiddyStrategyFactory.sol";
import "../interfaces/IGiddyFeeConfig.sol";

/**
 * @title GiddyBaseStrategyV3
 * @notice Base strategy contract for Giddy V3 vaults
 * @dev Implements centralized strategy management pattern for efficient configuration
 *      Provides common functionality for all V3 strategies
 *      Child contracts override specific yield farming logic (_deposit, _withdraw, etc.)
 *      Designed to work with BeaconProxy pattern for upgradeability
 */
abstract contract GiddyBaseStrategyV3 is
    PausableUpgradeable,
    ReentrancyGuardUpgradeable
{
    using SafeERC20 for IERC20;

    // ============ Structs ============

    struct StrategyInitParams {
        string name;
        address vaultToken;
        address factory;
        address vault;
        address[] rewardTokens;
    }

    struct RewardTokenInfo {
        address token;
        uint256 balance; // held + claimable
    }

    // ============ Errors ============

  error UnauthorizedCaller(address caller);
  error StrategyPaused();
  error NotManager();
  error AdapterZapFailed();
  error DepositExceedsCapacity(uint256 amount, uint256 remaining);

  event YieldStats(uint256 vaultYield1, uint256 vaultYield2, uint256 tokenYield);
  event BalanceStats(uint256 balanceOne, uint256 balanceTwo);

    // ============ State Variables ============

    address public vault;
    address public vaultToken;
    address public factory;
    uint256 public lastProcessYield;
    string public name;

  // Yield Tracking
  address[] public rewardTokens;
  uint256 public lastVaultTokenBalance;
  uint256 public lastVaultTokenGrowthIndex;
  mapping(address => uint256) public lastBaseTokensGrowthIndexes;
  uint256 public performanceFees;
  uint256 public strategyGrowthIndex;
  uint256 public cumulativeYield;

    // ============ Modifiers ============

    modifier onlyVault() {
        if (_msgSender() != vault) {
            revert UnauthorizedCaller(msg.sender);
        }
        _;
    }

    modifier ifNotPaused() {
        if (paused()) revert StrategyPaused();
        if (
            GiddyStrategyFactory(factory).globalPause() ||
            GiddyStrategyFactory(factory).strategyPause(stratName())
        ) revert StrategyPaused();
        _;
    }

    modifier onlyManager() {
        _checkManager();
        _;
    }

    // ============ Initialization ============

    /**
     * @notice Initialize the base strategy
     * @param params Struct containing all strategy initialization parameters
     * @dev This function should be called by child contracts in their initialize function
     */
    function __BaseStrategy_init(
        StrategyInitParams memory params
    ) internal onlyInitializing {
        require(params.vaultToken != address(0), "Invalid vaultToken address");
        require(params.factory != address(0), "Invalid factory address");
        require(params.vault != address(0), "Invalid vault address");

        __Pausable_init();
        __ReentrancyGuard_init();

        vaultToken = params.vaultToken;
        factory = params.factory;
        vault = params.vault;
        name = params.name;
        strategyGrowthIndex = 1e18;

        // Add reward tokens
        for (uint256 i = 0; i < params.rewardTokens.length; i++) {
            addRewardToken(params.rewardTokens[i]);
        }

        GiddyAdapterManager adapter = _adapterManager();

        // Initialize growth index tracking
        if (adapter.getTokenAdapter(vaultToken) != address(0)) {
            lastVaultTokenGrowthIndex = adapter.getGrowthIndex(vaultToken);

            address[] memory baseTokens = adapter.getBaseTokens(vaultToken);
            uint256 len = baseTokens.length;
            for (uint256 i = 0; i < len; ++i) {
                address baseToken = baseTokens[i];
                if (adapter.getTokenAdapter(baseToken) != address(0)) {
                    try adapter.getGrowthIndex(baseToken) returns (
                        uint256 index
                    ) {
                        lastBaseTokensGrowthIndexes[baseToken] = index;
                    } catch {
                        lastBaseTokensGrowthIndexes[baseToken] = 1e18;
                    }
                } else {
                    lastBaseTokensGrowthIndexes[baseToken] = 1e18;
                }
            }
        } else {
            lastVaultTokenGrowthIndex = 1e18;
        }
    }

    // ============ Core Operations ============

  function deposit(uint256[] calldata amounts, bool recordBalance) external onlyVault ifNotPaused nonReentrant {
    address adapter = _adapterManager().getTokenAdapter(vaultToken);
    if (adapter != address(0)) {
      (bool success,) = adapter.delegatecall(
        abi.encodeWithSignature("zapIn(address,uint256[])", vaultToken, amounts)
      );
      if (!success) {
        revert AdapterZapFailed();
      }
    }
    
    uint256 vaultTokenAmount = _balanceInContract();
    uint256 remainingCapacity = getRemainingCapacity();
    if (vaultTokenAmount > remainingCapacity) {
        revert DepositExceedsCapacity(vaultTokenAmount, remainingCapacity);
    }
    _deposit(vaultTokenAmount);
    if (recordBalance) {
      lastVaultTokenBalance = balanceOf();
    }
  }

    function withdraw(
        uint256 amount
    ) external onlyVault ifNotPaused nonReentrant {
        uint256 stakedBalance = _balanceInDefiStrategy();
        uint256 toWithdraw = amount > stakedBalance ? stakedBalance : amount;
        _withdraw(toWithdraw);

        address adapter = _adapterManager().getTokenAdapter(vaultToken);
        if (adapter == address(0)) {
            IERC20(vaultToken).safeTransfer(vault, amount);
        } else {
            (bool success, ) = adapter.delegatecall(
                abi.encodeWithSignature(
                    "zapOut(address,uint256,address)",
                    vaultToken,
                    amount,
                    vault
                )
            );
            if (!success) {
                revert AdapterZapFailed();
            }
        }
        lastVaultTokenBalance = balanceOf();
    }

    // ============ Yield Processing ============

  /**
   * @notice Record yield and accumulate performance fees
   * @dev Only callable by the vault contract
   */
  function recordYield() external onlyVault {
    
    GiddyAdapterManager adapter = _adapterManager();
    IGiddyFeeConfig feeConfig = _giddyFeeConfig();
   
    // 1) Calculate yield from vault token quantity increasing
    uint256 vaultYield1 = balanceOf() - lastVaultTokenBalance;
    emit BalanceStats(balanceOf(), lastVaultTokenBalance);
    
    // 2) Calculate yield from vault token value increasing via growth index
    uint256 vaultYield2 = 0;
    if (adapter.getTokenAdapter(vaultToken) != address(0)) {
      uint256 currentGrowthIndex = adapter.getGrowthIndex(vaultToken);
      if (currentGrowthIndex > lastVaultTokenGrowthIndex) {
        // Calculate yield based on growth index change: ((current - previous) / previous) * balance
        vaultYield2 = ((currentGrowthIndex - lastVaultTokenGrowthIndex) * lastVaultTokenBalance) / lastVaultTokenGrowthIndex;
        lastVaultTokenGrowthIndex = currentGrowthIndex;
      }
    }
    
    // 3) Calculate yield from component tokens
    uint256 tokenYield = _calculateTokenYield();
    
    // TOTAL YIELD since last processing (no reward yield calculation, no compounding)
    uint256 totalYield = vaultYield1 + vaultYield2 + tokenYield;
    emit YieldStats(vaultYield1, vaultYield2, tokenYield);
        
    // Calculate and accumulate PERFORMANCE FEES
    uint256 feeRate = feeConfig.getPerformanceFee(address(this), stratName());
    uint256 performanceFeeAmount = (totalYield * feeRate) / 10000;
    if (performanceFeeAmount > 0) {
      // Add fee to performanceFees instead of transferring immediately
      performanceFees += performanceFeeAmount;
      totalYield -= performanceFeeAmount; // Update total yield to reflect fee deduction
    }
    
    // Update CUMULATIVE YIELD earned and STRATEGY GROWTH INDEX (after fees)
    if (lastVaultTokenBalance > 0 && totalYield > 0) {
      cumulativeYield += totalYield;
      // Formula: newIndex = currentIndex * (1 + yield/balance)
      strategyGrowthIndex = strategyGrowthIndex + (strategyGrowthIndex * totalYield) / lastVaultTokenBalance;
    }
    
    // Update state for next processing
    lastVaultTokenBalance = balanceOf();
    lastProcessYield = block.timestamp;
  }

    /**
     * @notice Collect accumulated performance fees and send to fee recipient
     */
    function collectFees() external onlyManager {
        if (performanceFees == 0) {
            return;
        }

        uint256 amountToCollect = performanceFees;
        performanceFees = 0; // Reset before external calls

        GiddyAdapterManager adapter = _adapterManager();

        if (adapter.getTokenAdapter(vaultToken) != address(0)) {
            address[] memory baseTokens = adapter.getBaseTokens(vaultToken);
            address recipient = _giddyFeeRecipient();
            uint256 len = baseTokens.length;
            for (uint256 i = 0; i < len; ++i) {
                uint256 balance = IERC20(baseTokens[i]).balanceOf(
                    address(this)
                );
                if (balance > 0) {
                    IERC20(baseTokens[i]).safeTransfer(recipient, balance);
                }
            }
        } else {
            IERC20(vaultToken).safeTransfer(
                _giddyFeeRecipient(),
                amountToCollect
            );
        }
    }

    /**
     * @notice Swap reward tokens to base tokens using provided swap data
     * @param swaps Array of swap operations to convert reward tokens to base tokens
     * @dev Called by vault to swap claimed rewards to base tokens
     *      Claims rewards, swaps to base tokens, only swaps tokens that meet threshold
     *      Swaps are structured as: for each reward token, swaps to each base token
     * @return amounts Array of base token amounts received from swaps
     */
    function swapRewardTokens(
        SwapInfo[] calldata swaps
    )
        external
        onlyVault
        ifNotPaused
        nonReentrant
        returns (uint256[] memory amounts)
    {
        _claimAllRewards();

        address[] memory baseTokens = _adapterManager().getBaseTokens(
            vaultToken
        );
        uint256 baseTokensLength = baseTokens.length;
        uint256 swapsLength = swaps.length;
        amounts = new uint256[](baseTokensLength);

        // Execute all configured reward token swaps
        for (uint256 i = 0; i < swapsLength; ++i) {
            SwapInfo calldata swap = swaps[i];
            if (swap.amount == 0) continue;

            uint256 baseTokenIndex = i % baseTokensLength;

            uint256 amountReceived = GiddyLibraryV3.executeSwap(
                swap,
                address(this),
                address(this)
            );
            amounts[baseTokenIndex] += amountReceived;
        }

        return amounts;
    }

    // ============ View Functions (Public) ============

    function isAuthorizedSigner(address _signer) public view returns (bool) {
        return GiddyStrategyFactory(factory).isAuthorizedSigner(_signer);
    }

    function getBaseTokens()
        external
        view
        virtual
        returns (address[] memory tokens)
    {
        tokens = _adapterManager().getBaseTokens(vaultToken);
    }

    function getBaseRatios()
        external
        view
        virtual
        returns (uint256[] memory ratios)
    {
        ratios = _adapterManager().getBaseRatios(vaultToken);
    }

    function getBaseAmounts(
        uint256 amount
    ) external view virtual returns (uint256[] memory amounts) {
        amounts = _adapterManager().getBaseAmounts(vaultToken, amount);
    }

    function balanceOf() public view returns (uint256) {
        return
            _balanceInContract() + _balanceInDefiStrategy() - performanceFees;
    }

    function getRewardTokens() public view returns (address[] memory tokens) {
        return rewardTokens;
    }

    function getRewardInfo()
        external
        view
        returns (RewardTokenInfo[] memory info)
    {
        info = new RewardTokenInfo[](rewardTokens.length);
        for (uint256 i = 0; i < rewardTokens.length; i++) {
            address token = rewardTokens[i];
            uint256 heldBalance = 0;
            uint256 claimableBalance = 0;
            // Get held balance (already claimed rewards in contract)
            try IERC20(token).balanceOf(address(this)) returns (
                uint256 balance
            ) {
                heldBalance = balance;
            } catch {
                heldBalance = 0;
            }
            claimableBalance = _getClaimableBalance(token); // Get claimable balance (not yet claimed)
            info[i] = RewardTokenInfo({
                token: token,
                balance: heldBalance + claimableBalance
            });
        }
        return info;
    }

    function getRemainingCapacity()
        public
        view
        virtual
        returns (uint256 remaining)
    {
        return type(uint256).max; // Default: unlimited
    }

  function getTvl() public view virtual returns (uint256 tvl) {
    return _adapterManager().getTvl(vaultToken);
  }

  function getLiveApr() public view virtual returns (uint256 apr) {
    return _adapterManager().getLiveApr(vaultToken);
  }

    function baseVersion() external pure returns (string memory) {
        return "3.0";
    }

    // ============ Management Functions ============

    function panic() external onlyManager {
        pause();
        uint256 balance = _balanceInDefiStrategy();
        if (balance > 0) {
            _withdraw(balance);
        }
    }

    function pause() public onlyManager {
        _pause();
    }

    function unpause() external onlyManager {
        _unpause();
    }

    function rescueToken(
        address token,
        address to,
        uint256 amount
    ) external onlyManager {
        require(token != vaultToken, "Cannot rescue vaultToken");
        require(to != address(0), "Invalid recipient");

        IERC20(token).safeTransfer(to, amount);
    }

    function addRewardToken(address token) public onlyManager {
        require(token != address(0), "Invalid token");
        require(token != vaultToken, "Cannot add vault token");

        rewardTokens.push(token);
    }

    function removeRewardToken(uint256 index) external onlyManager {
        require(index < rewardTokens.length, "Index out of bounds");

        // Swap with last element and pop
        rewardTokens[index] = rewardTokens[rewardTokens.length - 1];
        rewardTokens.pop();
    }

    function resetRewardTokens() external onlyManager {
        // Clear array
        delete rewardTokens;
    }

    // ============ Internal Helper Functions ============

    function _balanceInContract() internal view returns (uint256) {
        return IERC20(vaultToken).balanceOf(address(this));
    }

    function _adapterManager() internal view returns (GiddyAdapterManager) {
        return
            GiddyAdapterManager(GiddyStrategyFactory(factory).adapterManager());
    }

    function _giddyFeeConfig() internal view returns (IGiddyFeeConfig) {
        return IGiddyFeeConfig(GiddyStrategyFactory(factory).feeConfig());
    }

    function _giddyFeeRecipient() internal view returns (address) {
        return _giddyFeeConfig().feeRecipient();
    }

    function _performanceFee() internal view returns (uint256 fee) {
        return _giddyFeeConfig().getPerformanceFee(address(this), stratName());
    }

    function _checkManager() internal view {
        if (!GiddyStrategyFactory(factory).isKeeper(msg.sender))
            revert NotManager();
    }

    /**
     * @notice Calculate token yield from base tokens and update their tracked growth indexes
     * @return tokenYield Total yield from base tokens
     */
    function _calculateTokenYield() internal returns (uint256 tokenYield) {
        GiddyAdapterManager adapter = _adapterManager();
        address[] memory baseTokens = adapter.getBaseTokens(vaultToken);
        uint256[] memory baseRatios = adapter.getBaseRatios(vaultToken);

        uint256 len = baseTokens.length;
        for (uint256 i = 0; i < len; ++i) {
            address baseToken = baseTokens[i];

            if (adapter.getTokenAdapter(baseToken) != address(0)) {
                try adapter.getGrowthIndex(baseToken) returns (
                    uint256 currentIndex
                ) {
                    uint256 lastIndex = lastBaseTokensGrowthIndexes[baseToken];

                    if (currentIndex > lastIndex) {
                        unchecked {
                            // Calculate yield only on the portion of vault that this base token represents
                            uint256 baseTokenPortion = (lastVaultTokenBalance *
                                baseRatios[i]) / 1e18;
                            uint256 baseTokenYield = ((currentIndex -
                                lastIndex) * baseTokenPortion) / lastIndex;
                            tokenYield += baseTokenYield;
                        }
                        lastBaseTokensGrowthIndexes[baseToken] = currentIndex;
                    }
                } catch {
                    // Skip this base token if growth index call fails
                }
            }
        }

        return tokenYield;
    }

    // ============ Abstract Functions for Child Contracts ============

    function _deposit(uint256 amount) internal virtual;

    function _withdraw(uint256 amount) internal virtual;

    function _balanceInDefiStrategy()
        internal
        view
        virtual
        returns (uint256 balance)
    {
        return IERC20(vaultToken).balanceOf(address(this));
    }

    function _getClaimableBalance(
        address /* token */
    ) internal view virtual returns (uint256 claimable) {
        return 0;
    }

    function _claimAllRewards() internal virtual {}

    function stratName() public view virtual returns (string memory name);

    function version() public pure virtual returns (string memory);
}
"
    },
    "node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

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

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 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 Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    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 Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            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 silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}
"
    },
    "node_modules/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Pausable
    struct PausableStorage {
        bool _paused;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;

    function _getPausableStorage() private pure returns (PausableStorage storage $) {
        assembly {
            $.slot := PausableStorageLocation
        }
    }

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    function __Pausable_init() internal onlyInitializing {
    }

    function __Pausable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        PausableStorage storage $ = _getPausableStorage();
        return $._paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = false;
        emit Unpaused(_msgSender());
    }
}
"
    },
    "node_modules/@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuardUpgradeable is Initializable {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
    struct ReentrancyGuardStorage {
        uint256 _status;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
        assembly {
            $.slot := ReentrancyGuardStorageLocation
        }
    }

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        $._status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if ($._status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        $._status = ENTERED;
    }

    function _nonReentrantAfter() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        $._status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        return $._status == ENTERED;
    }
}
"
    },
    "contracts/giddyVaultV3/libraries/GiddyLibraryV3.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.19;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

struct SwapInfo {
  address fromToken;
  address toToken;
  uint256 amount;
  address aggregator;
  bytes data;
}

library GiddyLibraryV3 {
  using SafeERC20 for IERC20;

  address private constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

  function executeSwap(SwapInfo calldata swap, address srcAccount, address dstAccount) internal returns (uint256 returnAmount) {
    bool isFromTokenNative = swap.fromToken == NATIVE_TOKEN || swap.fromToken == address(0);
    bool isToTokenNative = swap.toToken == NATIVE_TOKEN || swap.toToken == address(0);

    if (!isFromTokenNative) {
      SafeERC20.safeIncreaseAllowance(IERC20(swap.fromToken), swap.aggregator, swap.amount);
    }

    uint256 srcBalanceBefore = isFromTokenNative ? srcAccount.balance : IERC20(swap.fromToken).balanceOf(srcAccount);
    uint256 dstBalanceBefore = isToTokenNative ? dstAccount.balance : IERC20(swap.toToken).balanceOf(dstAccount);
    
    (bool swapSuccess, ) = isFromTokenNative ? swap.aggregator.call{value: swap.amount}(swap.data) : swap.aggregator.call(swap.data);

    if (!swapSuccess) {
      revert("SWAP_CALL_FAILED");
    }
    
    uint256 srcBalanceAfter = isFromTokenNative ? srcAccount.balance : IERC20(swap.fromToken).balanceOf(srcAccount);
    uint256 actualSrcChange = srcBalanceBefore - srcBalanceAfter;
    require(actualSrcChange > 0 && actualSrcChange <= swap.amount, "INVALID_SRC_BALANCE_CHANGE");

    uint256 dstBalanceAfter = isToTokenNative ? dstAccount.balance : IERC20(swap.toToken).balanceOf(dstAccount);
    returnAmount = dstBalanceAfter - dstBalanceBefore;
    require(returnAmount > 0, "SWAP_NO_TOKENS_RECEIVED");
  }
}
"
    },
    "contracts/giddyVaultV3/infra/GiddyAdapterManager.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED

pragma solidity ^0.8.19;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

import "../interfaces/IGiddyDefiAdapter.sol";
import "./GiddyStrategyFactory.sol";

contract GiddyAdapterManager is Initializable, OwnableUpgradeable {
  using SafeERC20 for IERC20;

  address public strategyFactory;
  mapping(address => bytes32) public tokenMap;
  mapping(bytes32 => address) public adapterMap;

  event AdapterSet(string adapterName, address adapterAddress);
  event TokenAdapterSet(address token, string adapterName);

  error NotManager();
  error InvalidAdapter();

  function initialize(address _strategyFactory) public initializer {
    __Ownable_init(_msgSender());
    strategyFactory = _strategyFactory;
  }

  modifier onlyManager() {
    if (!GiddyStrategyFactory(strategyFactory).keepers(msg.sender)) revert NotManager();
    _;
  }

  function getBaseTokens(address defiToken) external view returns (address[] memory tokens) {
    address adapter = getTokenAdapter(defiToken);
    if (adapter == address(0)) {
      tokens = new address[](1);
      tokens[0] = defiToken;
    } else {
      tokens = IGiddyDefiAdapter(adapter).getBaseTokens(defiToken);
    }
  }

  function getBaseRatios(address defiToken) external view returns (uint256[] memory ratios) {
    address adapter = getTokenAdapter(defiToken);
    if (adapter == address(0)) {
      ratios = new uint256[](1);
      ratios[0] = 1e18; // 100% ratio
    } else {
      ratios = IGiddyDefiAdapter(adapter).getBaseRatios(defiToken);
    }
  }

  function getBaseAmounts(address defiToken, uint defiAmount) external view returns (uint256[] memory baseAmounts) {
    address adapter = getTokenAdapter(defiToken);
    if (adapter == address(0)) {
      baseAmounts = new uint256[](1);
      baseAmounts[0] = defiAmount;
    } else {
      baseAmounts = IGiddyDefiAdapter(adapter).getBaseAmounts(defiToken, defiAmount);
    }
  }

  function getBaseComposition(address defiToken) external view returns (uint256[] memory ratios) {
    address adapter = getTokenAdapter(defiToken);
    if (adapter == address(0)) {
      ratios = new uint256[](0);
    } else {
      ratios = IGiddyDefiAdapter(adapter).getBaseComposition(defiToken);
    }
  }

  function getGrowthIndex(address defiToken) external view returns (uint256 index) {
    address adapter = getTokenAdapter(defiToken);
    if (adapter == address(0)) {
      index = 1e18; // Return 1:1 ratio if no adapter
    } else {
      index = IGiddyDefiAdapter(adapter).getGrowthIndex(defiToken);
    }
  }

  function getTvl(address token) external view returns (uint256 defiAmount) {
    address adapter = getTokenAdapter(token);
    if (adapter == address(0)) {
      defiAmount = 0;
    } else {
      defiAmount = IGiddyDefiAdapter(adapter).getTvl(token);
    }
  }

  function getLiveApr(address token) external view returns (uint256 apr) {
    // Live APR in basis points (e.g., 500 = 5%)
    address adapter = getTokenAdapter(token);
    if (adapter == address(0)) {
      apr = 0;
    } else {
      apr = IGiddyDefiAdapter(adapter).getLiveApr(token);
    }
  }

  function setAdapter(string memory adapterName, address adapterAddress) public onlyManager {
    if (bytes(adapterName).length == 0) revert InvalidAdapter();
    adapterMap[keccak256(bytes(adapterName))] = adapterAddress;
    emit AdapterSet(adapterName, adapterAddress);
  }

  function getAdapter(string memory adapterName) public view returns (address adapterAddress) {
    return adapterMap[keccak256(bytes(adapterName))];
  }

  function setTokenAdapter(address token, string memory adapterName) public onlyManager {
    if (bytes(adapterName).length == 0) revert InvalidAdapter();
    tokenMap[token] = keccak256(bytes(adapterName));
    emit TokenAdapterSet(token, adapterName);
  }

  function getTokenAdapter(address token) public view returns (address adapterAddress) {
    return adapterMap[tokenMap[token]];
  }

  function hasAdapter(address token) public view returns (bool) {
    return adapterMap[tokenMap[token]] != address(0);
  }
}"
    },
    "contracts/giddyVaultV3/infra/GiddyStrategyFactory.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED

pragma solidity ^0.8.19;

import "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol";
import "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";

/**
 * @title GiddyStrategyFactory
 * @notice Factory contract for deploying Giddy strategies using BeaconProxy pattern
 * @dev Implements BeaconProxy pattern for gas-efficient strategy deployment
 *      Implements centralized strategy management with pause controls
 */
contract GiddyStrategyFactory is OwnableUpgradeable {


    // ============ State Variables ============

    /// @notice Instance mapping to strategy name with version
    mapping (string => UpgradeableBeacon) public instances;

    /// @notice Deployed strategy types
    string[] public strategyTypes;

    /// @notice Mapping of keeper addresses
    mapping(address => bool) public keepers;

    /// @notice Pause state by strategy name
    mapping(string => bool) public strategyPause;

    /// @notice The fee config address
    address public feeConfig;

    /// @notice The adapter manager address
    address public adapterManager;

    /// @notice The authorized signer address for vault operations
    address public authorizedSigner;

    /// @notice Global pause state for all strategies
    bool public globalPause;

    /// @notice Mapping of authorized signer addresses for vault operations
    mapping(address => bool) public authorizedSigners;

    // ============ Errors ============

    error NotManager();

    // ============ Modifiers ============

    /// @notice Throws if called by any account other than the owner or a keeper
    modifier onlyManager() {
        if (msg.sender != owner() && !keepers[msg.sender]) revert NotManager();
        _;
    }

    // ============ Constructor ============

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /**
     * @notice Initialize the factory
     * @param _owner Owner of the contract
     */
    function initialize(address _owner) external initializer {
        require(_owner != address(0), "Invalid owner address");
        __Ownable_init(_ow

Tags:
ERC20, ERC165, Multisig, Mintable, Pausable, Swap, Liquidity, Staking, Yield, Upgradeable, Multi-Signature, Factory|addr:0x4f46f54abcd2384b9d52609a36e5dc19a6b512fd|verified:true|block:23698028|tx:0x31f11cc4aefff9ebbc2cdd3f9135912442cd4f1e3cb1033545e0c166ebb6b485|first_check:1761925667

Submitted on: 2025-10-31 16:47:47

Comments

Log in to comment.

No comments yet.