StrategyCurve

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

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/curve/ICurveGauge.sol";
import "./GiddyBaseStrategyV3.sol";

/**
 * @title StrategyCurve
 * @notice Curve gauge staking strategy for Giddy V3 vaults
 * @dev Implements Curve LP token staking in gauges with reward claiming
 *      Inherits from GiddyBaseStrategyV3 for common functionality
 *      Handles LP token deposits, withdrawals, and reward processing
 *      Used for Curve pools without Convex (direct gauge staking)
 */
contract StrategyCurve is GiddyBaseStrategyV3 {
  using SafeERC20 for IERC20;

  address public gauge;

  event CurveDeposited(uint256 amount, uint256 balance, address gauge);
  event CurveWithdrawn(uint256 amount);

  function initialize(
    StrategyInitParams memory _params,
    address[] memory _rewards,
    uint256[] memory _rewardThresholds,
    address _gauge
  ) external initializer {
    __BaseStrategy_init(_params);
    
    // Add reward tokens using validated function
    for (uint256 i = 0; i < _rewards.length; i++) {
      addRewardToken(_rewards[i], _rewardThresholds[i]);
    }
    
    gauge = _gauge;

    // Approve gauge to spend LP tokens
    IERC20(vaultToken).approve(gauge, type(uint256).max);
  }

  function _deposit(uint256 amount) internal override {
    if (amount > 0) {
      ICurveGauge(gauge).deposit(amount);
    }
    uint256 balance = IERC20(vaultToken).balanceOf(address(this));
    emit CurveDeposited(amount, balance, gauge);
  }

  function _withdraw(uint256 amount) internal override {
    if (amount > 0) {
      ICurveGauge(gauge).withdraw(amount);
    }
    emit CurveWithdrawn(amount);
  }

  function _emergencyWithdraw() internal override {
    uint256 balance = _balanceInDefiStrategy();
    if (balance > 0) {
      ICurveGauge(gauge).withdraw(balance);
    }
  }

  function _claimAllRewards() internal override {
    ICurveGauge(gauge).claim_rewards();
  }

  function _balanceInDefiStrategy() internal view override returns (uint256 balance) {
    return ICurveGauge(gauge).balanceOf(address(this));
  }

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

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

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

"
    },
    "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/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}
"
    },
    "contracts/giddyVaultV3/interfaces/curve/ICurveGauge.sol": {
      "content": "// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

/**
 * @title ICurveGauge
 * @notice Interface for Curve liquidity gauge contracts
 * @dev Handles LP token staking and reward claiming in Curve gauges
 */
interface ICurveGauge {
    /**
     * @notice Deposit LP tokens into the gauge
     * @param amount Amount of LP tokens to deposit
     */
    function deposit(uint256 amount) external;
    
    /**
     * notice Deposit LP tokens into the gauge for a specific user
     * @param amount Amount of LP tokens to deposit
     * @param user Address to deposit for
     */
    function deposit(uint256 amount, address user) external;
    
    /**
     * @notice Withdraw LP tokens from the gauge
     * @param amount Amount of LP tokens to withdraw
     */
    function withdraw(uint256 amount) external;
    
    /**
     * @notice Get balance of staked LP tokens for an account
     * @param account Account address
     * @return balance Amount of staked LP tokens
     */
    function balanceOf(address account) external view returns (uint256);
    
    /**
     * @notice Claim all pending rewards
     */
    function claim_rewards() external;
    
    /**
     * @notice Claim rewards for a specific user
     * @param user User address
     */
    function claim_rewards(address user) external;
    
    /**
     * @notice Get claimable reward amount for a specific token
     * @param user User address
     * @param token Reward token address
     * @return claimable Amount of claimable rewards
     */
    function claimable_reward(address user, address token) external view returns (uint256);
}

"
    },
    "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;
        string feeCategory;
        address vaultToken;
        address factory;
        address vault;
    }

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

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

    error UnauthorizedCaller(address caller);
    error StrategyPaused();
    error NotManager();
    error AdapterZapFailed();

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

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

    // Yield Tracking
    address[] public rewardTokens;
    mapping(address => uint256) public rewardThresholds;
    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;
        feeCategory = params.feeCategory;
        strategyGrowthIndex = 1e18;
        
        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) external onlyVault ifNotPaused nonReentrant {
      uint amount = amounts[0];
      address adapter = _adapterManager().getTokenAdapter(vaultToken);
      if (adapter != address(0)) {
        amount = IERC20(vaultToken).balanceOf(address(this));
        (bool success,) = adapter.delegatecall(
          abi.encodeWithSignature("zapIn(address,uint256[])", vaultToken, amounts)
        );
        if (!success) {
          revert AdapterZapFailed();
        }
        amount = IERC20(vaultToken).balanceOf(address(this)) - amount;
      }
      _deposit(amount);
      lastVaultTokenBalance = balanceOf();
    }

    function withdraw(uint256 amount) external onlyVault ifNotPaused nonReentrant {
      _withdraw(amount);
      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
     * @return yieldRecorded Amount of yield recorded
     */
    function recordYield() external onlyVault returns (uint256 yieldRecorded) {
        
        GiddyAdapterManager adapter = _adapterManager();
        IGiddyFeeConfig feeConfig = _giddyFeeConfig();
       
        // 1) Calculate yield from vault token quantity increasing
        uint256 vaultYield1 = 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;
            
        // Calculate and accumulate PERFORMANCE FEES
        uint256 feeRate = feeConfig.getPerformanceFee(address(this), feeCategory);
        uint256 performanceFeeAmount;
        unchecked { // Safe: totalYield * feeRate < 2^256 (feeRate <= 10000)
            performanceFeeAmount = (totalYield * feeRate) / 10000; // Basis points
        }
        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;
        return totalYield;
    }

    /**
     * @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 rewardTokensLength = rewardTokens.length;
        uint256 swapsLength = swaps.length;
        amounts = new uint256[](baseTokensLength);
        
        // Pre-check which reward tokens meet threshold
        bool[] memory shouldCompoundReward = new bool[](rewardTokensLength);
        for (uint256 j = 0; j < rewardTokensLength; ++j) {
            address rewardToken = rewardTokens[j];
            uint256 rewardBalance = IERC20(rewardToken).balanceOf(address(this));
            shouldCompoundReward[j] = rewardBalance >= rewardThresholds[rewardToken];
        }
        
        // Execute swaps for reward tokens that meet threshold
        for (uint256 i = 0; i < swapsLength; ++i) {
            SwapInfo calldata swap = swaps[i];
            if (swap.amount == 0) continue;
            
            uint256 rewardTokenIndex = i / baseTokensLength;
            uint256 baseTokenIndex = i % baseTokensLength;
            
            if (shouldCompoundReward[rewardTokenIndex]) {
                uint256 amountReceived = GiddyLibraryV3.executeSwap(swap, address(this), address(this));
                amounts[baseTokenIndex] += amountReceived;
            }
        }
        
        return amounts;
    }

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

    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
        try IERC20(token).balanceOf(address(this)) returns (uint256 balance) {
          heldBalance = balance;
        } catch {
          heldBalance = 0;
        }
        
        // Get claimable balance
        claimableBalance = _getClaimableBalance(token);
        
        info[i] = RewardTokenInfo({
          token: token,
          balance: heldBalance + claimableBalance,
          threshold: rewardThresholds[token]
        });
      }
      return info;
    }

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

    function getAPY() external view virtual returns (uint256 apy) {
        return 0;
    }

    function getTvl() public view virtual returns (uint256 tvl) {
        if (_adapterManager().getTokenAdapter(vaultToken) != address(0)) {
            try _adapterManager().getTvl(vaultToken) returns (uint256 adapterTvl) {
                return adapterTvl;
            } catch {
                
                return balanceOf(); // Fall back to strategy balance if adapter call fails
            }
        }
        return balanceOf(); // Default implementation returns strategy balance
    }

    function getLiveApr() public view virtual returns (uint256 apr) {
        if (_adapterManager().getTokenAdapter(vaultToken) != address(0)) {
            try _adapterManager().getLiveApr(vaultToken) returns (uint256 adapterApr) {
                return adapterApr;
            } catch {
                return 0; // Fall back to 0 if adapter call fails
            }
        }
        return 0; // Default implementation returns 0 - child contracts should override
    }

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

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

    function panic() external onlyManager {
        pause();
        _emergencyWithdraw();
    }

    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, uint256 threshold) public onlyManager {
      require(token != address(0), "Invalid token");
      require(token != vaultToken, "Cannot add vault token");
      require(threshold > 0, "Threshold required");
      
      rewardTokens.push(token);
      rewardThresholds[token] = threshold;
    }

    function removeRewardToken(uint256 index) external onlyManager {
      require(index < rewardTokens.length, "Index out of bounds");
      
      address tokenToRemove = rewardTokens[index];
      
      // Swap with last element and pop
      rewardTokens[index] = rewardTokens[rewardTokens.length - 1];
      rewardTokens.pop();
      
      // Clear threshold
      delete rewardThresholds[tokenToRemove];
    }

    function resetRewardTokens() external onlyManager {
      // Clear thresholds for all current reward tokens
      for (uint256 i = 0; i < rewardTokens.length; i++) {
        delete rewardThresholds[rewardTokens[i]];
      }
      
      // Clear array
      delete rewardTokens;
    }

    function setRewardThreshold(address token, uint256 threshold) external onlyManager {
      require(threshold > 0, "Threshold required");
      rewardThresholds[token] = threshold;
    }

    // ============ 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), feeCategory);
    }

    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 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 {
                            uint256 baseTokenYield = ((currentIndex - lastIndex) * lastVaultTokenBalance) / 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 _emergencyWithdraw() 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/interfaces/IERC1363.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
"
    },
    "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];
    }

    /**
     * @notice Set the fee config address
     * @param _feeConfig New fee config address
     */
    function setFeeConfig(address _feeConfig) external onlyOwner {
        require(_feeConfig != address(0), "Invalid fee config address");
        feeConfig = _feeConfig;
    }

    /**
     * @notice Set the adapter manager address
     * @param _adapterManager New adapter manager address
     */
    function setAdapterManager(address _adapterManager) external onlyOwner {
        require(_adapterManager != address(0), "Invalid adapter manager address");
        adapterManager = _adapterManager;
    }

    /**
     * @notice Set the authorized signer address
     * @param _authorizedSigner New authorized signer address
     * @param _authorized Whether the signer is authorized
     */
    function setAuthorizedSigner(address _authorizedSigner, bool _authorized) external onlyOwner {
      authorizedSigners[_authorizedSigner] = _authorized;
    }

    /**
     * @notice Check if an address is an authorized signer
     * @param _signer Address to check
     * @return Whether the address is an authorized signer
     */
    function isAuthorizedSigner(address _signer) external view returns (bool) {
      return authorizedSigners[_signer];
    }

    // ============ View Functions ============

    /**
     * @notice Get the implementation of a strategy type
     * @param _strategyName Name of the strategy
     * @return Implementation address
     */
    function getImplementation(string calldata _strategyName) external view returns (address) {
        return instances[_strategyName].implementation();
    }

    /**
     * @notice Get the array of deployed strategy types
     * @return Array of deployed strategy types
     */
    function getStrategyTypes() external view returns (string[] memory) {
        return strategyTypes;
    }
}"
    },
    "contracts/giddyVaultV3/interfaces/IGiddyFeeConfig.sol": {
      "content": "// SPDX-License

Tags:
ERC20, ERC165, Multisig, Pausable, Swap, Liquidity, Staking, Yield, Upgradeable, Multi-Signature, Factory|addr:0xab1a8e81fc4161749a68ee0415516450fe1940e2|verified:true|block:23647714|tx:0x95d5a36f991e62cdcd5e3d20eb9c3b0a2bf4430622bc669931de9122841e2a52|first_check:1761330975

Submitted on: 2025-10-24 20:36:15

Comments

Log in to comment.

No comments yet.