GiddyVaultV3

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/vaults/GiddyVaultV3.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/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

import "../libraries/GiddyLibraryV3.sol";
import "../interfaces/IGiddyDefiAdapter.sol";
import "../strategies/GiddyBaseStrategyV3.sol";

/**
 * @title GiddyVaultV3
 * @notice Implementation of Giddy V3 vault - the main entry point for users and backend
 * @dev Vault contract handles deposits, withdrawals, and user interactions
 *      Strategy contract handles the actual yield farming logic
 *      Uses user shares system (non-transferrable) instead of ERC20 receipt tokens
 *      Vault token is the single token the vault is denominated in (e.g., USDC, LP token)
 *      Implements standard yield farming pattern with Giddy-specific modifications
 */
contract GiddyVaultV3 is OwnableUpgradeable, ReentrancyGuardUpgradeable {
  using SafeERC20 for IERC20;
  using ECDSA for bytes32;

    /**
     * @dev Struct for authorized deposit/withdrawal operations
     * @param signature EIP-712 signature for authorization
     * @param nonce Unique nonce to prevent replay attacks
     * @param deadline Timestamp after which the authorization expires
     * @param amount Amount of tokens (deposits) or shares (on withdrawals)
     * @param vaultSwaps Array of swap operations for vault deposits/withdrawals
     * @param compoundSwaps Array of swap operations for compounding rewards
     */
  struct VaultAuth {
    bytes signature;
    bytes32 nonce;
    uint256 deadline;
    uint256 amount;
    SwapInfo[] vaultSwaps;
    SwapInfo[] compoundSwaps;
  }

  /**
   * @dev Reward token information struct - must match GiddyBaseStrategyV3.RewardTokenInfo
   * This is defined here so the ABI includes it for proper decoding
   */
  struct RewardTokenInfo {
    address token;
    uint256 balance; // held + claimable
  }

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

  error InvalidAuthorization(string reason);
  error NonceAlreadyUsed(bytes32 nonce);
  error AuthorizationExpired(uint256 deadline);
  error InsufficientShares(uint256 requested, uint256 available);
  error SwapLengthMismatch(uint256 expected, uint256 actual);
  error InvalidSwapToken(address expected, address actual);

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

  string public name;
  address public strategy;
  mapping(address => uint256) public userShares;
  uint256 public totalShares;

  uint256 private constant SHARES_MULTIPLIER = 1e10;
  address private constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
  bytes32 public DOMAIN_SEPARATOR;
  bytes32 public constant VAULTAUTH_TYPEHASH = keccak256("VaultAuth(bytes32 nonce,uint256 deadline,uint256 amount,bytes[] data)");
  
  mapping(bytes32 => bool) public nonceUsed;
  
  // ============ Events ============

  event Deposit(address indexed from, address depositToken, uint256 depositAmount, uint256 sharesMinted);
  event Withdraw(address indexed from, address withdrawToken, uint256 withdrawAmount,uint256 sharesBurned);
  event Yield(uint256 vaultTokens, uint256 totalShares, uint256 growthIndex, uint256 cumulativeYield);
  event StrategyUpgraded(address indexed oldStrategy, address indexed newStrategy);

  // ============ Initializer ============

  function initialize(string memory _name, address _strategy) external initializer {
    name = _name;
    strategy = _strategy;
      
    __Ownable_init(_msgSender());
    __ReentrancyGuard_init();
      

    DOMAIN_SEPARATOR = keccak256(
      abi.encode(
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
        keccak256(bytes(_name)),
        keccak256(bytes("1.0")),
        block.chainid,
        address(this)
      )
    );
  }

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

  function getVaultToken() public view returns (address token) {
    return GiddyBaseStrategyV3(strategy).vaultToken();
  }

  function getBaseTokens() public view returns (address[] memory) {
    return GiddyBaseStrategyV3(strategy).getBaseTokens();
  }

  function getBaseAmounts(uint256 vaultTokens) public view returns (uint256[] memory) {
    return GiddyBaseStrategyV3(strategy).getBaseAmounts(vaultTokens);
  }

  function getBaseRatios() external view returns (uint256[] memory) {
    return GiddyBaseStrategyV3(strategy).getBaseRatios();
  }

  function totalBalance() public view returns (uint256 vaultTokens) {
    return GiddyBaseStrategyV3(strategy).balanceOf();
  }

  function getVaultTokensPerShare() public view returns (uint256 vaultTokens) {
      return sharesToValue(10 ** IERC20Metadata(getVaultToken()).decimals());
  }

  function balanceOfVaultTokens(address user) public view returns (uint256 vaultTokens) {
      uint256 shares = userShares[user];
      if (shares == 0) return 0;
      return sharesToValue(shares);
  }

  function sharesToValue(uint256 shares) public view returns (uint256 vaultTokens) {
    if (totalShares == 0) {
      return 10 ** IERC20Metadata(getVaultToken()).decimals(); // Default 1:1 ratio when no shares exist
    }
    return (shares * totalBalance()) / totalShares;
  }

  function valueToShares(uint256 vaultTokens) public view returns (uint256 shares) {
    if (totalShares == 0) {
      return vaultTokens * SHARES_MULTIPLIER; // First deposit case
    }
    if (totalBalance() == 0) {
      return 0;
    }
    return (vaultTokens * totalShares) / totalBalance();
  }

  function getWithdrawAmounts(uint256 shares) external view returns (uint256[] memory) {
    return getBaseAmounts(sharesToValue(shares));
  }

  function rewardTokens() external view returns (address[] memory tokens) {
    return GiddyBaseStrategyV3(payable(strategy)).getRewardTokens();
  }

  function getRewardInfo() external view returns (RewardTokenInfo[] memory info) {
    // Cast the strategy return to our local struct type (they have the same layout)
    GiddyBaseStrategyV3.RewardTokenInfo[] memory strategyInfo = GiddyBaseStrategyV3(strategy).getRewardInfo();
    
    // Convert to local struct type
    info = new RewardTokenInfo[](strategyInfo.length);
    for (uint256 i = 0; i < strategyInfo.length; i++) {
      info[i] = RewardTokenInfo({
        token: strategyInfo[i].token,
        balance: strategyInfo[i].balance
      });
    }
    return info;
  }

    /**
   * @dev Returns type(uint256).max for unlimited, 0 if full, or actual remaining amount
   */
  function getRemainingCapacity() external view returns (uint256 remaining) {
    return GiddyBaseStrategyV3(strategy).getRemainingCapacity();
  }

  function getTvl() external view returns (uint256 tvl) {
    return GiddyBaseStrategyV3(strategy).getTvl();
  }

  function getLiveApr() external view returns (uint256 apr) {
    //Live APR in basis points (e.g., 500 = 5%)
    return GiddyBaseStrategyV3(strategy).getLiveApr();
  }

  function isAuthorizedSigner(address _signer) public view returns (bool) {
    return GiddyBaseStrategyV3(strategy).isAuthorizedSigner(_signer);
  }

  /**
   * @notice Get the strategy's growth index tracking yield from all sources
   * @return index Growth index (starts at 1e18 = 100%)
   * @dev Growth index increases as yield is recorded, similar to how yield-bearing tokens work
   *      This reflects the actual value growth that users experience
   */
  function getGrowthIndex() public view returns (uint256 index) {
    return GiddyBaseStrategyV3(strategy).strategyGrowthIndex();
  }

  /**
   * @notice Get the cumulative yield earned by the vault in vault tokens
   * @return yield Total yield earned from all sources (after performance fees)
   * @dev This tracks all yield earned over the lifetime of the vault that users actually received
   */
  function getCumulativeYield() public view returns (uint256 yield) {
    return GiddyBaseStrategyV3(strategy).cumulativeYield();
  }

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

  function deposit(VaultAuth calldata auth) external payable nonReentrant {
    _validateAuthorization(auth);

    address sender = _msgSender();
    address[] memory baseTokens = getBaseTokens();
    address depositToken = auth.vaultSwaps[0].fromToken;
  
    _compound(auth.compoundSwaps);
    _recordYield();
    uint256 beforeDeposit = totalBalance();
    
    if (baseTokens.length != auth.vaultSwaps.length) {
      revert SwapLengthMismatch(baseTokens.length, auth.vaultSwaps.length);
    }
    if (!_isNativeToken(depositToken)) {
      IERC20(depositToken).safeTransferFrom(sender, address(this), auth.amount);        
    }

    // Execute swaps and transfer base tokens to strategy
    uint256[] memory amounts = new uint256[](baseTokens.length);
    for (uint256 i = 0; i < baseTokens.length; i++) {
      SwapInfo calldata swap = auth.vaultSwaps[i];
      if (swap.amount > 0) {
        if (baseTokens[i] != swap.toToken) {
          revert InvalidSwapToken(baseTokens[i], swap.fromToken);
        }
        if (baseTokens[i] == swap.fromToken) {
          IERC20(baseTokens[i]).safeTransfer(strategy, swap.amount);
          amounts[i] = swap.amount;
        } else {
          amounts[i] = GiddyLibraryV3.executeSwap(swap, address(this), strategy);
        }
      }
    }
    
    // Calculate shares to mint based on actual value added to the strategy
    GiddyBaseStrategyV3(strategy).deposit(amounts, true);
    uint256 actualValueAdded = totalBalance() - beforeDeposit;

    uint256 newShares = totalShares == 0 ? actualValueAdded * SHARES_MULTIPLIER : actualValueAdded * totalShares / beforeDeposit;
    userShares[sender] += newShares;
    totalShares += newShares;
    emit Deposit(sender, depositToken, auth.amount, newShares);
  }

  function withdraw(VaultAuth calldata auth) external nonReentrant {
    _validateAuthorization(auth);

    address sender = _msgSender();
    address[] memory baseTokens = getBaseTokens();

    _compound(auth.compoundSwaps);
    _recordYield();

    if (userShares[_msgSender()] < auth.amount) {
      revert InsufficientShares(auth.amount, userShares[sender]);
    }
    if (baseTokens.length != auth.vaultSwaps.length) {
      revert SwapLengthMismatch(baseTokens.length, auth.vaultSwaps.length);
    }

    // Calculate vault tokens to withdraw based on shares being withdrawn then burn shares
    uint256 vaultTokensToWithdraw = (auth.amount * totalBalance()) / totalShares;
    userShares[sender] -= auth.amount;
    totalShares -= auth.amount;

    // Withdraws base tokens from the strategy contract and then swaps them to the withdraw token
    GiddyBaseStrategyV3(strategy).withdraw(vaultTokensToWithdraw);
    uint256 totalWithdrawn = 0;
    for (uint256 i = 0; i < baseTokens.length; i++) {
      SwapInfo calldata swap = auth.vaultSwaps[i];
      if (swap.amount > 0) {
        if (baseTokens[i] != swap.fromToken) {
          revert InvalidSwapToken(baseTokens[i], swap.fromToken);
        }
        if (baseTokens[i] == swap.toToken) {
          IERC20(baseTokens[i]).safeTransfer(sender, swap.amount); // no swap needed so sends directly to user
          totalWithdrawn += swap.amount;
        } else {
          uint256 swapReturnAmount = GiddyLibraryV3.executeSwap(swap, address(this), sender);
          totalWithdrawn += swapReturnAmount;
        }
      }
    }
    emit Withdraw(sender, auth.vaultSwaps[0].toToken, totalWithdrawn, auth.amount);
  }

  /**
   * @notice Standalone compound function that can be called to compound rewards
   * @param auth VaultAuth struct containing signature and compound swap data
   * @dev This function allows compounding to be called independently without a deposit/withdrawal
   *      Swaps reward tokens to base tokens, then deposits them back into the strategy
   *      Requires valid authorization signature from owner
   */
  function compound(VaultAuth calldata auth) external nonReentrant {
    _validateAuthorization(auth);
    _compound(auth.compoundSwaps);
    _recordYield();
  }

  function emergencyWithdraw(uint amount) external onlyOwner returns(uint256[] memory amounts) {
    address[] memory baseTokens = getBaseTokens();
    amounts = new uint256[](baseTokens.length);
    for (uint256 i = 0; i < baseTokens.length; i++) {
      amounts[i] = IERC20(baseTokens[i]).balanceOf(address(this));
    }
    GiddyBaseStrategyV3(strategy).withdraw(amount);
    for (uint256 i = 0; i < baseTokens.length; i++) {
      amounts[i] = IERC20(baseTokens[i]).balanceOf(address(this)) -  amounts[i];
    }
    GiddyBaseStrategyV3(strategy).pause();
  }

  function rescueToken(address token, address to, uint256 amount) external onlyOwner {
    require(token != getVaultToken(), "Cannot rescue vault token");
    require(to != address(0), "Invalid recipient");
    IERC20(token).safeTransfer(to, amount);
  }

  /**
   * @notice Upgrade to a new strategy, migrating all funds atomically
   * @param newStrategy Address of the new strategy to migrate to
   * @dev Uses existing withdraw/deposit flow to migrate funds between strategies
   */
  function upgradeStrategy(address newStrategy) external onlyOwner nonReentrant {
    require(newStrategy != address(0), "Invalid strategy address");
    require(newStrategy != strategy, "Same strategy");
    require(address(this) == GiddyBaseStrategyV3(newStrategy).vault(), "Strategy not valid for vault");
    require(getVaultToken() == GiddyBaseStrategyV3(newStrategy).vaultToken(), "Different vault token");
    
    address oldStrategy = strategy;
    uint256 balanceToMigrate = totalBalance();
    
    if (balanceToMigrate > 0) {
      // Withdraw all funds from old strategy
      // This withdraws from DeFi protocol, converts to base tokens via adapter, and sends to vault
      GiddyBaseStrategyV3(oldStrategy).withdraw(balanceToMigrate);
      
      // Get base tokens that were transferred to vault
      address[] memory baseTokens = getBaseTokens();
      uint256[] memory amounts = new uint256[](baseTokens.length);
      
      for (uint256 i = 0; i < baseTokens.length; i++) {
        amounts[i] = IERC20(baseTokens[i]).balanceOf(address(this));
        if (amounts[i] > 0) {
          IERC20(baseTokens[i]).safeTransfer(newStrategy, amounts[i]);
        }
      }
      
      strategy = newStrategy;
      GiddyBaseStrategyV3(newStrategy).deposit(amounts, true);
    } else {
      strategy = newStrategy;
    }
    
    emit StrategyUpgraded(oldStrategy, newStrategy);
  }

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

  function _recordYield() internal {
    GiddyBaseStrategyV3(strategy).recordYield();
    emit Yield(totalBalance(), totalShares, getGrowthIndex(), getCumulativeYield());
  }

  function _compound(SwapInfo[] calldata compoundSwaps) internal {
    if (compoundSwaps.length > 0) {
      uint256[] memory rewardAmounts = GiddyBaseStrategyV3(strategy).swapRewardTokens(compoundSwaps);
      GiddyBaseStrategyV3(strategy).deposit(rewardAmounts, false);
    }
  }

  function _isNativeToken(address token) internal pure returns (bool) {
    return token == NATIVE_TOKEN || token == address(0);
  }

  function _validateAuthorization(VaultAuth calldata auth) internal {

      if (block.timestamp > auth.deadline) {
          revert AuthorizationExpired(auth.deadline);
      }
      if (nonceUsed[auth.nonce]) {
          revert NonceAlreadyUsed(auth.nonce);
      }
      
      bytes memory dataArray;
      for (uint256 i = 0; i < auth.vaultSwaps.length; i++) {
          dataArray = abi.encodePacked(dataArray, keccak256(auth.vaultSwaps[i].data));
      }
      for (uint256 i = 0; i < auth.compoundSwaps.length; i++) {
          dataArray = abi.encodePacked(dataArray, keccak256(auth.compoundSwaps[i].data));
      }
      
      bytes memory data = abi.encodePacked(
          VAULTAUTH_TYPEHASH,
          abi.encode(
              auth.nonce,
              auth.deadline,
              auth.amount,
              keccak256(dataArray)
          )
      );
      // Create EIP-712 hash
      bytes32 digest = keccak256(
          abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, keccak256(data))
      );
      
      // Recover signer and verify against authorized signer
      address signer = digest.recover(auth.signature);
      if (!isAuthorizedSigner(signer)) {
          revert InvalidAuthorization("Invalid signature");
      }
      
      nonceUsed[auth.nonce] = true;
  }

  function version() external pure returns (string memory) {
      return "3.0";
  }
}"
    },
    "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);
}
"
    },
    "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/access/OwnableUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable
    struct OwnableStorage {
        address _owner;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;

    function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
        assembly {
            $.slot := OwnableStorageLocation
        }
    }

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    function __Ownable_init(address initialOwner) internal onlyInitializing {
        __Ownable_init_unchained(initialOwner);
    }

    function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        OwnableStorage storage $ = _getOwnableStorage();
        return $._owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        OwnableStorage storage $ = _getOwnableStorage();
        address oldOwner = $._owner;
        $._owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
"
    },
    "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;
    }
}
"
    },
    "node_modules/@openzeppelin/contracts/utils/cryptography/ECDSA.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(
        bytes32 hash,
        bytes memory signature
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly ("memory-safe") {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}
"
    },
    "node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

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

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

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

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}
"
    },
    "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/interfaces/IGiddyDefiAdapter.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED

pragma solidity ^0.8.19;

interface IGiddyDefiAdapter {
  function getBaseTokens(address defiToken) external view returns (address[] memory tokens);
  function getBaseRatios(address defiToken) external view returns (uint256[] memory ratios);
  function getBaseComposition(address defiToken) external view returns (uint256[] memory ratios);
  function getBaseAmounts(address defiToken, uint256 defiAmount) external view returns (uint256[] memory baseAmounts);
  function getGrowthIndex(address defiToken) external view returns (uint256 index);
  function getTvl(address defiToken) external view returns (uint256 defiAmount);
  function getLiveApr(address defiToken) external view returns (uint256 apr);

  function zapIn(address defiToken, uint256[] memory baseAmounts) external;
  function zapOut(address defiToken, uint256 defiAmount, address receiver) external;  
}"
    },
    "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
            }

Tags:
ERC20, ERC165, Multisig, Pausable, Swap, Yield, Upgradeable, Multi-Signature, Factory|addr:0x8143d2d62594fcaa59cd27b4d4dcc76deaccbcc9|verified:true|block:23698079|tx:0xae5aa42784d20738ae0a3cd742466cfac99cfbf2593cccff5419c5dda4be3314|first_check:1761926256

Submitted on: 2025-10-31 16:57:37

Comments

Log in to comment.

No comments yet.