SteleFund

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",
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 260
    },
    "viaIR": true,
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    },
    "remappings": []
  },
  "sources": {
    "contracts/SteleFund.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

// Simplified interfaces for Stele integration
import "./interfaces/ISteleFund.sol";
import "./interfaces/ISteleFundInfo.sol";
import "./interfaces/ISteleFundManagerNFT.sol";
import "./libraries/PriceOracle.sol";
import "./libraries/Path.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

interface IWETH9 {
  function deposit() external payable;
  function withdraw(uint256 wad) external;
  function transfer(address to, uint256 value) external returns (bool);
  function transferFrom(address from, address to, uint256 value) external returns (bool);
  function balanceOf(address account) external view returns (uint256);
}

interface ISwapRouter {
  struct ExactInputSingleParams {
    address tokenIn;
    address tokenOut;
    uint24 fee;
    address recipient;
    uint256 deadline;
    uint256 amountIn;
    uint256 amountOutMinimum;
    uint160 sqrtPriceLimitX96;
  }

  struct ExactInputParams {
    bytes path;
    address recipient;
    uint256 deadline;
    uint256 amountIn;
    uint256 amountOutMinimum;
  }

  function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
  function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
}


contract SteleFund is ISteleFund, ReentrancyGuard {
  using PriceOracle for address;
  using Path for bytes;
  using SafeERC20 for IERC20;

  address public override owner;

  // Uniswap V3 Contract
  address public constant swapRouter = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
  address public constant uniswapV3Factory = 0x1F98431c8aD98523631AE4a59f267346ea31F984; // For price oracle

  // Precision scaling for more accurate calculations
  uint256 private constant BASIS_POINTS = 10000; // 100% = 10000 basis points
  
  // Minimum thresholds to prevent dust issues
  uint256 private constant MIN_DEPOSIT_USD = 10; // Minimum $10 deposit
  
  // Maximum fund ID to prevent abuse
  uint256 private constant MAX_FUND_ID = 1000000000; // Maximum 1 billion funds
  
  // Maximum swaps per transaction to prevent DoS
  uint256 private constant MAX_SWAPS_PER_TX = 10;

  address public info;
  address public managerNFTContract; // SteleFundManagerNFT contract address

  uint256 public override managerFee = 100; // 100 : 1%
  uint256 public override maxSlippage = 300; // Maximum 3% slippage allowed (300 = 3%)

  address public weth9;
  address public usdToken;
  address public wbtc;
  address public uni;
  address public link;

  mapping(address => bool) public override isInvestable;


  modifier onlyOwner() {
      require(msg.sender == owner, 'NO');
      _;
  }

  modifier onlyManager(address sender, uint256 fundId) {
    require(fundId == ISteleFundInfo(info).managingFund(sender), "NM");
    _;
  }

  constructor(
    address _info,
    address _weth9,
    address _usdToken,
    address _wbtc,
    address _uni,
    address _link
  ) {
    require(_info != address(0), "ZA");
    require(_weth9 != address(0), "ZA");
    require(_usdToken != address(0), "ZA");
    require(_wbtc != address(0), "ZA");
    require(_uni != address(0), "ZA");
    require(_link != address(0), "ZA");

    info = _info;
    weth9 = _weth9;
    usdToken = _usdToken;
    wbtc = _wbtc;
    uni = _uni;
    link = _link;

    isInvestable[_weth9] = true;
    isInvestable[_usdToken] = true;
    isInvestable[_wbtc] = true;
    isInvestable[_uni] = true;
    isInvestable[_link] = true;

    emit AddToken(_weth9);
    emit AddToken(_usdToken);
    emit AddToken(_wbtc);
    emit AddToken(_uni);
    emit AddToken(_link);

    owner = msg.sender;
  }

  // Safe fund ID parsing from calldata
  function parseFundId(bytes memory data) private pure returns (uint256 fundId) {
    require(data.length == 32, "IDL"); // Must be exactly 32 bytes for uint256
    
    // Use standard ABI decoding for safety
    fundId = abi.decode(data, (uint256));
    
    // Prevent unreasonably large fund IDs
    require(fundId > 0 && fundId <= MAX_FUND_ID, "FID");
  }
  
  // Calculate portfolio total value in USD
  function getPortfolioValueUSD(uint256 fundId) internal view returns (uint256) {
    IToken.Token[] memory fundTokens = ISteleFundInfo(info).getFundTokens(fundId);
    uint256 totalValueUSD = 0;

    for (uint256 i = 0; i < fundTokens.length; i++) {
      if (fundTokens[i].amount > 0) {
        uint256 tokenValueUSD = PriceOracle.getTokenPriceUSD(uniswapV3Factory, fundTokens[i].token, fundTokens[i].amount, weth9, usdToken);
        totalValueUSD += tokenValueUSD;
      }
    }

    return totalValueUSD;
  }

  // Calculate shares to mint based on USD value with improved precision
  function _calculateSharesToMint(uint256 fundId, address token, uint256 amount) private view returns (uint256) {
    uint256 fundShare = ISteleFundInfo(info).getFundShare(fundId);

    // First deposit: shares = USD value of deposit
    if (fundShare == 0) {
      uint256 usdValue = PriceOracle.getTokenPriceUSD(uniswapV3Factory, token, amount, weth9, usdToken);
      return usdValue;
    }
    
    // Get deposit value in USD
    uint256 depositValueUSD = PriceOracle.getTokenPriceUSD(uniswapV3Factory, token, amount, weth9, usdToken);
    if (depositValueUSD == 0) return 0;
    
    // Get current portfolio value in USD
    uint256 portfolioValueUSD = getPortfolioValueUSD(fundId);
    if (portfolioValueUSD == 0) {
      return depositValueUSD;
    }
    
    // Use mulDiv for maximum precision: (depositValue * existingShares) / portfolioValue
    // This avoids intermediate overflow and maintains precision
    uint256 shares = PriceOracle.mulDiv(depositValueUSD, fundShare, portfolioValueUSD);

    // Round up to favor the protocol (prevent rounding attacks)
    if ((depositValueUSD * fundShare) % portfolioValueUSD > 0) {
      shares += 1;
    }
    
    return shares;
  }

  fallback() external payable nonReentrant {
    // ETH deposit with fundId (requires 32 bytes calldata)
    uint256 fundId = parseFundId(msg.data);

    // Verify fund exists (fundId > 0 already checked in parseFundId)
    require(fundId <= ISteleFundInfo(info).fundIdCount(), "FNE");
    require(ISteleFundInfo(info).isJoined(msg.sender, fundId), "US");
    
    // Check minimum USD deposit amount
    {
      uint256 depositUSD = PriceOracle.getTokenPriceUSD(uniswapV3Factory, weth9, msg.value, weth9, usdToken);
      uint8 decimals = IERC20Metadata(usdToken).decimals();
      require(decimals <= 18, "ID"); // Prevent overflow
      require(depositUSD >= MIN_DEPOSIT_USD * (10 ** uint256(decimals)), "MDA"); // Minimum $10 deposit
    }
    
    // Calculate manager fee (only for investors, not manager)
    uint256 feeAmount = 0;
    uint256 fundAmount = msg.value;
    if (msg.sender != ISteleFundInfo(info).manager(fundId)) {
      feeAmount = PriceOracle.mulDiv(msg.value, managerFee, BASIS_POINTS);
      fundAmount = msg.value - feeAmount;
    }
    
    // Calculate shares based on net deposit amount (after fee deduction)
    uint256 sharesToMint = _calculateSharesToMint(fundId, weth9, fundAmount);
    require(sharesToMint > 0, "ZS"); // Zero shares
    
    // Update state FIRST (before external calls)
    ISteleFundInfo(info).increaseFundToken(fundId, weth9, fundAmount); // Net amount to fund pool
    if (feeAmount > 0) {
      ISteleFundInfo(info).increaseFeeToken(fundId, weth9, feeAmount); // Fee amount to fee pool
    }
    (uint256 investorShare, uint256 fundShare) = ISteleFundInfo(info).increaseShare(fundId, msg.sender, sharesToMint);
    
    // External call LAST
    IWETH9(weth9).deposit{value: msg.value}();

    emit Deposit(fundId, msg.sender, weth9, msg.value, investorShare, fundShare, fundAmount, feeAmount);
  }

  receive() external payable {
    require(msg.sender == weth9, "OW"); // Only WETH unwrap
  }

  function withdraw(uint256 fundId, uint256 percentage) external payable override nonReentrant {
    bool isJoined = ISteleFundInfo(info).isJoined(msg.sender, fundId);
    require(isJoined, "US");
    require(percentage > 0 && percentage <= 10000, "IP"); // 0.01% to 100%
    
    uint256 investorShare = ISteleFundInfo(info).getInvestorShare(fundId, msg.sender);
    require(investorShare > 0, "NS");
    
    _withdraw(fundId, investorShare, percentage);
  }
  
  function _withdraw(uint256 fundId, uint256 investorShareBefore, uint256 percentage) private {
    IToken.Token[] memory fundTokens = ISteleFundInfo(info).getFundTokens(fundId);
    uint256 fundShare = ISteleFundInfo(info).getFundShare(fundId);
    require(fundShare > 0, "ZFS"); // Zero fund shares

    uint256 shareToWithdraw = PriceOracle.mulDiv(investorShareBefore, percentage, 10000);
    
    // If shareToWithdraw is 0 due to rounding, just return - no need to complicate
    if (shareToWithdraw == 0) {
      return; // No withdrawal, save gas
    }

    // Update state FIRST (before external calls)
    (uint256 investorShareAfter, uint256 fundShareAfter) = ISteleFundInfo(info).decreaseShare(fundId, msg.sender, shareToWithdraw);

    for (uint256 i = 0; i < fundTokens.length; i++) {
      if (fundTokens[i].amount > 0) {
        // Calculate token amount with overflow protection using mulDiv
        // Calculate token share directly: (amount * investorShareBefore * percentage) / (fundShare * 10000)
        uint256 tokenShare = PriceOracle.mulDiv(
          PriceOracle.mulDiv(fundTokens[i].amount, investorShareBefore, fundShare),
          percentage,
          10000
        );

        // Ensure we don't withdraw more than available
        if (tokenShare > fundTokens[i].amount) {
          tokenShare = fundTokens[i].amount;
        }

        if (tokenShare > 0) {
          address token = fundTokens[i].token;

          // Update state FIRST (before external calls)
          ISteleFundInfo(info).decreaseFundToken(fundId, token, tokenShare);

          // External calls
          if (token == weth9) {
            IWETH9(weth9).withdraw(tokenShare);
            (bool success, ) = payable(msg.sender).call{value: tokenShare}("");
            require(success, "FW");
          } else {
            IERC20(token).safeTransfer(msg.sender, tokenShare);
          }
        }
      }
    }

    emit Withdraw(fundId, msg.sender, percentage, investorShareAfter, fundShareAfter);
  }

  // Get last token from multi-hop path and validate intermediate tokens
  function getLastTokenFromPath(bytes memory path) private view returns (address) {
    address tokenOut;
    uint256 hopCount = 0;
    uint256 MAX_HOPS = 3;

    while (true) {
      require(hopCount < MAX_HOPS, "TMP"); // Too Many Pools

      bool hasMultiplePools = path.hasMultiplePools();
      (, tokenOut, ) = path.decodeFirstPool();

      // Validate intermediate tokens (not first, not last)
      if (hasMultiplePools && hopCount > 0) {
        // Intermediate token must be WETH or USDC
        require(tokenOut == weth9 || tokenOut == usdToken, "IIT"); // Invalid Intermediate Token
      }

      if (!hasMultiplePools) break;
      path = path.skipToken();
      hopCount++;
    }
    return tokenOut;
  }

  // Execute single-hop swap
  function exactInputSingle(uint256 fundId, SwapParams calldata trade) private {
    require(isInvestable[trade.tokenOut], "NWT");
    require(trade.amountIn <= ISteleFundInfo(info).getFundTokenAmount(fundId, trade.tokenIn), "NET");

    // Calculate minimum output with slippage protection (ignores Manager's input)
    uint256 minOutput = _calculateMinOutput(trade.tokenIn, trade.tokenOut, trade.amountIn);

    // Approve with SafeERC20 to prevent approve race condition
    IERC20(trade.tokenIn).safeApprove(swapRouter, 0);
    IERC20(trade.tokenIn).safeApprove(swapRouter, trade.amountIn);

    ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({
      tokenIn: trade.tokenIn,
      tokenOut: trade.tokenOut,
      fee: trade.fee,
      recipient: address(this),
      deadline: block.timestamp + 180, // 3 minutes deadline
      amountIn: trade.amountIn,
      amountOutMinimum: minOutput, // Use calculated minOutput
      sqrtPriceLimitX96: 0
    });

    uint256 amountOut = ISwapRouter(swapRouter).exactInputSingle(params);

    handleSwap(fundId, trade.tokenIn, trade.tokenOut, trade.amountIn, amountOut);
  }

  // Execute multi-hop swap
  function exactInput(uint256 fundId, SwapParams calldata trade) private {
    address tokenOut = getLastTokenFromPath(trade.path);
    (address tokenIn, , ) = trade.path.decodeFirstPool();

    require(isInvestable[tokenOut], "NWT");
    require(trade.amountIn <= ISteleFundInfo(info).getFundTokenAmount(fundId, tokenIn), "NET");

    // Calculate minimum output with slippage protection (ignores Manager's input)
    uint256 minOutput = _calculateMinOutput(tokenIn, tokenOut, trade.amountIn);

    // Approve with SafeERC20 to prevent approve race condition
    IERC20(tokenIn).safeApprove(swapRouter, 0);
    IERC20(tokenIn).safeApprove(swapRouter, trade.amountIn);

    ISwapRouter.ExactInputParams memory params = ISwapRouter.ExactInputParams({
      path: trade.path,
      recipient: address(this),
      deadline: block.timestamp + 180, // 3 minutes deadline
      amountIn: trade.amountIn,
      amountOutMinimum: minOutput // Use calculated minOutput
    });

    uint256 amountOut = ISwapRouter(swapRouter).exactInput(params);

    handleSwap(fundId, tokenIn, tokenOut, trade.amountIn, amountOut);
  }

  // Handle swap state updates
  function handleSwap(
    uint256 fundId,
    address tokenIn,
    address tokenOut,
    uint256 amountIn,
    uint256 amountOut
  ) private {
    ISteleFundInfo(info).decreaseFundToken(fundId, tokenIn, amountIn);
    ISteleFundInfo(info).increaseFundToken(fundId, tokenOut, amountOut);
    emit Swap(fundId, tokenIn, tokenOut, amountIn, amountOut);
  }

  // Calculate minimum output with slippage protection using spot price
  function _calculateMinOutput(
    address tokenIn,
    address tokenOut,
    uint256 amountIn
  ) private view returns (uint256) {
    // Get expected output from oracle (spot price)
    uint256 amountInETH = PriceOracle.getTokenPriceETH(uniswapV3Factory, tokenIn, weth9, amountIn);
    uint256 expectedOutput = PriceOracle.getTokenPriceETH(uniswapV3Factory, weth9, tokenOut, amountInETH);

    // Calculate minimum acceptable output: expectedOutput * (10000 - maxSlippage) / 10000
    uint256 minOutput = PriceOracle.mulDiv(expectedOutput, 10000 - maxSlippage, 10000);

    return minOutput;
  }

  function swap(uint256 fundId, SwapParams[] calldata trades)
    external override onlyManager(msg.sender, fundId) nonReentrant
  {
    require(trades.length <= MAX_SWAPS_PER_TX, "TMS");

    for (uint256 i = 0; i < trades.length; i++) {
      if (trades[i].swapType == SwapType.EXACT_INPUT_SINGLE_HOP) {
        exactInputSingle(fundId, trades[i]);
      } else if (trades[i].swapType == SwapType.EXACT_INPUT_MULTI_HOP) {
        exactInput(fundId, trades[i]);
      }
    }
  }

  function withdrawFee(uint256 fundId, address token, uint256 percentage) 
    external payable override onlyManager(msg.sender, fundId) nonReentrant
  {
    require(percentage > 0 && percentage <= 10000, "IP"); // 0.01% to 100%
    
    uint256 totalFeeAmount = ISteleFundInfo(info).getFeeTokenAmount(fundId, token);
    require(totalFeeAmount > 0, "NF"); // No fee available
    
    // Calculate amount to withdraw using high precision
    uint256 amount = PriceOracle.precisionMul(totalFeeAmount, percentage, 10000);
    
    // If amount is 0 due to rounding, return
    if (amount == 0) {
      return; // Save gas
    }
    
    // Ensure we don't withdraw more than available
    if (amount > totalFeeAmount) {
      amount = totalFeeAmount;
    }
    
    // Update state FIRST (before external calls)
    bool isSuccess = ISteleFundInfo(info).decreaseFeeToken(fundId, token, amount);
    require(isSuccess, "FD");

    // External calls BEFORE event emission (CEI pattern)
    if (token == weth9) {
      IWETH9(weth9).withdraw(amount);
      (bool success, ) = payable(msg.sender).call{value: amount}("");
      require(success, "FW");
    } else {
      IERC20(token).safeTransfer(msg.sender, amount);
    }

    // Event LAST - only emit after successful transfer
    emit WithdrawFee(fundId, msg.sender, token, amount);
  }

  // Transfer ownership (only owner)
  function transferOwnership(address newOwner) external onlyOwner {
    require(newOwner != address(0), "ZA"); // Zero Address
    owner = newOwner;
    emit OwnershipTransferred(msg.sender, newOwner);
  }

  // Renounce ownership of the contract
  function renounceOwnership() external onlyOwner {
    emit OwnershipTransferred(owner, address(0));
    owner = address(0);
  }

  // Set Manager NFT Contract (only callable by info contract owner)
  function setManagerNFTContract(address _managerNFTContract) external override onlyOwner {
    require(_managerNFTContract != address(0), "NZ");
    managerNFTContract = _managerNFTContract;
    emit ManagerNFTContractSet(_managerNFTContract);
  }

  // Mint Manager NFT (only callable by fund manager)
  function mintManagerNFT(uint256 fundId) external override onlyManager(msg.sender, fundId) nonReentrant returns (uint256) {
    require(managerNFTContract != address(0), "NNC"); // NFT Contract Not set
    address manager = ISteleFundInfo(info).manager(fundId);
    require(manager == msg.sender, "NM");

    // Create mint parameters
    MintParams memory params = MintParams({
      fundId: fundId,
      fundCreated: ISteleFundInfo(info).fundCreationBlock(fundId), // Get actual fund creation block
      investment: ISteleFundInfo(info).getFundShare(fundId),
      currentTVL: getPortfolioValueUSD(fundId)
    });

    // Call NFT contract to mint
    return ISteleFundManagerNFT(managerNFTContract).mintManagerNFT(params);
  }
}
"
    },
    "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
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);
}
"
    },
    "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 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 {
    using Address for address;

    /**
     * @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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 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.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @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.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @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).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @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 silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}
"
    },
    "@openzeppelin/contracts/security/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @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 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 ReentrancyGuard {
    // 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;

    uint256 private _status;

    constructor() {
        _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 {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // 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) {
        return _status == _ENTERED;
    }
}
"
    },
    "contracts/libraries/Path.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

import './BytesLib.sol';

/// @title Functions for manipulating path data for multihop swaps
library Path {
    using BytesLib for bytes;

    /// @dev The length of the bytes encoded address
    uint256 private constant ADDR_SIZE = 20;
    /// @dev The length of the bytes encoded fee
    uint256 private constant FEE_SIZE = 3;

    /// @dev The offset of a single token address and pool fee
    uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;
    /// @dev The offset of an encoded pool key
    uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;
    /// @dev The minimum length of an encoding that contains 2 or more pools
    uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;

    /// @notice Returns true iff the path contains two or more pools
    /// @param path The encoded swap path
    /// @return True if path contains two or more pools, otherwise false
    function hasMultiplePools(bytes memory path) internal pure returns (bool) {
        return path.length >= MULTIPLE_POOLS_MIN_LENGTH;
    }

    /// @notice Decodes the first pool in path
    /// @param path The bytes encoded swap path
    /// @return tokenA The first token of the given pool
    /// @return tokenB The second token of the given pool
    /// @return fee The fee level of the pool
    function decodeFirstPool(bytes memory path)
        internal
        pure
        returns (
            address tokenA,
            address tokenB,
            uint24 fee
        )
    {
        tokenA = path.toAddress(0);
        fee = path.toUint24(ADDR_SIZE);
        tokenB = path.toAddress(NEXT_OFFSET);
    }

    /// @notice Skips a token + fee element from the buffer and returns the remainder
    /// @param path The swap path
    /// @return The remaining token + fee elements in the path
    function skipToken(bytes memory path) internal pure returns (bytes memory) {
        return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);
    }
}
"
    },
    "contracts/libraries/PriceOracle.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

// Direct Uniswap V3 interfaces
interface IUniswapV3Factory {
    function getPool(address tokenA, address tokenB, uint24 fee) 
        external view returns (address pool);
}

interface IUniswapV3Pool {
    function slot0() external view returns (
        uint160 sqrtPriceX96,
        int24 tick,
        uint16 observationIndex,
        uint16 observationCardinality,
        uint16 observationCardinalityNext,
        uint8 feeProtocol,
        bool unlocked
    );
}

/// @title Price Oracle Library
/// @notice Library for calculating Spot Prices using Uniswap V3
/// @dev Provides functions for spot price calculation, tick math, and price conversion
library PriceOracle {

    // Standard Uniswap V3 fee tiers - using function to return array
    function getFeeTiers() private pure returns (uint16[3] memory) {
        return [uint16(500), uint16(3000), uint16(10000)]; // 0.05%, 0.3%, 1%
    }

    /// @notice Convert tick to sqrt price ratio
    /// @param tick The tick value
    /// @return sqrtPriceX96 The sqrt price in X96 format
    function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
        require(absTick <= uint256(int256(887272)), 'T');

        uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
        if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
        if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
        if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
        if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
        if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
        if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
        if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
        if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
        if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
        if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
        if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
        if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
        if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
        if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
        if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
        if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
        if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
        if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
        if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;

        if (tick > 0) ratio = type(uint256).max / ratio;

        sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
    }

    /// @notice Full precision multiplication
    /// @param a First number
    /// @param b Second number  
    /// @param denominator Denominator for division
    /// @return result The result of (a * b) / denominator
    function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        uint256 prod0;
        uint256 prod1;
        assembly {
            let mm := mulmod(a, b, not(0))
            prod0 := mul(a, b)
            prod1 := sub(sub(mm, prod0), lt(mm, prod0))
        }

        if (prod1 == 0) {
            require(denominator > 0);
            assembly {
                result := div(prod0, denominator)
            }
            return result;
        }

        require(denominator > prod1);

        uint256 remainder;
        assembly {
            remainder := mulmod(a, b, denominator)
        }
        assembly {
            prod1 := sub(prod1, gt(remainder, prod0))
            prod0 := sub(prod0, remainder)
        }

        uint256 twos = (~denominator + 1) & denominator;
        assembly {
            denominator := div(denominator, twos)
        }

        assembly {
            prod0 := div(prod0, twos)
        }
        assembly {
            twos := add(div(sub(0, twos), twos), 1)
        }
        prod0 |= prod1 * twos;

        uint256 inv = (3 * denominator) ^ 2;
        inv *= 2 - denominator * inv;
        inv *= 2 - denominator * inv;
        inv *= 2 - denominator * inv;
        inv *= 2 - denominator * inv;
        inv *= 2 - denominator * inv;
        inv *= 2 - denominator * inv;

        result = prod0 * inv;
        return result;
    }

    /// @notice Convert tick to price quote
    /// @param tick The tick value
    /// @param baseAmount The base amount to convert
    /// @param baseToken The base token address
    /// @param quoteToken The quote token address
    /// @return quoteAmount The calculated quote amount
    function getQuoteAtTick(
        int24 tick, 
        uint128 baseAmount, 
        address baseToken, 
        address quoteToken
    ) internal pure returns (uint256 quoteAmount) {
        uint160 sqrtRatioX96 = getSqrtRatioAtTick(tick);
        
        // Calculate the price ratio from sqrtRatioX96
        if (sqrtRatioX96 <= type(uint128).max) {
            uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
            quoteAmount = baseToken < quoteToken
                ? mulDiv(ratioX192, baseAmount, 1 << 192)
                : mulDiv(1 << 192, baseAmount, ratioX192);
        } else {
            uint256 ratioX128 = mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
            quoteAmount = baseToken < quoteToken
                ? mulDiv(ratioX128, baseAmount, 1 << 128)
                : mulDiv(1 << 128, baseAmount, ratioX128);
        }
    }

    /// @notice Get quote from pool using spot price
    /// @param pool The pool address
    /// @param baseAmount The base amount
    /// @param baseToken The base token address
    /// @param quoteToken The quote token address
    /// @return quoteAmount The calculated quote amount
    function getQuoteFromPool(
        address pool,
        uint128 baseAmount,
        address baseToken,
        address quoteToken
    ) internal view returns (uint256 quoteAmount) {
        // Use spot price (like Uniswap SwapRouter)
        (, int24 tick, , , , , ) = IUniswapV3Pool(pool).slot0();

        return getQuoteAtTick(tick, baseAmount, baseToken, quoteToken);
    }

    /// @notice Get best quote across multiple fee tiers using spot price
    /// @param factory The Uniswap V3 factory address
    /// @param tokenA First token address
    /// @param tokenB Second token address
    /// @param amountIn Input amount
    /// @return bestQuote The best quote found across all pools
    function getBestQuote(
        address factory,
        address tokenA,
        address tokenB,
        uint128 amountIn
    ) internal view returns (uint256 bestQuote) {
        bestQuote = 0;
        
        uint16[3] memory feeTiers = getFeeTiers();
        for (uint256 i = 0; i < feeTiers.length; i++) {
            address pool = IUniswapV3Factory(factory).getPool(tokenA, tokenB, uint24(feeTiers[i]));
            if (pool == address(0)) {
                continue;
            }

            // Note: Direct call without try-catch since we're in a library
            // The calling contract should handle exceptions
            uint256 quote = getQuoteFromPool(pool, amountIn, tokenA, tokenB);
            if (quote > bestQuote) {
                bestQuote = quote;
            }
        }
    }

    /// @notice Get ETH price in USD using spot price
    /// @dev Reverts if no valid price is available
    /// @param factory The Uniswap V3 factory address
    /// @param weth9 WETH9 token address
    /// @param usdToken USD token address (e.g., USDC)
    /// @return ethPriceUSD ETH price in USD
    function getETHPriceUSD(
        address factory,
        address weth9,
        address usdToken
    ) internal view returns (uint256 ethPriceUSD) {
        uint256 quote = getBestQuote(
            factory,
            weth9,
            usdToken,
            uint128(1e18) // 1 ETH
        );

        require(quote > 0, "No valid ETH price available");
        return quote;
    }

    /// @notice Get token price in ETH using spot price
    /// @param factory The Uniswap V3 factory address
    /// @param token Token address
    /// @param weth9 WETH9 token address
    /// @param amount Token amount
    /// @return ethAmount ETH amount equivalent
    function getTokenPriceETH(
        address factory,
        address token,
        address weth9,
        uint256 amount
    ) internal view returns (uint256 ethAmount) {
        if (token == weth9) {
            return amount; // 1:1 ratio for WETH to ETH
        }

        return getBestQuote(
            factory,
            token,
            weth9,
            uint128(amount)
        );
    }

    /// @notice Get token price in USD using spot price
    /// @param factory The Uniswap V3 factory address
    /// @param token Token address
    /// @param amount Token amount
    /// @param weth9 WETH9 token address
    /// @param usdToken USD token address (e.g., USDC)
    /// @return usdAmount USD amount equivalent
    function getTokenPriceUSD(
        address factory,
        address token,
        uint256 amount,
        address weth9,
        address usdToken
    ) internal view returns (uint256 usdAmount) {
        if (token == weth9) {
            // ETH to USD directly
            uint256 ethPriceUSD = getETHPriceUSD(factory, weth9, usdToken);
            return precisionMul(amount, ethPriceUSD, 1e18);
        } else if (token == usdToken) {
            // USD token (USDC) - return as is
            return amount;
        } else {
            // Other tokens: token -> ETH -> USD
            uint256 ethAmount = getTokenPriceETH(factory, token, weth9, amount);
            if (ethAmount == 0) return 0;

            uint256 ethPriceUSD = getETHPriceUSD(factory, weth9, usdToken);
            return precisionMul(ethAmount, ethPriceUSD, 1e18);
        }
    }
    
    /// @notice High precision multiplication: (a * b) / c
    /// @param a First number
    /// @param b Second number
    /// @param c Divisor
    /// @return result The result of (a * b) / c with high precision
    function precisionMul(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) {
        if (a == 0 || b == 0) return 0;
        require(c > 0, "Division by zero");
        
        uint256 PRECISION_SCALE = 1e18;
        
        // Check if we can safely multiply with precision scale
        if (a <= type(uint256).max / b && (a * b) <= type(uint256).max / PRECISION_SCALE) {
            return (a * b * PRECISION_SCALE) / (c * PRECISION_SCALE);
        }
        
        // Fallback to standard calculation to avoid overflow
        return (a * b) / c;
    }
}"
    },
    "contracts/interfaces/ISteleFundManagerNFT.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

// Mint parameters structure to avoid stack too deep
struct MintParams {
  uint256 fundId;
  uint256 fundCreated;
  uint256 investment;
  uint256 currentTVL;
}

interface ISteleFundManagerNFT {
  // Events
  event ManagerNFTMinted(
    uint256 indexed tokenId,
    uint256 indexed fundId,
    address indexed manager,
    uint256 investment,
    uint256 currentTVL,
    int256 returnRate,
    uint256 fundCreated,
    uint256 mintedAt
  );

  event TransferAttemptBlocked(uint256 indexed tokenId, address indexed from, address indexed to, string reason);

  // Main functions
  function mintManagerNFT(MintParams calldata params) external returns (uint256);
  
  // View functions
  function getTokenData(uint256 tokenId) external view returns (
    uint256 fundId,
    uint256 fundCreated,
    uint256 nftMintBlock,
    uint256 investment,
    uint256 currentTVL,
    int256 returnRate
  );
}"
    },
    "contracts/interfaces/ISteleFundInfo.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

import './IToken.sol';

interface ISteleFundInfo is IToken {
  event InfoCreated();
  event OwnerChanged(address owner, address newOwner);
  event Create(uint256 fundId, address indexed manager);
  event Join(uint256 fundId, address indexed investor);
 
  function owner() external view returns (address _owner);
  function manager(uint256 fundId) external view returns (address _manager);
  function managingFund(address _manager) external view returns (uint256 fundId);
  function fundIdCount() external view returns (uint256 fundCount);
  function fundCreationBlock(uint256 fundId) external view returns (uint256 creationBlock);

  function setOwner(address newOwner) external;
  function create() external returns (uint256 fundId);
  function isJoined(address investor, uint256 fundId) external view returns (bool);
  function join(uint256 fundId) external;

  function getFundTokens(uint256 fundId) external view returns (Token[] memory);
  function getFeeTokens(uint256 fundId) external view returns (Token[] memory);
  function getFundTokenAmount(uint256 fundId, address token) external view returns (uint256);
  function getFeeTokenAmount(uint256 fundId, address token) external view returns (uint256);
  function getFundShare(uint256 fundId) external view returns (uint256);
  function getInvestorShare(uint256 fundId, address investor) external view returns (uint256);

  function increaseFundToken(uint256 fundId, address token, uint256 amount) external;
  function decreaseFundToken(uint256 fundId, address token, uint256 amount) external returns (bool);
  function increaseShare(uint256 fundId, address investor, uint256 amount) external returns (uint256, uint256);
  function decreaseShare(uint256 fundId, address investor, uint256 amount) external returns (uint256, uint256);
  function increaseFeeToken(uint256 fundId, address token, uint256 amount) external;
  function decreaseFeeToken(uint256 fundId, address token, uint256 amount) external returns (bool);
}"
    },
    "contracts/interfaces/ISteleFund.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

interface ISteleFund {
  event Deposit(uint256 fundId, address indexed investor, address token, uint256 amount, uint256 investorShare, uint256 fundShare, uint256 fundAmount, uint256 feeAmount);
  event Withdraw(uint256 fundId, address indexed investor, uint256 percentage, uint256 investorShare, uint256 fundShare);
  event Swap(uint256 fundId, address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);
  event WithdrawFee(uint256 fundId, address indexed manager, address token, uint256 amount);
  event ManagerNFTContractSet(address indexed managerNFTContract);
  event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
  event AddToken(address indexed token);

  function managerFee() external view returns (uint256);
  function maxSlippage() external view returns (uint256);
  function isInvestable(address _token) external view returns (bool);

  enum SwapType {
    EXACT_INPUT_SINGLE_HOP,
    EXACT_INPUT_MULTI_HOP
  }

  struct SwapParams {
    SwapType swapType;
    address tokenIn;
    address tokenOut;
    bytes path;
    uint24 fee;
    uint256 amountIn;
    uint256 amountOutMinimum;
  }

  function owner() external view returns (address);
  function withdraw(uint256 fundId, uint256 percentage) external payable;
  function swap(uint256 fundId, SwapParams[] calldata trades) external;
  function withdrawFee(uint256 fundId, address token, uint256 percentage) external payable;
  function setManagerNFTContract(address _managerNFTContract) external;
  function mintManagerNFT(uint256 fundId) external returns (uint256);
}"
    },
    "contracts/libraries/BytesLib.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * @title Solidity Bytes Arrays Utils
 * @author Gonçalo Sá <goncalo.sa@consensys.net>
 *
 * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
 *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
 */
pragma solidity ^0.8.28;

library BytesLib {
    function slice(
        bytes memory _bytes,
        uint256 _start,
        uint256 _length
    ) internal pure returns (bytes memory) {
        require(_length + 31 >= _length, 'slice_overflow');
        require(_start + _length >= _start, 'slice_overflow');
        require(_bytes.length >= _start + _length, 'slice_outOfBounds');

        bytes memory tempBytes;

        assembly {
            switch iszero(_length)
                case 0 {
                    // Get a location of some free memory and store it in tempBytes as
                    // Solidity does for memory variables.
                    tempBytes := mload(0x40)

                    // The first word of the slice result is potentially a partial
                    // word read from the original array. To read it, we calculate
                    // the length of that partial word and start copying that many
                    // bytes into the array. The first word we copy will start with
                    // data we don't care about, but the last `lengthmod` bytes will
                    // land at the beginning of the contents of the new array. When
                    // we're done copying, we overwrite the full first word with
                    // the actual length of the slice.
                    let lengthmod := and(_length, 31)

                    // The multiplication in the next line is necessary
                    // because when slicing multiples of 32 bytes (lengthmod == 0)
                    // the following copy loop was copying the origin's length
                    // and then ending prematurely not copying everything it should.
                    let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                    let end := add(mc, _length)

                    for {
                        // The multiplication in the next line has the same exact purpose
                        // as the one above.
                        let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                    } lt(mc, end) {
                        mc := add(mc, 0x20)
                        cc := add(cc, 0x20)
                    } {
                        mstore(mc, mload(cc))
                    }

                    mstore(tempBytes, _length)

                    //update free-memory pointer
                    //allocating the array padded to 32 bytes like the compiler does now
                    mstore(0x40, and(add(mc, 31), not(31)))
                }
                //if we want a zero-length slice let's just return a zero-length array
                default {
                    tempBytes := mload(0x40)
                    //zero out the 32 bytes slice we are about to return
                    //we need to do it because Solidity does not garbage collect
                    mstore(tempBytes, 0)

                    mstore(0x40, add(tempBytes, 0x20))
                }
        }

        return tempBytes;
    }

    function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
        require(_start + 20 >= _start, 'toAddress_overflow');
        require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
        address tempAddress;

        assembly {
            tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
        }

        return tempAddress;
    }

    function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
        require(_start + 3 >= _start, 'toUint24_overflow');
        require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');
        uint24 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x3), _start))
        }

        return tempUint;
    }
}
"
    },
    "contracts/interfaces/IToken.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

interface IToken {
  struct Token {
    address token;
    uint256 amount;
  }
}"
    },
    "@openzeppelin/contracts/utils/Address.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}
"
    },
    "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to 

Tags:
ERC20, Multisig, Swap, Upgradeable, Multi-Signature, Factory, Oracle|addr:0x8a37ac980cec4c3a4f791147dc1c06983772c3d5|verified:true|block:23701482|tx:0xf6663b783670bf6dc9e0182e56a8279aaaa714ef0c087e28242d680ffa5003a6|first_check:1761993700

Submitted on: 2025-11-01 11:41:41

Comments

Log in to comment.

No comments yet.