StrategyYieldBasis

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/StrategyYieldBasis.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.19;

import "../interfaces/yieldbasis/IYieldBasisLT.sol";
import "../interfaces/yieldbasis/IYieldBasisGauge.sol";
import "../interfaces/yieldbasis/IYieldBasisFactory.sol";
import "../interfaces/yieldbasis/IYieldBasisOracle.sol";
import "../interfaces/IERC4626.sol";
import "./GiddyBaseStrategyV3.sol";

/**
 * @title StrategyYieldBasis
 * @notice YieldBasis strategy for Giddy V3 vaults
 * @dev Implements YieldBasis LT token deposits with gauge staking for YB rewards
 *      Inherits from GiddyBaseStrategyV3 for common functionality
 *      Handles deposits of WBTC/cbBTC/tBTC into YieldBasis LT contracts
 *      Automatically stakes received LT tokens in gauges to earn YB emissions
 */
contract StrategyYieldBasis is GiddyBaseStrategyV3 {
  using SafeERC20 for IERC20;

  // ============ Constants ============

  // YieldBasis Factory contract address (constant across all markets)
  address public constant FACTORY = 0x370a449FeBb9411c95bf897021377fe0B7D100c0;
  // Swap address for reserve deposits
  address public constant SWAP_ADDRESS = 0x8276f373E5c107fF9c4672e3Eb89abc7f8c493f8;

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

  // Market-specific contract addresses
  address public ltToken;      // YieldBasis LT token (yb-WBTC, yb-cbBTC, or yb-tBTC)
  address public gauge;        // YieldBasis gauge for staking LT tokens
  address public oracle;       // Price oracle for the LT token
  uint256 public marketId;     // Market ID in Factory (0=WBTC, 1=cbBTC, 2=tBTC)

  bool public swapForDeposits;  // If true, deposit via swap address; if false, deposit directly to protocol

  // ============ Events ============

  event DepositRouteChanged(bool swapForDeposits);

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

  /**
   * @notice Initialize the YieldBasis strategy
   * @param _params Strategy initialization parameters (name, vaultToken, factory, vault, rewardTokens)
   * @param _ltToken Address of the YieldBasis LT token contract
   * @param _gauge Address of the YieldBasis gauge contract for staking
   * @param _oracle Address of the price oracle for the LT token
   * @param _marketId Market ID in the Factory contract
   */
  function initialize(StrategyInitParams memory _params, address _ltToken, address _gauge, address _oracle, uint256 _marketId) external initializer {
    __BaseStrategy_init(_params);

    ltToken = _ltToken;
    gauge = _gauge;
    oracle = _oracle;
    marketId = _marketId;

    // Approve LT token contract to spend vault token (underlying asset)
    IERC20(vaultToken).approve(ltToken, type(uint256).max);
    
    // Approve gauge to spend LT tokens
    IERC20(ltToken).approve(gauge, type(uint256).max);
  }

  // ============ Deposit/Withdraw Functions ============

  /**
   * @notice Deposit vault tokens into YieldBasis and stake LT tokens
   * @param amount The amount of vault tokens to deposit
   * @dev Routes to either direct protocol deposit or swap address deposit based on swapForDeposits flag
   */
  function _deposit(uint256 amount) internal override {
    if (amount == 0) return;

    if (!swapForDeposits) {
      // Direct deposit route (current logic)
      _depositDirect(amount);
    } else {
      // Swap address deposit route
      _depositViaSwapAddress(amount);
    }
  }

  /**
   * @notice Direct deposit into YieldBasis protocol
   * @param amount The amount of vault tokens to deposit
   * @dev 1. Deposits underlying asset (WBTC/cbBTC/tBTC) into LT contract
   *      2. Receives LT tokens (yb-WBTC/yb-cbBTC/yb-tBTC)
   *      3. Stakes LT tokens in gauge to earn YB rewards
   */
  function _depositDirect(uint256 amount) internal {
    // Deposit underlying asset into LT contract to receive LT tokens
    IERC20(vaultToken).approve(ltToken, amount);
    IYieldBasisLT(ltToken).deposit(amount, address(this));

    // Stake all received LT tokens into gauge for YB rewards
    uint256 ltBalance = IERC20(ltToken).balanceOf(address(this));
    if (ltBalance > 0) {
      IERC20(ltToken).approve(gauge, ltBalance);
      IYieldBasisGauge(gauge).deposit(ltBalance);
    }
  }

  /**
   * @notice Deposit via swap address reserves
   * @param amount The amount of vault tokens to deposit
   * @dev 1. Calculates LT tokens needed using current exchange rate
   *      2. Transfers underlying assets to swap address
   *      3. Pulls gauge shares (staked tokens) from swap address
   */
  function _depositViaSwapAddress(uint256 amount) internal {
    // Send vault tokens to swap address
    uint256 ltTokensNeeded = IERC4626(ltToken).previewDeposit(amount);
    IERC20(vaultToken).safeTransfer(SWAP_ADDRESS, amount);

    // Transfer staked tokens to strategy contract
    uint256 gaugeShares = IERC4626(gauge).previewDeposit(ltTokensNeeded);
    IERC20(gauge).safeTransferFrom(SWAP_ADDRESS, address(this), gaugeShares);
  }

  /**
   * @notice Withdraw vault tokens from YieldBasis
   * @param amount The amount of vault tokens to withdraw
   * @dev 1. Unstakes LT tokens from gauge
   *      2. Withdraws underlying asset from LT contract
   */
  function _withdraw(uint256 amount) internal override {
    if (amount > 0) {
      // Unstake LT tokens from gauge
      // Note: LT tokens are initially ~1:1 with underlying asset
      IYieldBasisGauge(gauge).withdraw(amount);

      // Withdraw underlying asset from LT contract
      IYieldBasisLT(ltToken).withdraw(amount, address(this));
    }
  }

  // ============ Balance & Strategy State ============

  /**
   * @notice Get the balance of LT tokens staked in the gauge
   * @return balance The amount of LT tokens staked
   */
  function _balanceInDefiStrategy() internal view override returns (uint256 balance) {
    return IYieldBasisGauge(gauge).balanceOf(address(this));
  }

  // ============ Rewards ============

  function _claimAllRewards() internal override {
    IYieldBasisGauge(gauge).claim_rewards(address(this));
  }

  function _getClaimableBalance(address token) internal view override returns (uint256 claimable) {
    try IYieldBasisGauge(gauge).claimable_reward(address(this), token) returns (uint256 amount) {
      return amount;
    } catch {
      return 0;
    }
  }

  // ============ Getters ============

  /**
   * @notice Get the remaining deposit capacity for this market
   * @return remaining The remaining capacity in terms of underlying asset (vault tokens)
   * @dev If using swap address route, returns swap address's gauge balance converted to underlying.
   *      If using direct route, returns protocol capacity from Factory.
   */
  function getRemainingCapacity() public view override returns (uint256 remaining) {
    if (swapForDeposits) {
      // Calculate capacity based on swap address's gauge balance
      uint256 gaugeShares = IYieldBasisGauge(gauge).balanceOf(SWAP_ADDRESS);
      if (gaugeShares == 0) {
        return 0;
      }
      
      // Convert gauge shares to LT tokens using ERC4626 convertToAssets
      uint256 ltTokens;
      try IERC4626(gauge).convertToAssets(gaugeShares) returns (uint256 assets) {
        ltTokens = assets;
      } catch {
        // Fallback: assume 1:1 if convertToAssets fails
        ltTokens = gaugeShares;
      }
      
      // Convert LT tokens to underlying assets
      return IERC4626(ltToken).convertToAssets(ltTokens);
    } else {
      // Direct deposit route: return protocol capacity
      try IYieldBasisFactory(FACTORY).debt_ceiling(marketId) returns (uint256 ceiling) {
        try IYieldBasisFactory(FACTORY).debt(marketId) returns (uint256 currentDebt) {
          return ceiling > currentDebt ? ceiling - currentDebt : 0;
        } catch {
          return 0;
        }
      } catch {
        return 0;
      }
    }
  }

  function getTvl() public view override returns (uint256 tvl) {
    try IYieldBasisLT(ltToken).totalAssets() returns (uint256 totalAssets) {
      return totalAssets;
    } catch {
      return 0;
    }
  }

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

  function version() public pure override returns (string memory) {
    return "1.0";
  }

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

  function setSwapForDeposits(bool _use) external onlyManager {
    swapForDeposits = _use;
    emit DepositRouteChanged(_use);
  }
}

"
    },
    "contracts/giddyVaultV3/interfaces/yieldbasis/IYieldBasisLT.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

/**
 * @title IYieldBasisLT
 * @notice Interface for YieldBasis LT (Leveraged Token) contracts
 * @dev LT tokens represent leveraged positions (2x) in Curve LP tokens
 *      Users deposit underlying assets (WBTC, cbBTC, tBTC) to receive LT tokens
 *      LT tokens can be staked in gauges to earn YB rewards
 */
interface IYieldBasisLT {
    /**
     * @notice Deposit underlying assets to receive LT tokens
     * @param _amount The amount of underlying assets to deposit
     * @param _receiver The address that will receive the LT tokens
     * @return shares The amount of LT tokens minted
     * @dev This function deposits the underlying asset and mints LT tokens
     *      representing a leveraged position in the corresponding Curve pool
     */
    function deposit(uint256 _amount, address _receiver) external returns (uint256 shares);

    /**
     * @notice Withdraw underlying assets by burning LT tokens
     * @param _shares The amount of LT tokens to burn
     * @param _receiver The address that will receive the underlying assets
     * @return assets The amount of underlying assets returned
     * @dev This function burns LT tokens and returns the underlying assets
     */
    function withdraw(uint256 _shares, address _receiver) external returns (uint256 assets);

    /**
     * @notice Get the LT token balance of an account
     * @param account The address to check
     * @return The amount of LT tokens held by the account
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @notice Get the total assets controlled by the LT contract
     * @return The total amount of underlying assets
     */
    function totalAssets() external view returns (uint256);

    /**
     * @notice Get the underlying asset token address
     * @return The address of the underlying asset (WBTC, cbBTC, or tBTC)
     */
    function asset() external view returns (address);
}

"
    },
    "contracts/giddyVaultV3/interfaces/yieldbasis/IYieldBasisGauge.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

/**
 * @title IYieldBasisGauge
 * @notice Interface for YieldBasis liquidity gauge contracts
 * @dev Handles LT token staking and YB reward distribution
 *      Similar to Curve gauges but for YieldBasis LT tokens
 */
interface IYieldBasisGauge {
    /**
     * @notice Deposit (stake) LT tokens into the gauge
     * @param _value The amount of LT tokens to deposit
     * @dev Stakes LT tokens to earn YB rewards
     */
    function deposit(uint256 _value) external;

    /**
     * @notice Withdraw (unstake) LT tokens from the gauge
     * @param _value The amount of LT tokens to withdraw
     * @dev Unstakes LT tokens (does not claim rewards)
     */
    function withdraw(uint256 _value) external;

    /**
     * @notice Get the staked balance of LT tokens for an account
     * @param _addr The address to check
     * @return The amount of LT tokens staked in the gauge
     */
    function balanceOf(address _addr) external view returns (uint256);

    /**
     * @notice Claim all available rewards for an address
     * @param _addr The address to claim rewards for
     * @dev Claims YB tokens and any other reward tokens
     */
    function claim_rewards(address _addr) external;

    /**
     * @notice Get claimable amount of a specific reward token
     * @param _user The address to check rewards for
     * @param _reward_token The reward token address to query
     * @return The claimable amount of the specified token
     */
    function claimable_reward(address _user, address _reward_token) external view returns (uint256);

    /**
     * @notice Get the number of reward tokens for this gauge
     * @return The count of reward tokens
     */
    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
     */
    function reward_tokens(uint256 _index) external view returns (address);
}

"
    },
    "contracts/giddyVaultV3/interfaces/yieldbasis/IYieldBasisFactory.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

/**
 * @title IYieldBasisFactory
 * @notice Interface for YieldBasis Factory contract
 * @dev The Factory contract manages all markets and their configurations
 *      Each market has a debt ceiling that limits total deposits
 */
interface IYieldBasisFactory {
    /**
     * @notice Get the debt ceiling for a specific market
     * @param _market_id The market ID (0=WBTC, 1=cbBTC, 2=tBTC, etc.)
     * @return The maximum debt allowed for this market
     * @dev The debt ceiling limits how much can be deposited into the market
     */
    function debt_ceiling(uint256 _market_id) external view returns (uint256);

    /**
     * @notice Get the current debt for a specific market
     * @param _market_id The market ID (0=WBTC, 1=cbBTC, 2=tBTC, etc.)
     * @return The current debt in the market
     * @dev Current debt represents how much is currently deposited
     */
    function debt(uint256 _market_id) external view returns (uint256);

    /**
     * @notice Get the total number of markets
     * @return The count of active markets
     */
    function n_markets() external view returns (uint256);

    /**
     * @notice Get market information
     * @param _market_id The market ID
     * @return lt The LT token address
     * @return amm The AMM contract address
     * @return stablecoin The stablecoin address
     * @return cryptopool The Curve cryptopool address
     * @return oracle The oracle contract address
     * @return virtual_pool The virtual pool contract address
     */
    function markets(uint256 _market_id) external view returns (
        address lt,
        address amm,
        address stablecoin,
        address cryptopool,
        address oracle,
        address virtual_pool
    );
}

"
    },
    "contracts/giddyVaultV3/interfaces/yieldbasis/IYieldBasisOracle.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

/**
 * @title IYieldBasisOracle
 * @notice Interface for YieldBasis price oracle contracts
 * @dev Provides price feeds for LT tokens in terms of underlying assets
 *      Each market has its own oracle (CryptopoolLPOracle)
 */
interface IYieldBasisOracle {
    /**
     * @notice Get the current price of the LT token
     * @return The price of the LT token (in 18 decimals)
     * @dev Returns the price of the LT token in terms of the underlying asset
     *      Used for TVL calculations and position valuation
     */
    function price() external view returns (uint256);

    /**
     * @notice Get the price with safe bounds checking
     * @return The price of the LT token with additional safety checks
     */
    function price_w() external view returns (uint256);
}

"
    },
    "contracts/giddyVaultV3/interfaces/IERC4626.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

/**
 * @title IERC4626
 * @notice Minimal ERC4626 interface for exchange rate calculations
 * @dev Only includes functions needed for this contract
 */
interface IERC4626 {
  function previewDeposit(uint256 assets) external view returns (uint256 shares);
  function convertToShares(uint256 assets) external view returns (uint256 shares);
  function convertToAssets(uint256 shares) external view returns (uint256 assets);
}

"
    },
    "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, denominated in vault tokens
  }

  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 && lastIndex > 0) {
            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(_owner);
    }

        // ============ Core Functions ============

    /**
     * @notice Add a new strategy beacon to the factory
     * @param _strategyName Name of the strategy
     * @param _implementation Implementation address
     */
    function addStrategyBeacon(string calldata _strategyName, address _implementation) external onlyManager {
        require(address(instances[_strategyName]) == address(0), "Strategy type already exists");

        instances[_strategyName] = new UpgradeableBeacon(_implementation, address(this));
        strategyTypes.push(_strategyName);
    }

    /**
     * @notice Create a new strategy proxy
     * @param _strategyName Type of strategy to create
     * @return strategy Address of the created strategy proxy
     */
    function createStrategyProxy(string calldata _strategyName) external onlyManager returns (address strategy) {
        UpgradeableBeacon instance = instances[_strategyName];
        require(address(instance) != address(0), "Strategy type not found");
        
        BeaconProxy proxy = new BeaconProxy(address(instance), "");
        strategy = address(proxy);
        return strategy;
    }

    /**
     * @notice Upgrade the implementation of a strategy beacon
     * @param _strategyName Name of the strategy
     * @param _newImplementation New implementation address
     */
    function upgradeStrategyBeacon(string calldata _strategyName, address _newImplementation) external onlyOwner {
        UpgradeableBeacon instance = instances[_strategyName];
        require(address(instance) != address(0), "Strategy type not found");
        
        instance.upgradeTo(_newImplementation);
    }

    // ============ Pause Management ============

    /**
     * @notice Set global pause state
     * @param _paused Whether to pause all strategies
     */
    function setGlobalPause(bool _paused) external onlyManager {
        globalPause = _paused;
    }

    /**
     * @notice Set strategy-specific pause state
     * @param strategyName Name of the strategy
     * @param _paused Whether to pause the strategy
     */
    function setStrategyPause(string calldata strategyName, bool _paused) external onlyManager {
        strategyPause[strategyName] = _paused;
    }

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

    /**
     * @notice Add a keeper address
     * @param _keeper Keeper address to add
     */
    function addKeeper(address _keeper) external onlyOwner {
        require(_keeper != address(0), "Invalid keeper address");
        require(!keepers[_keeper], "Keeper already exists");
        keepers[_keeper] = true;
    }

    /**
     * @notice Remove a keeper address
     * @param _keeper Keeper address to remove
     */
    function removeKeeper(address _keeper) external onlyOwner {
        require(keepers[_keeper], "Keeper does not exist");
        keepers[_keeper] = false;
    }

    /**
     * @notice Check if an address is a keeper
     * @param _keeper Address to check
     * @return isKeeper Whether the address is a keeper
     */
    function isKeeper(address _keeper) external view returns (bool) {
        return keepers[_keeper

Tags:
ERC20, ERC165, Multisig, Pausable, Swap, Liquidity, Staking, Yield, Upgradeable, Multi-Signature, Factory, Oracle|addr:0xb25310bf09951dde087f583736b56708bb009c57|verified:true|block:23730699|tx:0x03e134b17d6c66fd0bede257198af6879e5b4f80f13440c9fee4e570efdc8104|first_check:1762342920

Submitted on: 2025-11-05 12:42:01

Comments

Log in to comment.

No comments yet.