Skip to content
Verified contractPartialMIT

PoolLogicLib

Address0x070ae30cbb97dac35c47a2f6b1f4131e4104dbc3
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.7.6

 

Same code

1 more contract

 

Details

Compiler
solc 0.7.6+commit.7338295f
Language
solidity
Optimization
Yes, 20 runs
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,440,666
Creation transaction
0x9556d7d1ea…0baba341d5
Main copy (most transactions)
0x3823f3fe…dc4552b1

contracts/utils/PoolLogicLib.sol

//
//        __  __    __  ________  _______    ______   ________
//       /  |/  |  /  |/        |/       \  /      \ /        |
//   ____$$ |$$ |  $$ |$$$$$$$$/ $$$$$$$  |/$$$$$$  |$$$$$$$$/
//  /    $$ |$$ |__$$ |$$ |__    $$ |  $$ |$$ | _$$/ $$ |__
// /$$$$$$$ |$$    $$ |$$    |   $$ |  $$ |$$ |/    |$$    |
// $$ |  $$ |$$$$$$$$ |$$$$$/    $$ |  $$ |$$ |$$$$ |$$$$$/
// $$ \__$$ |$$ |  $$ |$$ |_____ $$ |__$$ |$$ \__$$ |$$ |_____
// $$    $$ |$$ |  $$ |$$       |$$    $$/ $$    $$/ $$       |
//  $$$$$$$/ $$/   $$/ $$$$$$$$/ $$$$$$$/   $$$$$$/  $$$$$$$$/
//
// dHEDGE DAO - https://dhedge.org
//
// Copyright (c) 2025 dHEDGE DAO
//
// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";

import {IPoolManagerLogic} from "../interfaces/IPoolManagerLogic.sol";
import {IHasDaoInfo} from "../interfaces/IHasDaoInfo.sol";
import {IHasGuardInfo} from "../interfaces/IHasGuardInfo.sol";
import {IHasPausable} from "../interfaces/IHasPausable.sol";
import {IHasSupportedAsset} from "../interfaces/IHasSupportedAsset.sol";
import {IGovernance} from "../interfaces/IGovernance.sol";
import {IGuard} from "../interfaces/guards/IGuard.sol";
import {IHasOwnable} from "../interfaces/IHasOwnable.sol";
import {IManaged} from "../interfaces/IManaged.sol";
import {IPoolFactory} from "../interfaces/IPoolFactory.sol";
import {IValueManipulationCheck} from "../interfaces/IValueManipulationCheck.sol";
import {ITxTrackingGuard} from "../interfaces/guards/ITxTrackingGuard.sol";
import {IDytmOfficeContractGuard} from "../interfaces/dytm/IDytmOfficeContractGuard.sol";
import {IDytmOffice} from "../interfaces/dytm/IDytmOffice.sol";
import {IAaveLendingPoolAssetGuard} from "../interfaces/guards/IAaveLendingPoolAssetGuard.sol";
import {AddressHelper} from "./AddressHelper.sol";

library PoolLogicLib {
  using SafeMath for uint256;
  using AddressHelper for address;

  struct LiquidityMintTo {
    uint256 recipient;
    uint256 manager;
    uint256 dao;
    uint256 referrer; // portion of manager's entry fee share going to referrer
  }

  struct PoolTokensAllocation {
    uint256 toBurn;
    uint256 toTransferManager;
    uint256 toTransferDao;
    uint256 toGetPortionFrom;
  }

  event TransactionExecuted(address pool, address manager, uint16 transactionType, uint256 time);

  /// @notice Compute how deposited value is split into liquidity tokens for recipient, manager, DAO, and optionally referrer
  /// @dev When a valid referrer address is provided and referral is enabled for the pool,
  ///      a portion of the manager's entry fee share is redirected to the referrer.
  ///      DAO share is never affected. Pass address(0) for no referral.
  function computeLiquidityMintTo(
    uint256 _totalSupply,
    uint256 _depositValue,
    uint256 _totalValue,
    address _poolManagerLogic,
    address _poolFactory,
    address _referrer
  ) external view returns (LiquidityMintTo memory liquidityMintTo) {
    liquidityMintTo = _buildLiquidityMintTo(
      _totalSupply,
      _depositValue,
      _totalValue,
      _poolManagerLogic,
      _poolFactory,
      _referrer
    );

    // Check supply cap only during deposit mintings to avoid withdrawals being halted during PoolLogic::_mintManagerFee()
    _validateMinting(
      _totalSupply,
      liquidityMintTo.recipient.add(liquidityMintTo.manager).add(liquidityMintTo.dao).add(liquidityMintTo.referrer),
      _poolManagerLogic
    );
  }

  function computePoolTokensAllocation(
    uint256 _redeemAmount,
    address _poolManagerLogic,
    address _poolFactory
  ) external view returns (PoolTokensAllocation memory tokens) {
    tokens.toBurn = _redeemAmount;
    tokens.toGetPortionFrom = _redeemAmount;

    (uint256 exitFeeNumerator, uint256 poolFeeShareNumerator, uint256 feeDenominator) = IPoolManagerLogic(
      _poolManagerLogic
    ).getExitFeeInfo();

    // Exit fee is 0, hence burn full amount and process withdrawal according to the portion of this amount.
    if (exitFeeNumerator == 0) {
      return tokens;
    }

    uint256 exitFee = tokens.toBurn.mul(exitFeeNumerator).div(feeDenominator);

    tokens.toGetPortionFrom = tokens.toGetPortionFrom.sub(exitFee);

    uint256 exitFeeToTransfer = exitFee.mul(feeDenominator.sub(poolFeeShareNumerator)).div(feeDenominator);

    // Nothing to transfer to manager or DAO, 100% of exit fee is going to the pool. all tokens are burned, user's portion is reduced on size of the fee.
    if (exitFeeToTransfer == 0) {
      return tokens;
    }

    // Only tokens not intended for transfer are burned, user's portion still reduced on size of the fee.
    tokens.toBurn = tokens.toBurn.sub(exitFeeToTransfer);

    (uint256 daoFeeNumerator, uint256 daoFeeDenominator) = IHasDaoInfo(_poolFactory).getDaoFee();

    tokens.toTransferDao = exitFeeToTransfer.mul(daoFeeNumerator).div(daoFeeDenominator);
    tokens.toTransferManager = exitFeeToTransfer.sub(tokens.toTransferDao);

    require(tokens.toBurn > tokens.toTransferManager && tokens.toTransferManager > tokens.toTransferDao, "dh13");

    return tokens;
  }

  function _buildLiquidityMintTo(
    uint256 _totalSupply,
    uint256 _depositValue,
    uint256 _totalValue,
    address _poolManagerLogic,
    address _poolFactory,
    address _referrer
  ) internal view returns (LiquidityMintTo memory liquidityMintTo) {
    liquidityMintTo.recipient = _totalSupply > 0 ? _depositValue.mul(_totalSupply).div(_totalValue) : _depositValue;

    (uint256 entryFeeNumerator, uint256 poolFeeShareNumerator, uint256 feeDenominator) = IPoolManagerLogic(
      _poolManagerLogic
    ).getEntryFeeInfo();

    if (entryFeeNumerator == 0) {
      return liquidityMintTo;
    }

    uint256 entryFee = liquidityMintTo.recipient.mul(entryFeeNumerator).div(feeDenominator);

    liquidityMintTo.recipient = liquidityMintTo.recipient.sub(entryFee);

    uint256 entryFeeToMint = entryFee.mul(feeDenominator.sub(poolFeeShareNumerator)).div(feeDenominator);

    if (entryFeeToMint == 0) {
      return liquidityMintTo;
    }

    (uint256 daoFeeNumerator, uint256 daoFeeDenominator) = IHasDaoInfo(_poolFactory).getDaoFee();

    liquidityMintTo.dao = entryFeeToMint.mul(daoFeeNumerator).div(daoFeeDenominator);
    liquidityMintTo.manager = entryFeeToMint.sub(liquidityMintTo.dao);

    // Referral split: taken from manager's portion only, DAO share is never affected
    if (_referrer != address(0) && liquidityMintTo.manager > 0) {
      uint256 referrerShareNumerator = IPoolManagerLogic(_poolManagerLogic).getReferralShare();

      if (referrerShareNumerator > 0) {
        liquidityMintTo.referrer = liquidityMintTo.manager.mul(referrerShareNumerator).div(feeDenominator);
        liquidityMintTo.manager = liquidityMintTo.manager.sub(liquidityMintTo.referrer);
      }
    }

    require(
      liquidityMintTo.recipient > liquidityMintTo.manager.add(liquidityMintTo.referrer) &&
        liquidityMintTo.manager.add(liquidityMintTo.referrer) > liquidityMintTo.dao,
      "dh13"
    );

    return liquidityMintTo;
  }

  function _validateMinting(uint256 _totalSupply, uint256 _mintAmount, address _poolManagerLogic) internal view {
    uint256 supplyCap = IPoolManagerLogic(_poolManagerLogic).maxSupplyCap();
    if (supplyCap > 0) {
      require(_totalSupply.add(_mintAmount) <= supplyCap, "dh32");
    }
  }

  /// @notice Calculate lockup cooldown applied to the investor after pool deposit
  /// @param _currentBalance Investor's current pool tokens balance
  /// @param _liquidityMinted Liquidity to be minted to investor after pool deposit
  /// @param _newCooldown New cooldown lockup time
  /// @param _lastCooldown Last cooldown lockup time applied to investor
  /// @param _lastDepositTime Timestamp when last pool deposit happened
  /// @param _blockTimestamp Timestamp of a block
  /// @return cooldown New lockup cooldown to be applied to investor address
  function calculateCooldown(
    uint256 _currentBalance,
    uint256 _liquidityMinted,
    uint256 _newCooldown,
    uint256 _lastCooldown,
    uint256 _lastDepositTime,
    uint256 _blockTimestamp
  ) external pure returns (uint256 cooldown) {
    // Get timestamp when current cooldown ends
    uint256 cooldownEndsAt = _lastDepositTime.add(_lastCooldown);
    // Current exit remaining cooldown
    uint256 remainingCooldown = cooldownEndsAt < _blockTimestamp ? 0 : cooldownEndsAt.sub(_blockTimestamp);
    // If it's first deposit with zero liquidity, no cooldown should be applied
    if (_currentBalance == 0 && _liquidityMinted == 0) {
      cooldown = 0;
      // If it's first deposit, new cooldown should be applied
    } else if (_currentBalance == 0) {
      cooldown = _newCooldown;
      // If zero liquidity or new cooldown reduces remaining cooldown, apply remaining
    } else if (_liquidityMinted == 0 || _newCooldown < remainingCooldown) {
      cooldown = remainingCooldown;
      // For the rest cases calculate cooldown based on current balance and liquidity minted
    } else {
      // If the user already owns liquidity, the additional lockup should be in proportion to their existing liquidity.
      // Calculated as _newCooldown * _liquidityMinted / _currentBalance
      // Aggregate additional and remaining cooldowns
      uint256 aggregatedCooldown = _newCooldown.mul(_liquidityMinted).div(_currentBalance).add(remainingCooldown);
      // Resulting value is capped at new cooldown time (shouldn't be bigger) and falls back to one second in case of zero
      cooldown = aggregatedCooldown > _newCooldown
        ? _newCooldown
        : aggregatedCooldown != 0
          ? aggregatedCooldown
          : 1;
    }
  }

  /// @notice Execute a guarded transaction on behalf of the pool
  /// @dev Resolves the appropriate guard, validates authorization, executes the transaction,
  ///      and handles post-transaction tracking. Called via DELEGATECALL from PoolLogic.
  /// @param _to The destination address for pool to talk to
  /// @param _data The data that going to send in the transaction
  /// @param _isDelegationCallback Whether this transaction is being executed via a delegation callback
  /// @param _factory The pool factory address
  /// @param _poolManagerLogic The pool manager logic address
  /// @return success A boolean for success or fail transaction
  function execTransaction(
    address _to,
    bytes memory _data,
    bool _isDelegationCallback,
    address _factory,
    address _poolManagerLogic
  ) external returns (bool success) {
    require(!IHasPausable(_factory).tradingPausedPools(address(this)), "dh20");

    {
      address checker = IPoolFactory(_factory).valueManipulationCheck();
      if (checker != address(0)) {
        IValueManipulationCheck(checker).checkOperationType(
          address(this),
          IValueManipulationCheck.OperationType.ExecTransaction
        );
      }
    }

    require(_to != address(0), "dh18");

    address guard;
    uint16 txType;
    bool isPublic;

    {
      address contractGuard = IHasGuardInfo(_factory).getContractGuard(_to);

      if (contractGuard != address(0)) {
        guard = contractGuard;
        (txType, isPublic) = IGuard(contractGuard).txGuard(_poolManagerLogic, _to, _data);
      }
    }

    // invalid contract guard call, try asset guard
    if (txType == 0) {
      // no contract guard configured, get asset guard
      address assetGuard = IHasGuardInfo(_factory).getAssetGuard(_to);

      if (assetGuard == address(0)) {
        // If there is no contractGuard and no assetGuard then use the ERC20Guard for the transaction,
        // which will only allow a valid approve transaction
        address governanceAddress = IPoolFactory(_factory).governanceAddress();
        assetGuard = IGovernance(governanceAddress).assetGuards(0); // get ERC20Guard (assetType 0)
      } else {
        // if asset is configured, ensure that it's enabled in the pool
        require(IHasSupportedAsset(_poolManagerLogic).isSupportedAsset(_to), "dh22");
      }
      guard = assetGuard;
      (txType, isPublic) = IGuard(assetGuard).txGuard(_poolManagerLogic, _to, _data);
    }

    require(txType > 0, "dh23");

    {
      address manager = IManaged(_poolManagerLogic).manager();

      require(
        isPublic ||
          _isDelegationCallback ||
          msg.sender == manager ||
          msg.sender == IManaged(_poolManagerLogic).trader() ||
          msg.sender == IHasOwnable(_factory).owner(),
        "dh24"
      );

      success = _to.tryAssemblyCall(_data);

      // call afterTxGuard to track transactions
      // to make it compatible with previous version, we use low-level call before calling afterTxGuard() function
      // the low level call will return `false` if its execution reverts
      // solhint-disable-next-line avoid-low-level-calls
      (bool hasFunction, bytes memory returnData) = guard.call(abi.encodeWithSignature("isTxTrackingGuard()"));
      if (hasFunction && abi.decode(returnData, (bool))) {
        ITxTrackingGuard(guard).afterTxGuard(_poolManagerLogic, _to, _data);
      }

      emit TransactionExecuted(address(this), manager, txType, block.timestamp);
      IPoolFactory(_factory).emitPoolEvent();
    }
  }

  /// @notice Validate delegation callback caller is a legitimate DYTM office
  /// @dev Ensures the caller has a registered contract guard matching the DYTM office,
  ///      and that the original caller context (the account that initiated the delegation call) is this pool.
  ///      This prevents unauthorized contracts from triggering delegation callbacks on behalf of the pool.
  /// @param _factory The pool factory address for guard lookup
  /// @param _caller The msg.sender of the delegation callback (expected to be DYTM office)
  /// @param _self The address of the pool (this) to verify caller context
  function validateDelegationCallback(address _factory, address _caller, address _self) external view {
    address dytmOfficeContractGuard = IHasGuardInfo(_factory).getContractGuard(_caller);
    require(
      dytmOfficeContractGuard != address(0) &&
        _caller == IDytmOfficeContractGuard(dytmOfficeContractGuard).dytmOffice(),
      "dh35"
    );
    address originalCaller = IDytmOffice(_caller).callerContext();
    require(originalCaller == _self, "dh34");
  }

  /// @notice Validate flash loan callback caller is a legitimate Aave lending pool
  /// @dev Ensures the initiator is this pool and the caller has a registered asset guard
  ///      matching the Aave lending pool. Returns the guard for subsequent flashloanProcessing call.
  /// @param _factory The pool factory address for guard lookup
  /// @param _initiator The address that initiated the flash loan (must be this pool)
  /// @param _caller The msg.sender of the flash loan callback (expected to be Aave lending pool)
  /// @param _self The address of the pool (this)
  /// @return aaveLendingPoolAssetGuard The validated asset guard address
  function validateFlashLoanCallback(
    address _factory,
    address _initiator,
    address _caller,
    address _self
  ) external view returns (address aaveLendingPoolAssetGuard) {
    require(_initiator == _self, "dh29");
    aaveLendingPoolAssetGuard = IHasGuardInfo(_factory).getAssetGuard(_caller);
    require(
      aaveLendingPoolAssetGuard != address(0) &&
        _caller == IAaveLendingPoolAssetGuard(aaveLendingPoolAssetGuard).aaveLendingPool(),
      "dh30"
    );
  }
}

@openzeppelin/contracts/math/SafeMath.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        uint256 c = a + b;
        if (c < a) return (false, 0);
        return (true, c);
    }

    /**
     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b > a) return (false, 0);
        return (true, a - b);
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) return (true, 0);
        uint256 c = a * b;
        if (c / a != b) return (false, 0);
        return (true, c);
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b == 0) return (false, 0);
        return (true, a / b);
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b == 0) return (false, 0);
        return (true, a % b);
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");
        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b <= a, "SafeMath: subtraction overflow");
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        if (a == 0) return 0;
        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");
        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b > 0, "SafeMath: division by zero");
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b > 0, "SafeMath: modulo by zero");
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        return a - b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryDiv}.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        return a % b;
    }
}

contracts/interfaces/IGovernance.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;

interface IGovernance {
  function contractGuards(address target) external view returns (address guard);

  function assetGuards(uint16 assetType) external view returns (address guard);
}

contracts/interfaces/IHasDaoInfo.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;

interface IHasDaoInfo {
  function getDaoFee() external view returns (uint256, uint256);

  function daoAddress() external view returns (address);
}

contracts/interfaces/IHasGuardInfo.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;

interface IHasGuardInfo {
  // Get guard
  function getContractGuard(address extContract) external view returns (address);

  // Get asset guard
  function getAssetGuard(address extContract) external view returns (address);
}

contracts/interfaces/IHasOwnable.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;

interface IHasOwnable {
  function owner() external view returns (address);
}

contracts/interfaces/IHasPausable.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;

interface IHasPausable {
  function isPaused() external view returns (bool);

  function pausedPools(address pool) external view returns (bool);

  function tradingPausedPools(address pool) external view returns (bool);
}

contracts/interfaces/IHasSupportedAsset.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma experimental ABIEncoderV2;

interface IHasSupportedAsset {
  struct Asset {
    address asset;
    bool isDeposit;
  }

  function getSupportedAssets() external view returns (Asset[] memory);

  function isSupportedAsset(address asset) external view returns (bool);
}

contracts/interfaces/IManaged.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;

interface IManaged {
  function manager() external view returns (address);

  function trader() external view returns (address);

  function managerName() external view returns (string memory);
}

contracts/interfaces/IPoolFactory.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma abicoder v2;

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

interface IPoolFactory {
  function governanceAddress() external view returns (address);

  function isPool(address pool) external view returns (bool);

  function customCooldownWhitelist(address from) external view returns (bool);

  function receiverWhitelist(address to) external view returns (bool);

  function emitPoolEvent() external;

  function emitPoolManagerEvent() external;

  function isValidAsset(address asset) external view returns (bool);

  function getAssetPrice(address asset) external view returns (uint256);

  function getAssetHandler() external view returns (address);

  function addCustomCooldownWhitelist(address _extAddress) external;

  function createFund(
    bool _privatePool,
    address _manager,
    string memory _managerName,
    string memory _fundName,
    string memory _fundSymbol,
    uint256 _performanceFeeNumerator,
    uint256 _managerFeeNumerator,
    uint256 _entryFeeNumerator,
    uint256 _exitFeeNum,
    IHasSupportedAsset.Asset[] memory _supportedAssets
  ) external returns (address);

  function initialize(
    address _poolLogic,
    address _poolManagerLogic,
    address _assetHandler,
    address _daoAddress,
    address _governanceAddress
  ) external;

  function dataValidator() external view returns (address);

  function valueManipulationCheck() external view returns (address);

  function referralManager() external view returns (address);
}

contracts/interfaces/IPoolManagerLogic.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;

interface IPoolManagerLogic {
  function poolLogic() external view returns (address poolLogicAddress);

  function isDepositAsset(address asset) external view returns (bool isDeposit);

  function validateAsset(address asset) external view returns (bool isValid);

  function assetValue(address asset) external view returns (uint256 value);

  function assetValue(address asset, uint256 amount) external view returns (uint256 value);

  function assetBalance(address asset) external view returns (uint256 balance);

  function factory() external view returns (address factoryAddress);

  function setPoolLogic(address fundAddress) external returns (bool success);

  function totalFundValue() external view returns (uint256 total);

  function totalFundValueWithMaxAge() external view returns (uint256 total);

  function isMemberAllowed(address member) external view returns (bool isAllowed);

  function getFee()
    external
    view
    returns (
      uint256 performanceFeeNumerator,
      uint256 managerFeeNumerator,
      uint256 entryFeeNumerator,
      uint256 exitFeeNumerator,
      uint256 feeDenominator
    );

  function minDepositUSD() external view returns (uint256 minDeposit);

  function getEntryFeeInfo()
    external
    view
    returns (uint256 entryFeeNumerator, uint256 poolFeeShareNumerator, uint256 feeDenominator);

  function getExitFeeInfo()
    external
    view
    returns (uint256 exitFeeNumerator, uint256 poolFeeShareNumerator, uint256 feeDenominator);

  function maxSupplyCap() external view returns (uint256 supplyCap);

  function getReferralShare() external view returns (uint256 shareNumerator);
}

contracts/interfaces/IValueManipulationCheck.sol

//
//        __  __    __  ________  _______    ______   ________
//       /  |/  |  /  |/        |/       \  /      \ /        |
//   ____$$ |$$ |  $$ |$$$$$$$$/ $$$$$$$  |/$$$$$$  |$$$$$$$$/
//  /    $$ |$$ |__$$ |$$ |__    $$ |  $$ |$$ | _$$/ $$ |__
// /$$$$$$$ |$$    $$ |$$    |   $$ |  $$ |$$ |/    |$$    |
// $$ |  $$ |$$$$$$$$ |$$$$$/    $$ |  $$ |$$ |$$$$ |$$$$$/
// $$ \__$$ |$$ |  $$ |$$ |_____ $$ |__$$ |$$ \__$$ |$$ |_____
// $$    $$ |$$ |  $$ |$$       |$$    $$/ $$    $$/ $$       |
//  $$$$$$$/ $$/   $$/ $$$$$$$$/ $$$$$$$/   $$$$$$/  $$$$$$$$/
//
// dHEDGE DAO - https://dhedge.org
//
// Copyright (c) 2025 dHEDGE DAO
//
// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;

/// @title IValueManipulationCheck
/// @notice Interface for the ValueManipulationCheck contract
interface IValueManipulationCheck {
  /// @notice Types of operations that can be performed on a pool
  enum OperationType {
    None,
    Deposit,
    Withdraw,
    ExecTransaction
  }

  /// @notice Checks fund value for manipulation and updates expected value
  /// @dev Called at the start of deposit/withdraw operations.
  ///      On first call: stores expectedFundValueAfter as baseline for next operation
  ///      On subsequent calls: verifies currentFundValue matches expected from previous operation
  /// @param pool The address of the pool being checked
  /// @param currentFundValue The current total fund value
  /// @param expectedFundValueAfter The expected fund value after this operation completes
  function checkValueManipulation(address pool, uint256 currentFundValue, uint256 expectedFundValueAfter) external;

  /// @notice Checks and enforces that the operation type hasn't changed within the transaction
  /// @param pool The address of the pool being checked
  /// @param operationType The type of operation being performed
  function checkOperationType(address pool, OperationType operationType) external;

  /// @notice Gets the stored expected fund value for a pool from transient storage (for testing)
  /// @param pool The address of the pool
  /// @return The stored expected fund value (0 if not set in current transaction)
  function getStoredFundValue(address pool) external view returns (uint256);

  /// @notice Gets the stored operation type for a pool from transient storage (for testing)
  /// @param pool The address of the pool
  /// @return The stored operation type (None if not set in current transaction)
  function getStoredOperationType(address pool) external view returns (OperationType);
}

contracts/interfaces/dytm/IDytmDelegatee.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma experimental ABIEncoderV2;

interface IDytmDelegatee {
  function onDelegationCallback(bytes calldata callbackData) external returns (bytes memory returnData);
}

contracts/interfaces/dytm/IDytmOffice.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma experimental ABIEncoderV2;

import {DytmParamStructs} from "../../utils/dytm/DytmParamStructs.sol";

interface IDytmOffice {
  function delegationCall(
    DytmParamStructs.DelegationCallParams calldata params
  ) external returns (bytes memory returnData);
  function supply(DytmParamStructs.SupplyParams calldata params) external returns (uint256 shares);
  function switchCollateral(
    DytmParamStructs.SwitchCollateralParams calldata params
  ) external returns (uint256 assets, uint256 shares);
  function withdraw(DytmParamStructs.WithdrawParams calldata params) external returns (uint256 assets);
  function borrow(DytmParamStructs.BorrowParams calldata params) external returns (uint256 debtShares);
  function repay(DytmParamStructs.RepayParams calldata params) external returns (uint256 assetsRepaid);
  function transfer(address receiver, uint256 tokenId, uint256 amount) external returns (bool success);
  function isHealthyAccount(uint256 account, uint88 market) external returns (bool isHealthy);
  function callerContext() external view returns (address);
  function getAccountCount() external view returns (uint96 accountCount);
  function createMarket(address officer, address marketConfig) external returns (uint88 marketId);
  function accrueInterest(uint248 key) external returns (uint256 interest);
  function getAllCollateralIds(uint256 account, uint88 market) external view returns (uint256[] memory);
  function getDebtId(uint256 account, uint88 market) external view returns (uint256);
}

contracts/interfaces/dytm/IDytmOfficeContractGuard.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;

interface IDytmOfficeContractGuard {
  function dytmOffice() external view returns (address);

  function dytmPeriphery() external view returns (address);

  function poolFactory() external view returns (address);

  function getOwnedTokenIds(address _poolLogic) external view returns (uint256[] memory);

  function isValidOwnedTokenId(address _poolLogic, uint256 _tokenId) external view returns (bool);

  function poolsWhitelist(address _pool) external view returns (bool);

  function dytmMarketsWhitelist(uint88 _market) external view returns (bool);
}

contracts/interfaces/guards/IAaveLendingPoolAssetGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

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

interface IAaveLendingPoolAssetGuard {
  function flashloanProcessing(
    address pool,
    address repayAsset,
    uint256 repayAmount,
    uint256 premium,
    bytes calldata params
  ) external view returns (IAssetGuard.MultiTransaction[] memory transactions);

  function aaveLendingPool() external view returns (address lendingPool);
}

contracts/interfaces/guards/IAssetGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma experimental ABIEncoderV2;

interface IAssetGuard {
  struct MultiTransaction {
    address to;
    bytes txData;
  }

  function withdrawProcessing(
    address pool,
    address asset,
    uint256 withdrawPortion,
    address to
  ) external returns (address, uint256, MultiTransaction[] memory transactions);

  function getBalance(address pool, address asset) external view returns (uint256 balance);

  function getDecimals(address asset) external view returns (uint256 decimals);

  function removeAssetCheck(address poolLogic, address asset) external view;
}

contracts/interfaces/guards/IGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;

interface IGuard {
  function txGuard(
    address poolManagerLogic,
    address to,
    bytes calldata data
  ) external returns (uint16 txType, bool isPublic); // TODO: eventually update `txType` to be of enum type as per ITransactionTypes
}

contracts/interfaces/guards/ITxTrackingGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;

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

interface ITxTrackingGuard is IGuard {
  function isTxTrackingGuard() external view returns (bool);

  function afterTxGuard(address poolManagerLogic, address to, bytes calldata data) external;
}

contracts/utils/AddressHelper.sol

//
//        __  __    __  ________  _______    ______   ________
//       /  |/  |  /  |/        |/       \  /      \ /        |
//   ____$$ |$$ |  $$ |$$$$$$$$/ $$$$$$$  |/$$$$$$  |$$$$$$$$/
//  /    $$ |$$ |__$$ |$$ |__    $$ |  $$ |$$ | _$$/ $$ |__
// /$$$$$$$ |$$    $$ |$$    |   $$ |  $$ |$$ |/    |$$    |
// $$ |  $$ |$$$$$$$$ |$$$$$/    $$ |  $$ |$$ |$$$$ |$$$$$/
// $$ \__$$ |$$ |  $$ |$$ |_____ $$ |__$$ |$$ \__$$ |$$ |_____
// $$    $$ |$$ |  $$ |$$       |$$    $$/ $$    $$/ $$       |
//  $$$$$$$/ $$/   $$/ $$$$$$$$/ $$$$$$$/   $$$$$$/  $$$$$$$$/
//
// dHEDGE DAO - https://dhedge.org
//
// Copyright (c) 2025 dHEDGE DAO
//
// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;

/**
 * @title A library for Address utils.
 */
library AddressHelper {
  /**
   * @notice try a contract call via assembly
   * @param to the contract address
   * @param data the call data
   * @return success if the contract call is successful or not
   */
  function tryAssemblyCall(address to, bytes memory data) internal returns (bool success) {
    assembly {
      success := call(gas(), to, 0, add(data, 0x20), mload(data), 0, 0)
      switch iszero(success)
      case 1 {
        let size := returndatasize()
        returndatacopy(0x00, 0x00, size)
        revert(0x00, size)
      }
    }
  }

  /**
   * @notice try a contract delegatecall via assembly
   * @param to the contract address
   * @param data the call data
   * @return success if the contract call is successful or not
   */
  function tryAssemblyDelegateCall(address to, bytes memory data) internal returns (bool success) {
    assembly {
      success := delegatecall(gas(), to, add(data, 0x20), mload(data), 0, 0)
      switch iszero(success)
      case 1 {
        let size := returndatasize()
        returndatacopy(0x00, 0x00, size)
        revert(0x00, size)
      }
    }
  }
}

contracts/utils/dytm/DytmParamStructs.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma experimental ABIEncoderV2;

import {IDytmDelegatee} from "../../interfaces/dytm/IDytmDelegatee.sol";

library DytmParamStructs {
  struct MarketId {
    uint88 value; // Underlying value as uint88
  }

  enum TokenType {
    NONE, // 0
    ESCROW, // 1
    LEND, // 2
    DEBT, // 3
    ISOLATED_ACCOUNT // 4
  }

  struct DelegationCallParams {
    IDytmDelegatee delegatee;
    bytes callbackData;
  }

  struct SupplyParams {
    uint256 account;
    uint256 tokenId;
    uint256 assets;
    bytes extraData;
  }

  struct WithdrawParams {
    uint256 account;
    uint256 tokenId;
    address receiver;
    uint256 assets;
    uint256 shares;
    bytes extraData;
  }

  struct BorrowParams {
    uint256 account;
    uint248 key;
    address receiver;
    uint256 assets;
    bytes extraData;
  }

  struct RepayParams {
    uint256 account;
    uint248 key;
    TokenType withCollateralType;
    uint256 assets;
    uint256 shares;
    bytes extraData;
  }

  struct SwitchCollateralParams {
    uint256 account;
    uint256 tokenId;
    uint256 assets;
    uint256 shares;
  }

  struct DebtInfo {
    uint256 debtShares;
    uint256 debtAssets;
    uint256 debtValueUSD;
    uint248 debtKey;
    address debtAsset;
  }
  struct CollateralInfo {
    uint256 tokenId;
    uint256 shares;
    uint256 assets;
    uint256 valueUSD;
    uint256 weightedValueUSD;
    uint64 weight;
    uint248 key;
    address asset;
    TokenType tokenType;
  }

  struct AccountPosition {
    DebtInfo debt;
    CollateralInfo[] collaterals;
    uint256 totalCollateralValueUSD;
    uint256 totalWeightedCollateralValueUSD;
    uint256 healthFactor;
    bool isHealthy;
  }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 20,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.