Skip to content
Verified contractExactMIT

OndoGMTokenAssetGuard

Address0x43151b7c381675bddae7f86e229bf72f39b41791
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.7.6

 

Same code

Only this contract

 

Details

Compiler
solc 0.7.6+commit.7338295f
Language
solidity
Optimization
Yes, 20 runs
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,490,269
Creation transaction
0xc15f9b853c…5afb377e62

53 files

contracts/guards/assetGuards/ondo/OndoGMTokenAssetGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

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

import {ERC20Guard} from "../ERC20Guard.sol";
import {NonDepositAssetGuard} from "../shared/NonDepositAssetGuard.sol";
import {IAssetGuard} from "../../../interfaces/guards/IAssetGuard.sol";
import {IComplexAssetGuard} from "../../../interfaces/guards/IComplexAssetGuard.sol";
import {IERC20Extended} from "../../../interfaces/IERC20Extended.sol";
import {IGMTokenManager} from "../../../interfaces/ondo/IGMTokenManager.sol";
import {IOndoGMSwap} from "../../../interfaces/ondo/IOndoGMSwap.sol";
import {IPoolLogic} from "../../../interfaces/IPoolLogic.sol";
import {IPoolManagerLogic} from "../../../interfaces/IPoolManagerLogic.sol";
import {AutomationBase} from "../../../utils/chainlink/AutomationBase.sol";
import {WithdrawalHelperLib} from "../../../utils/WithdrawalHelperLib.sol";

/// @title Ondo GM Token asset guard
/// @dev Asset type = 41
/// @notice Redeems the depositor's portion of GM to USDC atomically inside
///         `PoolLogic._withdrawProcessing` via `OndoGMSwap.swapExactInWithAttestation`.
/// @dev    Inherits `ERC20Guard` for `getBalance` / `getDecimals` / `removeAssetCheck`. The
///         5-arg `IComplexAssetGuard` overload does the redeem and requires a signed Ondo
///         attestation in `withdrawData`; raw GM is never delivered. The 4-arg overload
///         (empty `withdrawData`) reverts — unless the depositor's GM portion is sub-$1 dust
///         that Ondo can't swap, in which case it skips the redeem and leaves the dust behind.
contract OndoGMTokenAssetGuard is ERC20Guard, IComplexAssetGuard, AutomationBase, NonDepositAssetGuard {
  using SafeMath for uint256;

  /// @notice Frontend-supplied per-withdrawal payload, embedded into `ComplexAsset.withdrawData`.
  /// @dev    `tokenIn` is `_asset` (PoolLogic-supplied), `tokenOut` is the immutable `usdc`,
  ///         and `amountIn` is `quote.quantity` — none of those are passed by the frontend so
  ///         calldata cannot redirect the swap. `amountOutMinimum` lets the frontend tighten
  ///         the USDC floor above the on-chain 1% cap; it cannot loosen it.
  struct OndoWithdrawData {
    bytes attestationSignature;
    IGMTokenManager.Quote quote;
    uint256 amountOutMinimum;
  }

  uint256 internal constant BPS_DENOMINATOR = 10_000;

  /// @dev Maximum allowed shortfall of `amountOutMinimum` vs. the deterministic USDon
  ///      redemption value (= quote.quantity × quote.price / 1e18). Bounds how aggressively
  ///      a frontend can understate the USDC floor so PoolLogic's net-slippage check can't
  ///      be sidestepped by pairing a large slippageTolerance with a near-zero amountOutMinimum.
  uint256 internal constant MAX_AMOUNT_OUT_MIN_DISCOUNT_BPS = 100; // 1%

  address public immutable ondoGMSwap;

  address public immutable usdc;

  /// @notice One-sided tolerance (bps) for `quote.quantity` undershoot vs on-chain portion.
  ///         Absorbs sim→exec drift; quote.quantity must NEVER exceed portionAmount.
  uint256 public immutable mismatchDeltaNumerator;

  /// @notice Minimum USD value (1e18-scaled) of a GM portion for a redeem to be attempted.
  ///         Below this the portion is left in the pool as dust — Ondo rejects sub-$1 swaps.
  ///         Set above $1 to absorb oracle-vs-attestation price drift.
  uint256 public immutable minRedeemValue;

  constructor(address _ondoGMSwap, uint256 _mismatchDeltaNumerator, uint256 _minRedeemValue) {
    require(_ondoGMSwap != address(0), "invalid ondoGMSwap");
    require(_mismatchDeltaNumerator <= MAX_AMOUNT_OUT_MIN_DISCOUNT_BPS, "invalid mismatch delta");
    require(_minRedeemValue >= 1e18, "invalid minRedeemValue");

    ondoGMSwap = _ondoGMSwap;
    usdc = IOndoGMSwap(_ondoGMSwap).usdc();
    mismatchDeltaNumerator = _mismatchDeltaNumerator;
    minRedeemValue = _minRedeemValue;
  }

  /// @notice Runs when `withdrawData` is empty. Reverts — a redeem needs a signed Ondo
  ///         attestation via the 5-arg overload — unless the GM portion is worth less than
  ///         `minRedeemValue`: Ondo can't swap sub-$1 dust, so it is left in the pool.
  /// @dev    Returns `address(0)` so PoolLogic skips the dh26 net-slippage check entirely;
  ///         nothing is transferred to the investor for this asset, dust is left in the pool.
  function withdrawProcessing(
    address _pool,
    address _asset,
    uint256 _withdrawPortion,
    address /* _to */
  )
    external
    view
    override
    returns (address withdrawAsset, uint256 withdrawBalance, IAssetGuard.MultiTransaction[] memory transactions)
  {
    uint256 portionAmount = _portionAmount(_pool, _asset, _withdrawPortion);
    require(_isBelowMinRedeemValue(_pool, _asset, portionAmount), "withdrawData required");
    return (withdrawAsset, withdrawBalance, transactions);
  }

  /// @inheritdoc IComplexAssetGuard
  function withdrawProcessing(
    address _pool,
    address _asset,
    uint256 _withdrawPortion,
    address /* _to */,
    bytes memory _withdrawData
  )
    external
    view
    override
    returns (address withdrawAsset, uint256 withdrawBalance, IAssetGuard.MultiTransaction[] memory transactions)
  {
    OndoWithdrawData memory data = abi.decode(_withdrawData, (OndoWithdrawData));

    // The per-user GM share is deterministic (balance × portion / 1e18). The frontend
    // calls `previewGmTokenAmount` via `callStatic` to obtain the exact amount and then
    // requests an Ondo attestation quote sized for that result.
    // ONE-SIDED tolerance: quote.quantity must NEVER exceed portionAmount (otherwise the pool
    // would redeem more GM than the user is entitled to and the user extracts value from
    // other LPs — PoolLogic's slippage check is a lower bound on USDC received, not an upper
    // bound on GM consumed). A small undershoot is allowed for sim→exec drift; any leftover
    // GM stays in the pool.
    uint256 portionAmount = _portionAmount(_pool, _asset, _withdrawPortion);
    _assertQuoteQuantityWithinDelta(data.quote.quantity, portionAmount, mismatchDeltaNumerator);

    // USDon is swapped to USDC by USDonManager — the only leg with price variance, with
    // `amountOutMinimum` as its floor. Bound that floor here so it can't be set unreasonably low.
    // Comparison assumes 1 USDon ≈ 1 USDC (Ondo's USDonManager redeems USDon for USDC at par).
    {
      uint256 amountOutMinD18 = data.amountOutMinimum.mul(1e18).div(10 ** IERC20Extended(usdc).decimals());
      require(
        amountOutMinD18.mul(BPS_DENOMINATOR) >=
          _redemptionUSDonValueD18(data.quote).mul(BPS_DENOMINATOR.sub(MAX_AMOUNT_OUT_MIN_DISCOUNT_BPS)),
        "amountOutMinimum too low"
      );
    }

    transactions = _buildRedeemTransactions(
      _pool,
      _asset,
      data.quote.quantity,
      data.amountOutMinimum,
      data.attestationSignature,
      data.quote
    );

    withdrawAsset = usdc;
    // Note that `withdrawBalance` is 0 because PoolLogic will handle the withdrawn portion from Ondo GM redemption
    return (withdrawAsset, withdrawBalance, transactions);
  }

  /// @notice GM token amount a withdrawer gets for a pool token amount; sizes `quote.quantity`
  ///         for the Ondo attestation.
  /// @dev    State mutating (mints manager fee for an accurate totalSupply) — call via `callStatic`.
  ///         Output is shaved 0.01% to stay at or below the on-chain `portionAmount` if fees
  ///         accrue between simulation and execution.
  /// @param _pool            The pool logic address
  /// @param _asset           The Ondo GM token address
  /// @param _poolTokenAmount The amount of pool tokens to be withdrawn
  /// @return gmTokenAmount   The GM token amount to be withdrawn (rounded down)
  function previewGmTokenAmount(
    address _pool,
    address _asset,
    uint256 _poolTokenAmount
  ) external cannotExecute returns (uint256 gmTokenAmount) {
    (uint256 portion, ) = WithdrawalHelperLib.calculateWithdrawalPortion(_pool, _poolTokenAmount);
    uint256 portionAmount = _portionAmount(_pool, _asset, portion);
    // Mirrors the 4-arg `withdrawProcessing` dust guard: when the portion is worth less than
    // `minRedeemValue` (including zero-balance) no attestation is needed, so signal that to
    // the frontend by returning 0.
    if (_isBelowMinRedeemValue(_pool, _asset, portionAmount)) return 0;
    // `_portionAmount` does getBalance × portion / 1e18 — division rounds down.
    // Shave 0.01% so quoted amount stays at or below the on-chain `portionAmount` despite fee accrual.
    gmTokenAmount = WithdrawalHelperLib.applyPortionShrinkBuffer(portionAmount);
  }

  function _portionAmount(address _pool, address _asset, uint256 _portion) internal view returns (uint256) {
    return getBalance(_pool, _asset).mul(_portion).div(1e18);
  }

  /// @dev True when `_amount` of `_asset` is worth less than `minRedeemValue` per the pool's
  ///      oracle. Valued on-chain so the skip decision can't be manipulated via calldata.
  function _isBelowMinRedeemValue(address _pool, address _asset, uint256 _amount) internal view returns (bool) {
    address poolManagerLogic = IPoolLogic(_pool).poolManagerLogic();
    return IPoolManagerLogic(poolManagerLogic).assetValue(_asset, _amount) < minRedeemValue;
  }

  /// @dev One-sided cross-check: `_quoteQuantity` MUST NOT exceed `_reference`, and any
  ///      undershoot must fall within the mismatch-delta band.
  function _assertQuoteQuantityWithinDelta(
    uint256 _quoteQuantity,
    uint256 _reference,
    uint256 _mismatchDelta
  ) internal pure {
    require(_quoteQuantity <= _reference, "quote quantity > reference");
    require(
      _reference.sub(_quoteQuantity) <= _reference.mul(_mismatchDelta).div(BPS_DENOMINATOR),
      "quote quantity mismatch"
    );
  }

  /// @dev Deterministic on-chain redemption value of the quote in USDon (D18 fixed-point):
  ///      `quote.quantity × quote.price / 1e18`. Matches GMTokenManager's redemption math.
  function _redemptionUSDonValueD18(IGMTokenManager.Quote memory _quote) internal pure returns (uint256) {
    return _quote.quantity.mul(_quote.price).div(1e18);
  }

  /// @dev Approve + swap calldata for an Ondo GM redemption. Returns 2 txs — the receiver of
  ///      the swap output is `msg.sender` of the swap call, which is the pool when executed by
  ///      PoolLogic via `withdrawProcessing`.
  function _buildRedeemTransactions(
    address _pool,
    address _gmAsset,
    uint256 _amountIn,
    uint256 _amountOutMinimum,
    bytes memory _attestationSignature,
    IGMTokenManager.Quote memory _quote
  ) internal view returns (IAssetGuard.MultiTransaction[] memory transactions) {
    transactions = new IAssetGuard.MultiTransaction[](2);
    transactions[0].to = _gmAsset;
    // Preserve the pool's standing allowance after this redemption spends _amountIn.
    (bool result, uint256 newAllowance) = IERC20Extended(_gmAsset).allowance(_pool, ondoGMSwap).tryAdd(_amountIn);
    transactions[0].txData = abi.encodeWithSelector(
      IERC20Extended.approve.selector,
      ondoGMSwap,
      result ? newAllowance : type(uint256).max
    );
    transactions[1].to = ondoGMSwap;
    transactions[1].txData = abi.encodeWithSelector(
      IOndoGMSwap.swapExactInWithAttestation.selector,
      _gmAsset,
      _amountIn,
      usdc,
      _amountOutMinimum,
      _attestationSignature,
      _quote
    );
  }
}

@openzeppelin/v3/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;
    }
}

@openzeppelin/v3/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

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

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

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

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

@openzeppelin/v3/contracts/utils/SafeCast.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;


/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such 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.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits.
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128) {
        require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
        return int128(value);
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64) {
        require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
        return int64(value);
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32) {
        require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
        return int32(value);
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16) {
        require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
        return int16(value);
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits.
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8) {
        require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
        return int8(value);
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        require(value < 2**255, "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}

contracts/guards/assetGuards/ClosedAssetGuard.sol

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

pragma solidity >=0.7.6;
pragma abicoder v2;

import {TxDataUtils} from "../../utils/TxDataUtils.sol";
import {IAssetGuard} from "../../interfaces/guards/IAssetGuard.sol";
import {IGuard} from "../../interfaces/guards/IGuard.sol";

// This should be the base for all AssetGuards that are not ERC20 or are ERC20 but should not be transferrable
abstract contract ClosedAssetGuard is TxDataUtils, IGuard, IAssetGuard {
  /// @notice Doesn't allow any transactions uses separate contract guard that should be migrated here
  /// @dev Parses the manager transaction data to ensure transaction is valid
  /// @return txType transaction type described in PoolLogic
  /// @return isPublic if the transaction is public or private
  function txGuard(address, address, bytes calldata) external pure virtual override returns (uint16 txType, bool) {
    return (txType, false);
  }

  /// @notice Returns the balance of the managed asset
  /// @dev May include any external balance in staking contracts
  /// @return balance The asset balance of given pool for the given asset
  function getBalance(address, address) public view virtual override returns (uint256) {
    revert("not implemented");
  }

  /// @notice Necessary check for remove asset
  /// @param pool Address of the pool
  /// @param asset Address of the remove asset
  function removeAssetCheck(address pool, address asset) public view virtual override {
    uint256 balance = getBalance(pool, asset);
    require(balance == 0, "cannot remove non-empty asset");
  }

  function withdrawProcessing(
    address,
    address,
    uint256,
    address
  ) external virtual override returns (address, uint256, MultiTransaction[] memory) {
    revert("not implemented");
  }

  function getDecimals(address) external view virtual override returns (uint256) {
    revert("not implemented");
  }
}

contracts/guards/assetGuards/ERC20Guard.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/v3/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/v3/contracts/token/ERC20/IERC20.sol";

import {TxDataUtils} from "../../utils/TxDataUtils.sol";
import {IAssetGuard} from "../../interfaces/guards/IAssetGuard.sol";
import {IGuard} from "../../interfaces/guards/IGuard.sol";
import {IERC20Extended} from "../../interfaces/IERC20Extended.sol";
import {IPoolLogic} from "../../interfaces/IPoolLogic.sol";
import {IPoolManagerLogic} from "../../interfaces/IPoolManagerLogic.sol";
import {IHasGuardInfo} from "../../interfaces/IHasGuardInfo.sol";
import {IHasSupportedAsset} from "../../interfaces/IHasSupportedAsset.sol";
import {ITransactionTypes} from "../../interfaces/ITransactionTypes.sol";
import {IAaveLendingPoolAssetGuard} from "../../interfaces/guards/IAaveLendingPoolAssetGuard.sol";
import {IGovernance} from "../../interfaces/IGovernance.sol";
import {IPoolFactory} from "../../interfaces/IPoolFactory.sol";
import {IAaveV3Pool} from "../../interfaces/aave/v3/IAaveV3Pool.sol";
import {IHasAssetInfo} from "../../interfaces/IHasAssetInfo.sol";
import {IMidasRedemptionVault} from "../../interfaces/midas/IMidasRedemptionVault.sol";
import {IMidasRedemptionVaultContractGuard} from "../../interfaces/midas/IMidasRedemptionVaultContractGuard.sol";
import {IPoolLimitOrderManager} from "../../interfaces/IPoolLimitOrderManager.sol";
import {ITokenizedOptionsMarketContractGuard} from "../../interfaces/tokenizedOptions/ITokenizedOptionsMarketContractGuard.sol";
import {ITokenizedOptionsMarket} from "../../interfaces/tokenizedOptions/ITokenizedOptionsMarket.sol";
import {IDytmOfficeContractGuard} from "../../interfaces/dytm/IDytmOfficeContractGuard.sol";
import {IDytmPeriphery} from "../../interfaces/dytm/IDytmPeriphery.sol";
import {DytmParamStructs} from "../../utils/dytm/DytmParamStructs.sol";
import {DytmHelperLib} from "../../utils/dytm/DytmHelperLib.sol";
import {EasySwapperV2UnrolledAssetsGuard} from "./EasySwapperV2UnrolledAssetsGuard.sol";
import {DytmOfficeAssetGuard} from "./dytm/DytmOfficeAssetGuard.sol";

/// @title Generic ERC20 asset guard
/// @dev Asset type = 0
contract ERC20Guard is TxDataUtils, IGuard, IAssetGuard, ITransactionTypes {
  using SafeMath for uint256;

  /// @dev Must match `AssetHandler` asset type 43 (Midas Pending Redemption Asset); used by
  ///      `_checkMidasPendingRedemptions` to find the pool's Midas redemption vault positions.
  uint16 internal constant MIDAS_PENDING_REDEMPTION_ASSET_TYPE = 43;

  /// @dev Must match `AssetHandler` asset type 107 (Tokenized Options Market Asset); used by
  ///      `_checkTokenizedOptionsPositions` to find the pool's tokenized options market positions.
  uint16 internal constant TOKENIZED_OPTIONS_MARKET_ASSET_TYPE = 107;

  /// @notice Transaction guard for approving assets
  /// @dev Parses the manager transaction data to ensure transaction is valid
  /// @param poolManagerLogic PoolManagerLogic address
  /// @param data Transaction call data attempt by manager
  /// @return txType transaction type described in ITransactionTypes
  /// @return isPublic if the transaction is public or private
  function txGuard(
    address poolManagerLogic,
    address /* to */,
    bytes calldata data
  ) external view virtual override returns (uint16 txType, bool) {
    bytes4 method = getMethod(data);

    if (method == IERC20.approve.selector) {
      (address spender, uint256 amount) = abi.decode(getParams(data), (address, uint256));

      // amount == 0 skips the spender check so ERC20 allowances to deprecated contracts can be revoked.
      // On an ERC721 `to` the second argument is a tokenId, so this also approves any spender for token #0.
      // No valued ERC721 routed to this guard can have token #0.
      if (amount > 0) {
        address factory = IPoolManagerLogic(poolManagerLogic).factory();
        address spenderGuard = IHasGuardInfo(factory).getContractGuard(spender);
        require(spenderGuard != address(0), "unsupported spender approval");
      }

      txType = uint16(TransactionType.Approve);
    }

    return (txType, false);
  }

  /// @notice Withdraw processing for ERC20 asset
  /// @param pool Address of the pool
  /// @param asset Address of the managed asset
  /// @param portion Portion of the asset balance to withdraw, in 10^18 scale
  /// @return withdrawAsset and
  /// @return withdrawBalance are used to withdraw portion of asset balance to depositor
  /// @return transactions are used to execute the withdrawal transactions in PoolLogic
  function withdrawProcessing(
    address pool,
    address asset,
    uint256 portion,
    address /* to */
  )
    external
    virtual
    override
    returns (address withdrawAsset, uint256 withdrawBalance, MultiTransaction[] memory transactions)
  {
    withdrawAsset = asset;
    uint256 totalAssetBalance = getBalance(pool, asset);
    withdrawBalance = totalAssetBalance.mul(portion).div(10 ** 18);
    return (withdrawAsset, withdrawBalance, transactions);
  }

  /// @notice Returns the balance of the managed asset
  /// @param pool Address of the pool
  /// @param asset Address of the managed asset
  /// @return balance The asset balance of given pool
  function getBalance(address pool, address asset) public view virtual override returns (uint256 balance) {
    // The base ERC20 guard has no externally staked tokens
    balance = IERC20(asset).balanceOf(pool);
  }

  /// @notice Returns the decimal of the managed asset
  /// @param asset Address of the managed asset
  /// @return decimals The decimal of given asset
  function getDecimals(address asset) external view virtual override returns (uint256 decimals) {
    decimals = IERC20Extended(asset).decimals();
  }

  /// @notice Necessary check for remove asset.
  ///         In AaveLendingPoolAssetGuard, when calculating getBalance, the function loops through all the supported assets.
  ///         Supported asset balance can be 0, but aave collateral or debt can be > 0. If it was able to remove the asset,
  ///         the value of Aave lending pool position would become lower. Having this asset guard with removeAssetCheck prevents this.
  ///         If there is any collateral or debt of a particular asset in Aave, it's not possible to remove that asset.
  /// @param pool Address of the pool
  /// @param asset Address of the remove asset
  function removeAssetCheck(address pool, address asset) public view virtual override {
    require(getBalance(pool, asset) == 0, "cannot remove non-empty asset");

    address factory = IPoolLogic(pool).factory();
    address governance = IPoolFactory(factory).governanceAddress();

    _checkAaveAssetPositions(pool, asset, governance);
    _checkLimitOrderPositions(pool, asset, governance);
    _checkDytmAssetPositions(pool, asset, factory, governance);
    _checkMidasPendingRedemptions(pool, asset, factory, governance);
    _checkTokenizedOptionsPositions(pool, asset, factory, governance);
  }

  function _checkAaveAssetPositions(address pool, address asset, address governance) internal view {
    // Magic number 8 is Aave lending pool "asset" asset type
    address aaveLendingPoolAssetGuard = IGovernance(governance).assetGuards(8);

    if (aaveLendingPoolAssetGuard == address(0)) {
      // If Aave lending pool asset guard is not set, skip the check
      return;
    }

    address aaveLendingPool = IAaveLendingPoolAssetGuard(aaveLendingPoolAssetGuard).aaveLendingPool();

    if (!IHasSupportedAsset(IPoolLogic(pool).poolManagerLogic()).isSupportedAsset(aaveLendingPool)) {
      // If Aave lending pool asset is not supported, skip the check
      return;
    }

    // Returns address(0) if it's not supported in Aave
    address variableDebtToken = IAaveV3Pool(aaveLendingPool).getReserveVariableDebtToken(asset);

    if (variableDebtToken != address(0))
      require(IERC20(variableDebtToken).balanceOf(pool) == 0, "repay Aave debt first");

    // Returns address(0) if it's not supported in Aave
    address aToken = IAaveV3Pool(aaveLendingPool).getReserveAToken(asset);
    if (aToken != address(0)) require(IERC20(aToken).balanceOf(pool) == 0, "withdraw Aave collateral first");
  }

  function _checkLimitOrderPositions(address pool, address asset, address governance) internal view {
    // Magic number 30 is EasySwapperV2 "asset" asset type
    address unrolledAssetsGuard = IGovernance(governance).assetGuards(30);

    if (unrolledAssetsGuard == address(0)) {
      // If guard is not set, skip the check
      return;
    }

    IPoolLimitOrderManager poolLimitOrderManagerProxy = EasySwapperV2UnrolledAssetsGuard(unrolledAssetsGuard)
      .poolLimitOrderManagerProxy();

    address settlementToken = poolLimitOrderManagerProxy.limitOrderSettlementToken();

    // If the asset is the settlement token, check pool has no open limit orders or settlement order
    if (asset == settlementToken) {
      require(
        poolLimitOrderManagerProxy.hasOpenLimitOrder(pool) == false &&
          poolLimitOrderManagerProxy.hasSettlementOrder(pool) == false,
        "has open order"
      );
    }
  }

  /// @notice Block removal while the asset is held as DYTM collateral or debt — prevents
  ///         bypassing the per-asset oracle-freshness gate that runs on deposits.
  function _checkDytmAssetPositions(address pool, address asset, address factory, address governance) internal view {
    // Magic number 106 is DYTM Office asset type
    address dytmGuard = IGovernance(governance).assetGuards(106);

    if (dytmGuard == address(0)) {
      // If DYTM Office asset guard is not set, skip the check
      return;
    }

    address dytmOffice = DytmOfficeAssetGuard(dytmGuard).dytmOffice();

    if (!IHasSupportedAsset(IPoolLogic(pool).poolManagerLogic()).isSupportedAsset(dytmOffice)) {
      // If DYTM Office is not supported by the pool, skip the check
      return;
    }

    address periphery = DytmOfficeAssetGuard(dytmGuard).dytmPeriphery();
    uint256[] memory marketIds = IDytmOfficeContractGuard(IHasGuardInfo(factory).getContractGuard(dytmOffice))
      .getOwnedTokenIds(pool);
    uint256 account = DytmHelperLib.toUserAccount(pool);

    for (uint256 i; i < marketIds.length; ++i) {
      DytmParamStructs.AccountPosition memory pos = IDytmPeriphery(periphery).getAccountPosition({
        account: account,
        market: uint88(marketIds[i])
      });

      require(pos.debt.debtAsset != asset, "asset held as DYTM debt");

      for (uint256 j; j < pos.collaterals.length; ++j) {
        require(pos.collaterals[j].asset != asset, "asset held as DYTM collateral");
      }
    }
  }

  /// @notice Block removal while a Midas async redemption involving the asset is unresolved:
  ///         settlement (`approveRequest`) pays the request's `tokenOut` into the pool, and a
  ///         rejected (Canceled) request is settled by Midas ops transferring the mToken back
  ///         manually — either way the incoming tokens would sit in the pool unaccounted if the
  ///         asset were no longer enabled. The mToken is owed back on BOTH Pending (via rejection)
  ///         and Canceled (return in flight); `tokenOut` is only owed while Pending.
  ///         NOTE: this protection only runs for assets whose asset guard inherits ERC20Guard —
  ///         which holds for Midas payment tokens (plain ERC20 stablecoins like USDC) and mTokens
  ///         (`MidasMTokenAssetGuard` extends ERC20Guard).
  function _checkMidasPendingRedemptions(
    address pool,
    address asset,
    address factory,
    address governance
  ) internal view {
    if (IGovernance(governance).assetGuards(MIDAS_PENDING_REDEMPTION_ASSET_TYPE) == address(0)) {
      // If Midas pending redemption asset guard is not set, skip the check
      return;
    }

    IHasSupportedAsset.Asset[] memory supportedAssets = IHasSupportedAsset(IPoolLogic(pool).poolManagerLogic())
      .getSupportedAssets();

    for (uint256 i; i < supportedAssets.length; ++i) {
      address redemptionVault = supportedAssets[i].asset;

      if (IHasAssetInfo(factory).getAssetType(redemptionVault) != MIDAS_PENDING_REDEMPTION_ASSET_TYPE) continue;

      address contractGuard = IHasGuardInfo(factory).getContractGuard(redemptionVault);
      if (contractGuard == address(0)) continue;

      bool isMToken = IMidasRedemptionVault(redemptionVault).mToken() == asset;
      uint256[] memory requestIds = IMidasRedemptionVaultContractGuard(contractGuard).getPendingRequestIds(
        pool,
        redemptionVault
      );

      for (uint256 j; j < requestIds.length; ++j) {
        (address sender, address tokenOut, uint8 status, , , ) = IMidasRedemptionVault(redemptionVault).redeemRequests(
          requestIds[j]
        );

        if (sender != pool) continue;

        if (status == uint8(IMidasRedemptionVault.RequestStatus.Pending)) {
          require(!isMToken && tokenOut != asset, "pending redemption in progress");
        } else if (status == uint8(IMidasRedemptionVault.RequestStatus.Canceled)) {
          require(!isMToken, "pending redemption in progress");
        }
      }
    }
  }

  /// @notice Block removing the market's USDC while a tokenized options position is outstanding:
  ///         escrow surplus, intent refunds, close proceeds and settled redemptions all pay USDC
  ///         into the pool later, and would sit there unaccounted if the asset were disabled.
  function _checkTokenizedOptionsPositions(
    address pool,
    address asset,
    address factory,
    address governance
  ) internal view {
    if (IGovernance(governance).assetGuards(TOKENIZED_OPTIONS_MARKET_ASSET_TYPE) == address(0)) {
      // If the tokenized options market asset guard is not set, skip the check
      return;
    }

    IHasSupportedAsset.Asset[] memory supportedAssets = IHasSupportedAsset(IPoolLogic(pool).poolManagerLogic())
      .getSupportedAssets();

    for (uint256 i; i < supportedAssets.length; i++) {
      address market = supportedAssets[i].asset;

      if (IHasAssetInfo(factory).getAssetType(market) != TOKENIZED_OPTIONS_MARKET_ASSET_TYPE) continue;
      if (ITokenizedOptionsMarket(market).usdc() != asset) continue;

      require(
        !ITokenizedOptionsMarketContractGuard(IHasGuardInfo(factory).getContractGuard(market)).hasOutstandingExposure(
          pool,
          market
        ),
        "options exposure outstanding"
      );
    }
  }
}

contracts/guards/assetGuards/EasySwapperV2UnrolledAssetsGuard.sol

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

pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

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

import {IPoolLogic} from "../../interfaces/IPoolLogic.sol";
import {IPoolManagerLogic} from "../../interfaces/IPoolManagerLogic.sol";
import {IEasySwapperV2} from "../../swappers/easySwapperV2/interfaces/IEasySwapperV2.sol";
import {IWithdrawalVault} from "../../swappers/easySwapperV2/interfaces/IWithdrawalVault.sol";
import {ClosedAssetGuard} from "./ClosedAssetGuard.sol";
import {IPoolLimitOrderManager} from "../../interfaces/IPoolLimitOrderManager.sol";

contract EasySwapperV2UnrolledAssetsGuard is ClosedAssetGuard {
  using SafeMath for uint256;

  IPoolLimitOrderManager public immutable poolLimitOrderManagerProxy;

  /// @param _poolLimitOrderManagerProxy It's an upgradeable contract so address is not expected to change
  constructor(address _poolLimitOrderManagerProxy) {
    require(_poolLimitOrderManagerProxy != address(0), "invalid address");

    poolLimitOrderManagerProxy = IPoolLimitOrderManager(_poolLimitOrderManagerProxy);
  }

  /// @dev Asset type 30 is used for accounting tokens in both types of WithdrawalVaults, for managers' ease of use (no need to add two separate assets)
  /// @param _pool dHEDGE vault address
  /// @param _asset In case of this asset guard, always EasySwapperV2 address
  /// @return balance Total balance accounted for both WithdrawalVaults belonging to the dHEDGE vault already in USD value
  function getBalance(address _pool, address _asset) public view override returns (uint256 balance) {
    address poolManagerLogic = IPoolLogic(_pool).poolManagerLogic();

    balance = _balanceOfWithdrawalVault(_pool, _asset, poolManagerLogic).add(
      _balanceOfLimitOrderVault(_pool, _asset, poolManagerLogic)
    );
  }

  /// @param _pool dHEDGE vault address
  /// @param _asset In case of this asset guard, always EasySwapperV2 address
  function removeAssetCheck(address _pool, address _asset) public view override {
    // It won't let to remove EasySwapperV2 "asset" if there is positive balance at least in one of the WithdrawalVaults
    super.removeAssetCheck(_pool, _asset);

    // Do not allow to remove EasySwapperV2 "asset" if there is an open limit order, because once limit order is executed,
    // tokens will be sent to WithdrawalVault and they won't be accounted hence vault losses value.
    require(poolLimitOrderManagerProxy.hasOpenLimitOrder(_pool) == false, "limit order opened");
  }

  function getDecimals(address) external pure override returns (uint256 decimals) {
    decimals = 18;
  }

  function withdrawProcessing(
    address _pool,
    address _asset,
    uint256 _withdrawPortion,
    address _to
  )
    external
    view
    override
    returns (address withdrawAsset, uint256 withdrawBalance, MultiTransaction[] memory transactions)
  {
    address poolManagerLogic = IPoolLogic(_pool).poolManagerLogic();

    uint256 withdrawalVaultBalance = _balanceOfWithdrawalVault(_pool, _asset, poolManagerLogic);
    uint256 limitOrderVaultBalance = _balanceOfLimitOrderVault(_pool, _asset, poolManagerLogic);

    // If both types are empty, early return
    if (withdrawalVaultBalance == 0 && limitOrderVaultBalance == 0) {
      return (withdrawAsset, withdrawBalance, transactions);
    }

    // If there are balances in both vaults, need to withdraw proportionally from both
    if (withdrawalVaultBalance > 0 && limitOrderVaultBalance > 0) {
      transactions = new MultiTransaction[](2);

      transactions[0] = MultiTransaction({
        to: _asset,
        txData: abi.encodeWithSelector(
          IEasySwapperV2.partialWithdraw.selector,
          _withdrawPortion,
          _to,
          IEasySwapperV2.WithdrawalVaultType.SINGLE_ASSET_WITHDRAWAL
        )
      });
      transactions[1] = MultiTransaction({
        to: _asset,
        txData: abi.encodeWithSelector(
          IEasySwapperV2.partialWithdraw.selector,
          _withdrawPortion,
          _to,
          IEasySwapperV2.WithdrawalVaultType.LIMIT_ORDER
        )
      });

      return (withdrawAsset, withdrawBalance, transactions);
    }

    // In remaining case, only one of the vaults has balance, so withdraw proportionally from that vault
    IEasySwapperV2.WithdrawalVaultType vaultType = withdrawalVaultBalance > 0
      ? IEasySwapperV2.WithdrawalVaultType.SINGLE_ASSET_WITHDRAWAL
      : IEasySwapperV2.WithdrawalVaultType.LIMIT_ORDER;

    transactions = new MultiTransaction[](1);
    transactions[0] = MultiTransaction({
      to: _asset,
      txData: abi.encodeWithSelector(IEasySwapperV2.partialWithdraw.selector, _withdrawPortion, _to, vaultType)
    });

    return (withdrawAsset, withdrawBalance, transactions);
  }

  function _balanceOfWithdrawalVault(
    address _pool,
    address _asset,
    address _poolManagerLogic
  ) internal view returns (uint256 balance) {
    IWithdrawalVault.TrackedAsset[] memory trackedAssets = IEasySwapperV2(_asset).getTrackedAssets(_pool);

    for (uint256 i; i < trackedAssets.length; ++i) {
      balance = balance.add(
        IPoolManagerLogic(_poolManagerLogic).assetValue(trackedAssets[i].token, trackedAssets[i].balance)
      );
    }
  }

  function _balanceOfLimitOrderVault(
    address _pool,
    address _asset,
    address _poolManagerLogic
  ) internal view returns (uint256 balance) {
    IWithdrawalVault.TrackedAsset[] memory trackedAssets = IEasySwapperV2(_asset).getTrackedAssetsFromLimitOrders(
      _pool
    );

    for (uint256 i; i < trackedAssets.length; ++i) {
      balance = balance.add(
        IPoolManagerLogic(_poolManagerLogic).assetValue(trackedAssets[i].token, trackedAssets[i].balance)
      );
    }
  }
}

contracts/guards/assetGuards/dytm/DytmOfficeAssetGuard.sol

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

import {SafeMath} from "@openzeppelin/v3/contracts/math/SafeMath.sol";
import {SafeCast} from "@openzeppelin/v3/contracts/utils/SafeCast.sol";
import {ClosedAssetGuard} from "../ClosedAssetGuard.sol";
import {IDytmPeriphery} from "../../../interfaces/dytm/IDytmPeriphery.sol";
import {DytmParamStructs} from "../../../utils/dytm/DytmParamStructs.sol";
import {IDytmAccountSplitterAndMerger} from "../../../interfaces/dytm/IDytmAccountSplitterAndMerger.sol";
import {IDytmOffice} from "../../../interfaces/dytm/IDytmOffice.sol";
import {IDytmDelegatee} from "../../../interfaces/dytm/IDytmDelegatee.sol";
import {DytmSplitTokenIdTracker} from "./DytmSplitTokenIdTracker.sol";
import {DytmWithdrawalCalculator} from "./DytmWithdrawalCalculator.sol";
import {NonDepositAssetGuard} from "../shared/NonDepositAssetGuard.sol";
import {DytmHelperLib} from "../../../utils/dytm/DytmHelperLib.sol";
import {IPoolLogic} from "../../../interfaces/IPoolLogic.sol";
import {IHasSupportedAsset} from "../../../interfaces/IHasSupportedAsset.sol";

/// @title Dytm Office Asset Guard
/// @dev Asset type = 106
contract DytmOfficeAssetGuard is
  ClosedAssetGuard,
  DytmSplitTokenIdTracker,
  DytmWithdrawalCalculator,
  NonDepositAssetGuard
{
  using SafeMath for uint256;
  using SafeCast for uint256;

  /// @notice Processor used by `DytmWithdrawLib` to run the DYTM unwind in an isolated context.
  address public immutable dytmWithdrawProcessor;

  function _addAssetCheck(address _poolLogic, IHasSupportedAsset.Asset calldata _asset) internal view override {
    super._addAssetCheck(_poolLogic, _asset);

    require(_useContractGuard().poolsWhitelist(_poolLogic), "pool not whitelisted");
  }

  /// @param _mismatchDeltaNumerator Numerator for mismatch delta tolerance
  /// @param _dytmOffice DYTM Office address
  /// @param _poolFactory dHEDGE pool factory address
  /// @param _dytmPeriphery DYTM Periphery address
  /// @param _accountSplitterAndMerger Account splitter and merger address
  /// @param _dytmWithdrawProcessor DYTM unwind processor address
  constructor(
    uint256 _mismatchDeltaNumerator,
    address _dytmOffice,
    address _poolFactory,
    address _dytmPeriphery,
    address _accountSplitterAndMerger,
    address _dytmWithdrawProcessor
  )
    DytmWithdrawalCalculator(
      _mismatchDeltaNumerator,
      _dytmOffice,
      _poolFactory,
      _dytmPeriphery,
      _accountSplitterAndMerger
    )
  {
    require(_dytmWithdrawProcessor != address(0), "invalid processor");
    dytmWithdrawProcessor = _dytmWithdrawProcessor;
  }

  /// @notice Returns the balance of the Dytm Office User Account of the pool
  /// @dev Returns the balance to be priced in USD
  /// @param _pool PoolLogic address
  /// @return balance Dytm Office User Account balance of the pool
  function getBalance(address _pool, address) public view override returns (uint256 balance) {
    uint256[] memory marketIds = _useContractGuard().getOwnedTokenIds(_pool);
    for (uint256 i; i < marketIds.length; ++i) {
      DytmParamStructs.AccountPosition memory position = IDytmPeriphery(dytmPeriphery).getAccountPosition({
        account: DytmHelperLib.toUserAccount(_pool),
        market: uint88(marketIds[i])
      });
      // Net equity clamped at zero: unhealthy (weighted HF < 1) positions can still have collateral > debt.
      if (position.totalCollateralValueUSD > position.debt.debtValueUSD) {
        balance = balance.add(position.totalCollateralValueUSD.sub(position.debt.debtValueUSD));
      }
    }
  }

  /// @notice Returns decimal of the dytm office asset
  /// @dev Returns decimal 18 (USD pricing)
  function getDecimals(address) external pure override returns (uint256 decimals) {
    decimals = 18;
  }

  /// @notice Process withdrawal for DYTM positions (IComplexAssetGuard variant)
  /// @dev Called by PoolLogic when ComplexAsset.withdrawData is non-empty.
  ///      Delegates to the internal implementation (withdrawData is used later by DytmWithdrawLib).
  function withdrawProcessing(
    address _pool,
    address _asset,
    uint256 _portion,
    address _to,
    bytes memory // _withdrawData — consumed by DytmWithdrawLib in easySwapperV2 withdrawalVault during unrollAssets, not here
  ) external override returns (address withdrawAsset, uint256 withdrawBalance, MultiTransaction[] memory transactions) {
    return _withdrawProcessingInternal(_pool, _asset, _portion, _to);
  }

  /// @notice Process withdrawal for DYTM positions
  /// @dev Splits accounts proportionally and transfers isolated accounts to withdrawer
  /// @param _pool Pool address
  /// @param _asset DYTM Office address
  /// @param _portion Portion to withdraw (in 1e18 scale, e.g., 1e18 = 100%)
  /// @param _to Recipient address
  /// @return withdrawAsset Asset to withdraw (always address(0) for DYTM)
  /// @return withdrawBalance Balance to withdraw (always 0 for DYTM)
  /// @return transactions Array of transactions to execute for account splitting and transfer
  function withdrawProcessing(
    address _pool,
    address _asset,
    uint256 _portion,
    address _to
  )
    external
    virtual
    override
    returns (address withdrawAsset, uint256 withdrawBalance, MultiTransaction[] memory transactions)
  {
    return _withdrawProcessingInternal(_pool, _asset, _portion, _to);
  }

  /// @dev Internal implementation for withdraw processing, shared by both overloads.
  ///      - `_to` receives the freshly-split DYTM isolated account; the market's hook usually
  ///        blocks `beforeBorrow` for non-whitelisted owners, so the recipient can't borrow.
  ///      - Returns no withdraw asset/balance — value reaches `_to` via the split-account transfers.
  function _withdrawProcessingInternal(
    address _pool,
    address _asset,
    uint256 _portion,
    address _to
  ) internal returns (address, uint256, MultiTransaction[] memory transactions) {
    uint256 newAccountIdCount = uint256(IDytmOffice(dytmOffice).getAccountCount()).add(1);
    uint256[] memory marketIds = _useContractGuard().getOwnedTokenIds(_pool);

    _accessControl(IPoolLogic(_pool).poolManagerLogic(), poolFactory);

    // Reset previously tracked split token IDs
    _resetSplitTokenIds(_to);

    transactions = new MultiTransaction[](marketIds.length.mul(2));
    uint256 txCount;
    // Running total of net equity in the unhealthy markets skipped below
    uint256 skippedEquityUSD;

    for (uint256 i; i < marketIds.length; ++i) {
      uint88 marketId = uint88(marketIds[i]);

      // Skip markets that can't be split (unhealthy / no collateral); reverts when skipped
      // net equity exceeds MAX_FORFEIT_VALUE_USD
      bool isWithdrawable;
      (isWithdrawable, , skippedEquityUSD) = _checkWithdrawableAndForfeitBound(_pool, marketId, skippedEquityUSD);
      if (!isWithdrawable) {
        continue;
      }

      // Transaction 1: Split account to create isolated account with portion of assets/debts
      transactions[txCount].to = _asset;
      transactions[txCount].txData = _encodeSplitDelegationCall(_pool, _portion, marketId);
      ++txCount;

      // Transaction 2: Transfer the split isolated account to the withdrawer
      transactions[txCount].to = _asset; // DYTM Office address
      transactions[txCount].txData = abi.encodeWithSelector(
        IDytmOffice.transfer.selector,
        _to,
        _addSplitTokenId(_to, newAccountIdCount, marketId), // Track split token ID and market ID
        1
      );
      ++txCount;
      newAccountIdCount = newAccountIdCount.add(1);
    }

    // Reduce array length to remove empty transaction slots
    uint256 reduceLength = transactions.length.sub(txCount);
    assembly {
      mstore(transactions, sub(mload(transactions), reduceLength))
    }

    return (address(0), 0, transactions);
  }

  /// @dev Build the `delegationCall` calldata that splits `_portion` of the pool's position in
  ///      `_marketId` into a fresh isolated account.
  ///      - Extracted so the withdraw loop above stays within 0.7.6's stack limit.
  function _encodeSplitDelegationCall(
    address _pool,
    uint256 _portion,
    uint88 _marketId
  ) private view returns (bytes memory txData) {
    bytes memory callbackData = abi.encode(
      IDytmAccountSplitterAndMerger.CallbackData({
        operation: IDytmAccountSplitterAndMerger.Operation.SPLIT_ACCOUNT,
        data: abi.encode(
          IDytmAccountSplitterAndMerger.SplitAccountParams({
            fraction: _portion.toUint64(),
            sourceAccount: DytmHelperLib.toUserAccount(_pool),
            market: _marketId
          })
        )
      })
    );

    txData = abi.encodeWithSelector(
      IDytmOffice.delegationCall.selector,
      DytmParamStructs.DelegationCallParams({
        callbackData: callbackData,
        delegatee: IDytmDelegatee(accountSplitterAndMerger)
      })
    );
  }
}

contracts/guards/assetGuards/dytm/DytmSplitTokenIdTracker.sol

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

import {IPoolManagerLogic} from "../../../interfaces/IPoolManagerLogic.sol";
import {IPoolFactory} from "../../../interfaces/IPoolFactory.sol";

/// @title Dytm Split Token ID Tracker
/// @notice Abstract contract for tracking DYTM split account positions created during withdrawals
/// @dev Extends this to track isolated account IDs and their market IDs from account splitting operations
abstract contract DytmSplitTokenIdTracker {
  struct SplitPosition {
    uint256 tokenId; // isolated account ID
    uint88 marketId; // DYTM market ID
  }

  /// @dev Split positions tracked per recipient
  mapping(address => SplitPosition[]) internal splitPositions;

  /// @notice Access control check for pool operations
  /// @param poolManagerLogic Address of the pool manager logic
  /// @param poolFactory Address of the pool factory
  /// @return poolLogic Address of the pool logic
  function _accessControl(address poolManagerLogic, address poolFactory) internal view returns (address poolLogic) {
    poolLogic = IPoolManagerLogic(poolManagerLogic).poolLogic();
    require(msg.sender == poolLogic && IPoolFactory(poolFactory).isPool(poolLogic), "not pool logic");
  }

  /// @notice Reset all split positions for a recipient
  /// @dev Clears previously tracked split positions, called before new withdrawal processing
  /// @param _to Address of the recipient whose split positions should be reset
  function _resetSplitTokenIds(address _to) internal {
    delete splitPositions[_to];
  }

  /// @notice Add a new split position for a recipient
  /// @dev Creates an isolated account ID from the DYTM account counter and records the market ID
  /// @param _to Address of the recipient
  /// @param _newAccountIdCount New account ID count from DYTM Office
  /// @param _marketId DYTM market ID for the split position
  /// @return newAccountId The newly created isolated account ID (shifted left by 160 bits)
  function _addSplitTokenId(
    address _to,
    uint256 _newAccountIdCount,
    uint88 _marketId
  ) internal returns (uint256 newAccountId) {
    newAccountId = uint256(_newAccountIdCount << 160); // Shift to create isolated account ID
    splitPositions[_to].push(SplitPosition({tokenId: newAccountId, marketId: _marketId}));
  }

  /// @notice Get all split positions for a recipient
  /// @dev Returns all isolated account IDs and their market IDs that were split during withdrawal
  /// @param _to Address of the recipient
  /// @return positions Array of split positions (tokenId + marketId)
  function getSplitPositions(address _to) external view returns (SplitPosition[] memory) {
    return splitPositions[_to];
  }
}

contracts/guards/assetGuards/dytm/DytmWithdrawalCalculator.sol

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

import {SafeMath} from "@openzeppelin/v3/contracts/math/SafeMath.sol";
import {WithdrawalHelperLib} from "../../../utils/WithdrawalHelperLib.sol";
import {IHasGuardInfo} from "../../../interfaces/IHasGuardInfo.sol";
import {IHasAssetInfo} from "../../../interfaces/IHasAssetInfo.sol";
import {IPoolFactory} from "../../../interfaces/IPoolFactory.sol";
import {IDytmPeriphery} from "../../../interfaces/dytm/IDytmPeriphery.sol";
import {IDytmOffice} from "../../../interfaces/dytm/IDytmOffice.sol";
import {DytmParamStructs} from "../../../utils/dytm/DytmParamStructs.sol";
import {DytmHelperLib} from "../../../utils/dytm/DytmHelperLib.sol";
import {IDytmWithdrawalCalculator} from "../../../interfaces/guards/IDytmWithdrawalCalculator.sol";
import {IDytmOfficeContractGuard} from "../../../interfaces/dytm/IDytmOfficeContractGuard.sol";
import {AutomationBase} from "../../../utils/chainlink/AutomationBase.sol";

/// @title DytmWithdrawalCalculator
/// @notice Abstract size-discovery calculator for DYTM withdrawal. Single frontend entrypoint:
///         `previewWithdrawal(pool, X)` returns a flat `AssetData[]` — one entry per
///         collateral and per debt slot across every withdrawable DYTM market. Each entry carries
///         the raw `(asset, amount)` plus asset classification (`assetType`, `isPool`, `isDebt`)
///         and the DYTM action identifiers (`marketId`, `accountId`, `tokenId` / `debtKey`,
///         `shares`) so the frontend can build both off-chain work (DEX / Pendle / Ondo) and
///         on-chain `WithdrawParams` / `RepayParams` calldata in a single round-trip.
/// @dev    No on-chain swap-data planning, no flattening — the dispatcher is a generic multicall
///         executor, and dHEDGE-vault collateral underlyings are resolved client-side via
///         `isPool == true`.
abstract contract DytmWithdrawalCalculator is IDytmWithdrawalCalculator, AutomationBase {
  using SafeMath for uint256;

  uint256 public constant BPS_DENOMINATOR = 10_000;

  /// @notice Max total net equity (USD, 1e18) in unhealthy markets a withdrawal may skip.
  ///         - Above it, withdrawals revert until a keeper liquidates.
  ///         - Same $3 dust budget as MAX_REMNANT_VALUE_USD in DytmWithdrawLib.
  uint256 public constant MAX_FORFEIT_VALUE_USD = 3e18; // $3

  /// @notice Preview-emission buffer in bps — shrinks collateral, inflates debt. NOT a validation tolerance like Aave/Ondo.
  uint256 public immutable mismatchDeltaNumerator;

  address public immutable dytmOffice;

  address public immutable poolFactory;

  address public immutable dytmPeriphery;

  address public immutable accountSplitterAndMerger;

  constructor(
    uint256 _mismatchDeltaNumerator,
    address _dytmOffice,
    address _poolFactory,
    address _dytmPeriphery,
    address _accountSplitterAndMerger
  ) {
    require(_mismatchDeltaNumerator < BPS_DENOMINATOR, "invalid mismatch delta numerator");
    mismatchDeltaNumerator = _mismatchDeltaNumerator;
    dytmOffice = _dytmOffice;
    poolFactory = _poolFactory;
    dytmPeriphery = _dytmPeriphery;
    accountSplitterAndMerger = _accountSplitterAndMerger;
  }

  // ──────────────────────────────────────────────────────────────────────────
  // Public functions
  // ──────────────────────────────────────────────────────────────────────────

  /// @inheritdoc IDytmWithdrawalCalculator
  /// @dev Emits one `AssetData` per collateral and per non-zero debt across every withdrawable market.
  ///      - Skips unhealthy / zero-collateral markets and reverts when the skipped net equity exceeds
  ///        MAX_FORFEIT_VALUE_USD — mirrors the on-chain split path (`DytmOfficeAssetGuard.withdrawProcessing`),
  ///        so blocked withdrawals surface at preview time.
  ///      - `accountId` is the DYTM-allocated next split account, pre-shifted by 160 bits, incremented
  ///        by one `<< 160` step per emitted market (markets share an `accountId` across their entries).
  ///      - `accountId` is a sim-time prediction; concurrent DYTM splits shift it — retry on revert.
  function previewWithdrawal(
    address _pool,
    uint256 _poolTokenAmount
  ) public virtual override cannotExecute returns (DytmParamStructs.AssetData[] memory assetData) {
    (uint256 portion, ) = WithdrawalHelperLib.calculateWithdrawalPortion(_pool, _poolTokenAmount);
    uint256[] memory marketIds = _useContractGuard().getOwnedTokenIds(_pool);

    uint256 baseAccountId = (uint256(IDytmOffice(dytmOffice).getAccountCount()) + 1) << 160;
    uint256 totalCollaterals = _accrueInterestAndCountCollaterals(
      marketIds,
      DytmHelperLib.toUserAccount(_pool),
      dytmOffice
    );

    // Upper bound: every collateral slot + at most one debt slot per market.
    // Unhealthy / zero-collateral markets contribute zero entries; trimmed at the end.
    assetData = new DytmParamStructs.AssetData[](totalCollaterals.add(marketIds.length));

    uint256 count;
    uint256 marketIndex;
    uint256 skippedEquityUSD;
    for (uint256 i; i < marketIds.length; ++i) {
      uint256 prevCount = count;
      (count, skippedEquityUSD) = _processOneMarket(
        assetData,
        count,
        _pool,
        uint88(marketIds[i]),
        baseAccountId + (marketIndex << 160),
        portion,
        skippedEquityUSD
      );
      // `marketIndex` only advances for processed markets so that the next allocated `accountId`
      // matches what DYTM will actually allocate during the on-chain split.
      if (count > prevCount) marketIndex++;
    }

    // Trim `assetData` to the populated entries.
    assembly {
      mstore(assetData, count)
    }
  }

  // ──────────────────────────────────────────────────────────────────────────
  // Internal helpers (shared with DytmOfficeAssetGuard)
  // ──────────────────────────────────────────────────────────────────────────

  /// @dev Get the DYTM Office contract guard
  function _useContractGuard() internal view returns (IDytmOfficeContractGuard) {
    return IDytmOfficeContractGuard(IHasGuardInfo(poolFactory).getContractGuard(dytmOffice));
  }

  /// @dev Check whether a market position can be split for withdrawal (healthy + has collateral).
  ///      - Unhealthy markets can't be split (DYTM reverts), so callers skip them and the
  ///        withdrawer's share of their net equity is forfeited to remaining holders.
  ///      - To bound that loss, callers thread a running total of skipped net equity through
  ///        `_skippedEquityUSD`; reverts once it exceeds MAX_FORFEIT_VALUE_USD.
  ///      - Net equity is clamped at zero — same valuation as `DytmOfficeAssetGuard.getBalance`.
  ///      - Lives here so preview and the on-chain split path enforce the same bound.
  function _checkWithdrawableAndForfeitBound(
    address _pool,
    uint88 _marketId,
    uint256 _skippedEquityUSD
  )
    internal
    view
    returns (bool isWithdrawable, DytmParamStructs.AccountPosition memory position, uint256 skippedEquityUSD)
  {
    position = IDytmPeriphery(dytmPeriphery).getAccountPosition({
      account: DytmHelperLib.toUserAccount(_pool),
      market: _marketId
    });
    isWithdrawable = position.isHealthy && position.totalCollateralValueUSD > 0;
    skippedEquityUSD = _skippedEquityUSD;
    if (!isWithdrawable && position.totalCollateralValueUSD > position.debt.debtValueUSD) {
      skippedEquityUSD = skippedEquityUSD.add(position.totalCollateralValueUSD.sub(position.debt.debtValueUSD));
      require(skippedEquityUSD <= MAX_FORFEIT_VALUE_USD, "unhealthy position too large");
    }
  }

  /// @dev Accrue interest for all reserves across all markets and count total collaterals
  function _accrueInterestAndCountCollaterals(
    uint256[] memory _marketIds,
    uint256 _account,
    address _dytmOffice
  ) internal returns (uint256 totalCollaterals) {
    for (uint256 i; i < _marketIds.length; ++i) {
      totalCollaterals = totalCollaterals.add(
        DytmHelperLib.accruePositionInterest(IDytmOffice(_dytmOffice), _account, uint88(_marketIds[i]))
      );
    }
  }

  /// @dev Process a single market: check withdrawability, then emit collateral + debt entries.
  ///      - Returns the updated write offset (unchanged if the market was skipped) and the
  ///        running skipped-equity total.
  function _processOneMarket(
    DytmParamStructs.AssetData[] memory _assetData,
    uint256 _count,
    address _pool,
    uint88 _marketId,
    uint256 _accountId,
    uint256 _portion,
    uint256 _skippedEquityUSD
  ) internal view returns (uint256 count, uint256 skippedEquityUSD) {
    bool isWithdrawable;
    DytmParamStructs.AccountPosition memory pos;
    (isWithdrawable, pos, skippedEquityUSD) = _checkWithdrawableAndForfeitBound(_pool, _marketId, _skippedEquityUSD);
    if (!isWithdrawable) return (_count, skippedEquityUSD);
    count = _emitMarketEntries(_assetData, _count, pos, _marketId, _accountId, _portion);
  }

  /// @dev Write one `AssetData` per collateral and one for the debt (if non-zero) into `_assetData`
  ///      starting at offset `_count`. Returns the updated write offset.
  function _emitMarketEntries(
    DytmParamStructs.AssetData[] memory _assetData,
    uint256 _count,
    DytmParamStructs.AccountPosition memory _pos,
    uint88 _marketId,
    uint256 _accountId,
    uint256 _portion
  ) internal view returns (uint256 count) {
    count = _count;
    // Buffer collateral DOWN (MF dilution) and debt UP (interest accrual) for sim→exec drift; excess swap output returns to vault via `uint256.max` repay.
    uint256 collateralBufferedPortion = _portion.mul(BPS_DENOMINATOR.sub(mismatchDeltaNumerator)).div(BPS_DENOMINATOR);
    uint256 debtBufferedPortion = _portion.mul(BPS_DENOMINATOR.add(mismatchDeltaNumerator)).div(BPS_DENOMINATOR);
    for (uint256 j; j < _pos.collaterals.length; ++j) {
      DytmParamStructs.CollateralInfo memory col = _pos.collaterals[j];
      _assetData[count++] = DytmParamStructs.AssetData({
        asset: col.asset,
        amount: col.assets.mul(collateralBufferedPortion).div(1e18),
        assetType: IHasAssetInfo(poolFactory).getAssetType(col.asset),
        isPool: IPoolFactory(poolFactory).isPool(col.asset),
        isDebt: false,
        marketId: _marketId,
        accountId: _accountId,
        tokenId: col.tokenId,
        debtKey: 0,
        shares: col.shares.mul(collateralBufferedPortion).div(1e18)
      });
    }
    if (_pos.debt.debtAssets > 0) {
      _assetData[count++] = DytmParamStructs.AssetData({
        asset: _pos.debt.debtAsset,
        amount: _pos.debt.debtAssets.mul(debtBufferedPortion).div(1e18),
        assetType: IHasAssetInfo(poolFactory).getAssetType(_pos.debt.debtAsset),
        isPool: IPoolFactory(poolFactory).isPool(_pos.debt.debtAsset),
        isDebt: true,
        marketId: _marketId,
        accountId: _accountId,
        tokenId: 0,
        debtKey: _pos.debt.debtKey,
        shares: _pos.debt.debtShares.mul(debtBufferedPortion).div(1e18)
      });
    }
  }
}

contracts/guards/assetGuards/shared/AddAssetCheckGuard.sol

//
//    ===========  ======     ======         =         ====          ====   =========    ==========   ==========
//   ==        ==    ===        ==          ===          ===         ===     ==    ==     ===    ==     ==   ====
// ===          =    ===        ==         = ===         ====       ====     ==    ==     ===           ==    ===
// ====              =============        =   ===        = ===    == ===     ========     ========      =======
// ====              ===        ==       =========       =  ===  ==  ===     ==    ===    ===    =      ==  ===
// ==                ===        ==      =       ===      =   === ==  ===     ==     ===   ===           ==   ===
//   ===       ==    ===        ==     ==        ====    =    ===    ===     ==     ==    ===     ==    ==     ====
//     ==========  ======     ====== =====       ===== ====    ==    ====  ==========    ===========  ======     ====
//
// Chamber Finance - https://chamberfi.com
//
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma abicoder v2;

import {IAddAssetCheckGuard} from "../../../interfaces/guards/IAddAssetCheckGuard.sol";
import {IHasSupportedAsset} from "../../../interfaces/IHasSupportedAsset.sol";

/// @notice Base for asset guards that validate an asset before a pool enables it.
/// @dev Inheriting this base advertises `isAddAssetCheckGuard` to `PoolManagerLogic`, which then
///      calls `addAssetCheck` on every add. Implement `_addAssetCheck` with the checks.
abstract contract AddAssetCheckGuard is IAddAssetCheckGuard {
  // solhint-disable-next-line const-name-snakecase
  bool public constant override isAddAssetCheckGuard = true;

  function addAssetCheck(address _poolLogic, IHasSupportedAsset.Asset calldata _asset) external view override {
    _addAssetCheck(_poolLogic, _asset);
  }

  function _addAssetCheck(address _poolLogic, IHasSupportedAsset.Asset calldata _asset) internal view virtual;
}

contracts/guards/assetGuards/shared/NonDepositAssetGuard.sol

//
//    ===========  ======     ======         =         ====          ====   =========    ==========   ==========
//   ==        ==    ===        ==          ===          ===         ===     ==    ==     ===    ==     ==   ====
// ===          =    ===        ==         = ===         ====       ====     ==    ==     ===           ==    ===
// ====              =============        =   ===        = ===    == ===     ========     ========      =======
// ====              ===        ==       =========       =  ===  ==  ===     ==    ===    ===    =      ==  ===
// ==                ===        ==      =       ===      =   === ==  ===     ==     ===   ===           ==   ===
//   ===       ==    ===        ==     ==        ====    =    ===    ===     ==     ==    ===     ==    ==     ====
//     ==========  ======     ====== =====       ===== ====    ==    ====  ==========    ===========  ======     ====
//
// Chamber Finance - https://chamberfi.com
//
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma abicoder v2;

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

/// @notice Base for asset guards whose asset can be held by a pool but never enabled as a deposit asset.
/// @dev Overrides that add further checks call `super._addAssetCheck` first.
abstract contract NonDepositAssetGuard is AddAssetCheckGuard {
  function _addAssetCheck(address, IHasSupportedAsset.Asset calldata _asset) internal view virtual override {
    require(!_asset.isDeposit, "deposit not supported");
  }
}

contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
  /**
   * @dev Returns the amount of tokens in existence.
   */
  function totalSupply() external view returns (uint256);

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

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

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

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

  /**
   * @dev Moves `amount` tokens from `sender` to `recipient` using the
   * allowance mechanism. `amount` is then deducted from the caller's
   * allowance.
   *
   * Returns a boolean value indicating whether the operation succeeded.
   *
   * Emits a {Transfer} event.
   */
  function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

  /**
   * @dev Emitted when `value` tokens are moved from one account (`from`) to
   * another (`to`).
   *
   * Note that `value` may be zero.
   */
  event Transfer(address indexed from, address indexed to, uint256 value);

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

contracts/interfaces/IERC20Extended.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;

interface IERC20Extended {
  // ERC20 Optional Views
  function name() external view returns (string memory);

  function symbol() external view returns (string memory);

  function decimals() external view returns (uint8);

  // Views
  function totalSupply() external view returns (uint256);

  function balanceOf(address owner) external view returns (uint256);

  function scaledBalanceOf(address user) external view returns (uint256);

  function allowance(address owner, address spender) external view returns (uint256);

  // Mutative functions
  function transfer(address to, uint256 value) external returns (bool);

  function approve(address spender, uint256 value) external returns (bool);

  function transferFrom(address from, address to, uint256 value) external returns (bool);

  // Events
  event Transfer(address indexed from, address indexed to, uint256 value);

  event Approval(address indexed owner, address indexed spender, uint256 value);
}

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/IHasAssetInfo.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;

interface IHasAssetInfo {
  function isValidAsset(address asset) external view returns (bool isValid);

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

  function getAssetPriceWithTime(
    address asset
  ) external view returns (uint256 price, uint256 updatedAt, uint256 maxPriceAge);

  function getAssetType(address asset) external view returns (uint16 assetType);

  function getMaximumSupportedAssetCount() external view returns (uint256 count);
}

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/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/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/IPoolLimitOrderManager.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma abicoder v2;

import {IPoolLogic} from "contracts/interfaces/IPoolLogic.sol";
import {IWithdrawalVault} from "contracts/swappers/easySwapperV2/interfaces/IWithdrawalVault.sol";

interface IPoolLimitOrderManager {
  struct LimitOrderInfo {
    uint256 amount;
    uint256 stopLossPriceD18;
    uint256 takeProfitPriceD18;
    address user;
    address pool;
    address pricingAsset;
  }

  struct LimitOrderExecution {
    bytes32 orderId;
    IPoolLogic.ComplexAsset[] complexAssetsData;
    uint256 amount;
  }

  struct SettlementOrderExecution {
    address user;
    IWithdrawalVault.MultiInSingleOutData swapData;
  }

  function createLimitOrder(LimitOrderInfo calldata limitOrderInfo_) external;

  function deleteLimitOrder(address pool_) external;

  function easySwapper() external view returns (address);

  function hasOpenLimitOrder(address user_) external view returns (bool hasOpenLimitOrder_);

  function getUserLimitOrderIds(address user_) external view returns (bytes32[] memory orderIds_);

  function hasSettlementOrder(address user_) external view returns (bool hasSettlementOrder_);

  function limitOrderSettlementToken() external view returns (address);

  function modifyLimitOrder(LimitOrderInfo calldata modificationInfo_) external;

  function executeLimitOrders(LimitOrderExecution[] calldata orders_) external;

  function executeSettlementOrders(SettlementOrderExecution[] calldata orders_) external;
}

contracts/interfaces/IPoolLogic.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma abicoder v2;

interface IPoolLogic {
  struct ComplexAsset {
    address supportedAsset;
    bytes withdrawData; // shape depends on the asset's complex guard: ComplexAssetSwapData (Aave), DytmWithdrawLib.UnwindPlan (DYTM), OndoGMTokenAssetGuard.OndoWithdrawData (Ondo GM, type 41), or TokenizedOptionsWithdrawLib.CloseOrder[] (tokenized options, type 107)
    uint256 slippageTolerance; // duplicated from ComplexAssetSwapData on purpose
  }

  function factory() external view returns (address);

  function poolManagerLogic() external view returns (address);

  function setPoolManagerLogic(address _poolManagerLogic) external;

  function calculateAvailableManagerFee(uint256 _fundValue) external view returns (uint256 fee);

  function tokenPrice() external view returns (uint256 price);

  function tokenPriceWithoutManagerFee() external view returns (uint256 price);

  function mintManagerFee() external;

  function deposit(address _asset, uint256 _amount) external returns (uint256 liquidityMinted);

  function depositForWithCustomCooldown(
    address _recipient,
    address _asset,
    uint256 _amount,
    uint256 _cooldown,
    address _referrer
  ) external returns (uint256 liquidityMinted);

  function withdraw(uint256 _fundTokenAmount) external;

  function withdrawSafe(uint256 _fundTokenAmount, ComplexAsset[] memory _complexAssetsData) external;

  function withdrawTo(address _recipient, uint256 _fundTokenAmount) external;

  function withdrawToSafe(
    address _recipient,
    uint256 _fundTokenAmount,
    ComplexAsset[] memory _complexAssetsData
  ) external;

  function setPoolPrivate(bool _privatePool) external;

  function totalSupply() external view returns (uint256 supply);

  function transfer(address to, uint256 value) external returns (bool);

  function balanceOf(address owner) external view returns (uint256);

  function approve(address spender, uint256 amount) external returns (bool);

  function symbol() external view returns (string memory);

  function transferFrom(address from, address to, uint256 value) external returns (bool);

  function getExitRemainingCooldown(address sender) external view returns (uint256 remaining);

  function execTransaction(address to, bytes calldata data) external returns (bool success);
}

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/ITransactionTypes.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma experimental ABIEncoderV2;

/// @title Transaction types used in pool execTransaction() contract guards
/// @dev Gradually migrate to this enum as we update / add new contract guards
interface ITransactionTypes {
  enum TransactionType {
    NotUsed, // 0
    Approve, // 1
    Exchange, // 2
    AddLiquidity, // 3
    RemoveLiquidity, // 4
    Stake, // 5
    Unstake, // 6
    Claim, // 7
    UnstakeAndClaim, // 8
    AaveDeposit, // 9
    AaveWithdraw, // 10
    AaveSetUserUseReserveAsCollateral, // 11
    AaveBorrow, // 12
    AaveRepay, // 13
    AaveSwapBorrowRateMode, // 14
    AaveRebalanceStableBorrowRate, // 15
    BalancerJoinPool, // 16
    BalancerExitPool, // 17
    EasySwapperDeposit, // 18
    EasySwapperWithdraw, // 19
    UniswapV3Mint, // 20
    UniswapV3IncreaseLiquidity, // 21
    UniswapV3DecreaseLiquidity, // 22
    UniswapV3Burn, // 23
    UniswapV3Collect, // 24
    UniswapV3Multicall, // 25
    LyraOpenPosition, // 26
    LyraClosePosition, // 27
    LyraForceClosePosition, // 28
    KwentaFuturesMarket, // 29
    AddLiquiditySingle, // 30
    RemoveLiquiditySingle, // 31
    MaiTx, // 32
    LyraAddCollateral, // 33
    LyraLiquidatePosition, // 34
    KwentaPerpsV2Market, // 35
    RedeemSynth, // 36
    SynthetixV3CreateAccount, // 37
    SynthetixV3DepositCollateral, // 38
    SynthetixV3WithdrawCollateral, // 39
    SynthetixV3DelegateCollateral, // 40
    SynthetixV3MintUSD, // 41
    SynthetixV3BurnUSD, // 42
    SynthetixV3Multicall, // 43
    XRamCreateVest, // 44
    XRamExitVest, // 45
    SynthetixV3Wrap, // 46
    SynthetixV3Unwrap, // 47
    SynthetixV3BuySynth, // 48
    SynthetixV3SellSynth, // 49
    SonneMint, // 50
    SonneRedeem, // 51
    SonneRedeemUnderlying, // 52
    SonneBorrow, // 53
    SonneRepay, // 54
    SonneComptrollerEnterMarkets, // 55
    SonneComptrollerExitMarket, // 56
    SynthetixV3UndelegateCollateral, // 57
    AaveMigrateToV3, // 58
    FlatMoneyStableDeposit, // 59
    FlatMoneyStableWithdraw, // 60
    FlatMoneyCancelOrder, // 61
    SynthetixV3ClaimReward, // 62
    VelodromeCLStake, // 63
    VelodromeCLUnstake, // 64
    VelodromeCLMint, // 65
    VelodromeCLIncreaseLiquidity, // 66
    VelodromeCLDecreaseLiquidity, // 67
    VelodromeCLBurn, // 68
    VelodromeCLCollect, // 69
    VelodromeCLMulticall, // 70
    FlatMoneyLeverageOpen, // 71
    FlatMoneyLeverageAdjust, // 72
    FlatMoneyLeverageClose, // 73
    SynthetixV3PerpsCreateAccount, // 74
    SynthetixV3PerpsModifyCollateral, // 75
    SynthetixV3PerpsCommitOrder, // 76
    CompoundDeposit, // 77
    CompoundWithdraw, // 78
    CompoundClaimRewards, // 79
    RamsesCLMint, // 80
    RamsesCLIncreaseLiquidity, // 81
    RamsesCLDecreaseLiquidity, // 82
    RamsesCLBurn, // 83
    RamsesCLCollect, // 84
    RamsesCLMulticall, // 85
    RamsesCLGetReward, // 86
    EasySwapperV2Deposit, // 87
    EasySwapperV2InitWithdraw, // 88
    EasySwapperV2CompleteWithdrawSingle, // 89
    EasySwapperV2CompleteWithdrawMultiple, // 90
    SafeTransferERC721, // 91
    PancakeCLMint, // 92
    PancakeCLIncreaseLiquidity, // 93
    PancakeCLDecreaseLiquidity, // 94
    PancakeCLBurn, // 95
    PancakeCLCollect, // 96
    PancakeCLMulticall, // 97
    PancakeCLStake, // 98
    PancakeCLUnstake, // 99
    PancakeCLHarvest, // 100
    GmxMulticall, // 101
    GmxClaimFundingFees, // 102
    GmxClaimCollateral, // 103
    GmxCancelOrder, // 104
    GmxCancelDeposit, // 105
    GmxCancelWithdrawal, // 106
    AcrossDepositV3, // 107
    FluidLendingDeposit, // 108
    FluidLendingWithdraw, // 109
    BuyPendlePT, // 110
    SellPendlePT, // 111
    AaveSetEfficiencyMode, // 112
    LimitOrderCreate, // 113
    LimitOrderModify, // 114
    LimitOrderDelete, // 115
    CowSwapPreSign, // 116
    CowSwapInvalidateOrder, // 117
    DytmSupply, // 118
    DytmWithdraw, // 119
    DytmBorrow, // 120
    DytmRepay, // 121
    DytmDelegationCall, // 122
    DytmSwitchCollateral, // 123
    HyperliquidLimitOrder, // 124
    HyperliquidCloidCancelOrder, // 125
    HyperliquidOidCancelOrder, // 126
    HyperliquidSystemAddressTransfer, // 127
    CoreWalletDeposit, // 128
    HyperliquidSpotSendAction, // 129
    HyperliquidUSDClassTransferAction, // 130
    HyperliquidSendAssetAction, // 131
    DytmMerge, // 132
    HyperliquidAddApiWallet, // 133
    AcrossDeposit, // 134
    GmxSetSavedCallbackContract, // 135
    TokenizedOptionsOpenIntent, // 136
    TokenizedOptionsCloseIntent, // 137
    TokenizedOptionsRedeem, // 138
    TokenizedOptionsOpenShortIntent, // 139
    TokenizedOptionsCloseShortIntent, // 140
    TokenizedOptionsRefundIntent, // 141
    TokenizedOptionsOpenStrategyIntent, // 142
    TokenizedOptionsCloseStrategyIntent, // 143
    TokenizedOptionsRedeemStrategy, // 144
    TokenizedOptionsPushFeeds // 145
  }
}

contracts/interfaces/aave/v3/DataTypes.sol

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

library DataTypes {
  /**
   * This exists specifically to maintain the `getReserveData()` interface, since the new, internal
   * `ReserveData` struct includes the reserve's `virtualUnderlyingBalance`.
   */
  struct ReserveDataLegacy {
    //stores the reserve configuration
    ReserveConfigurationMap configuration;
    //the liquidity index. Expressed in ray
    uint128 liquidityIndex;
    //the current supply rate. Expressed in ray
    uint128 currentLiquidityRate;
    //variable borrow index. Expressed in ray
    uint128 variableBorrowIndex;
    //the current variable borrow rate. Expressed in ray
    uint128 currentVariableBorrowRate;
    // DEPRECATED on v3.2.0
    uint128 currentStableBorrowRate;
    //timestamp of last update
    uint40 lastUpdateTimestamp;
    //the id of the reserve. Represents the position in the list of the active reserves
    uint16 id;
    //aToken address
    address aTokenAddress;
    // DEPRECATED on v3.2.0
    address stableDebtTokenAddress;
    //variableDebtToken address
    address variableDebtTokenAddress;
    //address of the interest rate strategy
    address interestRateStrategyAddress;
    //the current treasury balance, scaled
    uint128 accruedToTreasury;
    //the outstanding unbacked aTokens minted through the bridging feature
    uint128 unbacked;
    //the outstanding debt borrowed against this asset in isolation mode
    uint128 isolationModeTotalDebt;
  }

  struct ReserveConfigurationMap {
    //bit 0-15: LTV
    //bit 16-31: Liq. threshold
    //bit 32-47: Liq. bonus
    //bit 48-55: Decimals
    //bit 56: reserve is active
    //bit 57: reserve is frozen
    //bit 58: borrowing is enabled
    //bit 59: DEPRECATED: stable rate borrowing enabled
    //bit 60: asset is paused
    //bit 61: borrowing in isolation mode is enabled
    //bit 62: siloed borrowing enabled
    //bit 63: flashloaning enabled
    //bit 64-79: reserve factor
    //bit 80-115: borrow cap in whole tokens, borrowCap == 0 => no cap
    //bit 116-151: supply cap in whole tokens, supplyCap == 0 => no cap
    //bit 152-167: liquidation protocol fee
    //bit 168-175: DEPRECATED: eMode category
    //bit 176-211: unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled
    //bit 212-251: debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals
    //bit 252: virtual accounting is enabled for the reserve
    //bit 253-255 unused

    uint256 data;
  }

  /**
   * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.
   * The first bit indicates if an asset is used as collateral by the user, the second whether an
   * asset is borrowed by the user.
   */
  struct UserConfigurationMap {
    uint256 data;
  }
}

contracts/interfaces/aave/v3/IAaveV3Pool.sol

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

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

/**
 * @title IPool
 * @author Aave
 * @notice Defines the basic interface for an Aave Pool.
 */
interface IAaveV3Pool {
  /**
   * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
   * - E.g. User supplies 100 USDC and gets in return 100 aUSDC
   * @param asset The address of the underlying asset to supply
   * @param amount The amount to be supplied
   * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
   *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
   *   is a different wallet
   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.
   *   0 if the action is executed directly by the user, without any middle-man
   */
  function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;

  /**
   * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
   * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
   * @param asset The address of the underlying asset to withdraw
   * @param amount The underlying amount to be withdrawn
   *   - Send the value type(uint256).max in order to withdraw the whole aToken balance
   * @param to The address that will receive the underlying, same as msg.sender if the user
   *   wants to receive it on his own wallet, or a different address if the beneficiary is a
   *   different wallet
   * @return The final amount withdrawn
   */
  function withdraw(address asset, uint256 amount, address to) external returns (uint256);

  /**
   * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
   * already supplied enough collateral, or he was given enough allowance by a credit delegator on the VariableDebtToken
   * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
   *   and 100 variable debt tokens
   * @param asset The address of the underlying asset to borrow
   * @param amount The amount to be borrowed
   * @param interestRateMode 2 for Variable, 1 is deprecated on v3.2.0
   * @param referralCode The code used to register the integrator originating the operation, for potential rewards.
   *   0 if the action is executed directly by the user, without any middle-man
   * @param onBehalfOf The address of the user who will receive the debt. Should be the address of the borrower itself
   * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
   * if he has been given credit delegation allowance
   */
  function borrow(
    address asset,
    uint256 amount,
    uint256 interestRateMode,
    uint16 referralCode,
    address onBehalfOf
  ) external;

  /**
   * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
   * - E.g. User repays 100 USDC, burning 100 variable debt tokens of the `onBehalfOf` address
   * @param asset The address of the borrowed underlying asset previously borrowed
   * @param amount The amount to repay
   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
   * @param interestRateMode 2 for Variable, 1 is deprecated on v3.2.0
   * @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the
   * user calling the function if he wants to reduce/remove his own debt, or the address of any other
   * other borrower whose debt should be removed
   * @return The final amount repaid
   */
  function repay(
    address asset,
    uint256 amount,
    uint256 interestRateMode,
    address onBehalfOf
  ) external returns (uint256);

  /**
   * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the
   * equivalent debt tokens
   * - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable debt tokens
   * @dev  Passing uint256.max as amount will clean up any residual aToken dust balance, if the user aToken
   * balance is not enough to cover the whole debt
   * @param asset The address of the borrowed underlying asset previously borrowed
   * @param amount The amount to repay
   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
   * @param interestRateMode DEPRECATED in v3.2.0
   * @return The final amount repaid
   */
  function repayWithATokens(address asset, uint256 amount, uint256 interestRateMode) external returns (uint256);

  /**
   * @notice Allows suppliers to enable/disable a specific supplied asset as collateral
   * @param asset The address of the underlying asset supplied
   * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise
   */
  function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;

  /**
   * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
   * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
   *   a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
   * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
   * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
   * @param user The address of the borrower getting liquidated
   * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
   * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants
   * to receive the underlying collateral asset directly
   */
  function liquidationCall(
    address collateralAsset,
    address debtAsset,
    address user,
    uint256 debtToCover,
    bool receiveAToken
  ) external;

  /**
   * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,
   * as long as the amount taken plus a fee is returned.
   * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept
   * into consideration. For further details please visit https://docs.aave.com/developers/
   * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanReceiver interface
   * @param assets The addresses of the assets being flash-borrowed
   * @param amounts The amounts of the assets being flash-borrowed
   * @param interestRateModes Types of the debt to open if the flash loan is not returned:
   *   0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
   *   1 -> Deprecated on v3.2.0
   *   2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
   * @param onBehalfOf The address  that will receive the debt in the case of using 2 on `modes`
   * @param params Variadic packed params to pass to the receiver as extra information
   * @param referralCode The code used to register the integrator originating the operation, for potential rewards.
   *   0 if the action is executed directly by the user, without any middle-man
   */
  function flashLoan(
    address receiverAddress,
    address[] calldata assets,
    uint256[] calldata amounts,
    uint256[] calldata interestRateModes,
    address onBehalfOf,
    bytes calldata params,
    uint16 referralCode
  ) external;

  /**
   * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,
   * as long as the amount taken plus a fee is returned.
   * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept
   * into consideration. For further details please visit https://docs.aave.com/developers/
   * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanSimpleReceiver interface
   * @param asset The address of the asset being flash-borrowed
   * @param amount The amount of the asset being flash-borrowed
   * @param params Variadic packed params to pass to the receiver as extra information
   * @param referralCode The code used to register the integrator originating the operation, for potential rewards.
   *   0 if the action is executed directly by the user, without any middle-man
   */
  function flashLoanSimple(
    address receiverAddress,
    address asset,
    uint256 amount,
    bytes calldata params,
    uint16 referralCode
  ) external;

  /**
   * @notice Returns the user account data across all the reserves
   * @param user The address of the user
   * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed
   * @return totalDebtBase The total debt of the user in the base currency used by the price feed
   * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed
   * @return currentLiquidationThreshold The liquidation threshold of the user
   * @return ltv The loan to value of The user
   * @return healthFactor The current health factor of the user
   */
  function getUserAccountData(
    address user
  )
    external
    view
    returns (
      uint256 totalCollateralBase,
      uint256 totalDebtBase,
      uint256 availableBorrowsBase,
      uint256 currentLiquidationThreshold,
      uint256 ltv,
      uint256 healthFactor
    );

  /**
   * @notice Returns the configuration of the reserve
   * @param asset The address of the underlying asset of the reserve
   * @return The configuration of the reserve
   */
  function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory);

  /**
   * @notice Returns the configuration of the user across all the reserves
   * @param user The user address
   * @return The configuration of the user
   */
  function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory);

  /**
   * @notice Returns the state and configuration of the reserve
   * @param asset The address of the underlying asset of the reserve
   * @return The state and configuration data of the reserve
   */
  function getReserveData(address asset) external view returns (DataTypes.ReserveDataLegacy memory);

  /**
   * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct
   * @param id The id of the reserve as stored in the DataTypes.ReserveData struct
   * @return The address of the reserve associated with id
   */
  function getReserveAddressById(uint16 id) external view returns (address);

  /**
   * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
   * - E.g. User supplies 100 USDC and gets in return 100 aUSDC
   * @dev Deprecated: Use the `supply` function instead
   * @param asset The address of the underlying asset to supply
   * @param amount The amount to be supplied
   * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
   *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
   *   is a different wallet
   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.
   *   0 if the action is executed directly by the user, without any middle-man
   */
  function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;

  /**
   * @notice Returns the aToken address of a reserve.
   * @param asset The address of the underlying asset of the reserve
   * @return The address of the aToken
   */
  function getReserveAToken(address asset) external view returns (address);

  /**
   * @notice Returns the variableDebtToken address of a reserve.
   * @param asset The address of the underlying asset of the reserve
   * @return The address of the variableDebtToken
   */
  function getReserveVariableDebtToken(address asset) external view returns (address);

  /**
   * @notice Allows a user to use the protocol in eMode
   * @param categoryId The id of the category
   */
  function setUserEMode(uint8 categoryId) external;

  /**
   * @notice Returns the eMode the user is using
   * @param user The address of the user
   * @return The eMode id
   */
  function getUserEMode(address user) external view returns (uint256);
}

contracts/interfaces/dytm/IDytmAccountSplitterAndMerger.sol

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

interface IDytmAccountSplitterAndMerger {
  enum Operation {
    INVALID, // 0
    SPLIT_ACCOUNT, // 1
    MERGE_ACCOUNTS // 2
  }

  struct CallbackData {
    Operation operation;
    bytes data;
  }

  struct SplitAccountParams {
    uint256 sourceAccount;
    uint88 market;
    uint64 fraction;
  }

  struct MergeAccountsParams {
    uint256 sourceAccount;
    uint256 recipientAccount;
    uint88 market;
    uint64 fraction;
  }
}

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);
  function ownerOf(uint256 account) external view returns (address owner);
}

contracts/interfaces/dytm/IDytmOfficeContractGuard.sol

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

import {INftTrackerConsumerGuard} from "../guards/INftTrackerConsumerGuard.sol";

interface IDytmOfficeContractGuard is INftTrackerConsumerGuard {
  struct WhitelistSetting {
    address poolLogic;
    bool whitelisted;
  }

  event PoolWhitelistUpdated(address indexed poolLogic, bool whitelisted);

  function dytmOffice() external view returns (address);

  function dytmPeriphery() external view returns (address);

  function poolFactory() external view returns (address);

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

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

  function getWhitelistedPools() external view returns (address[] memory);
}

contracts/interfaces/dytm/IDytmPeriphery.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma experimental ABIEncoderV2;
import {DytmParamStructs} from "../../utils/dytm/DytmParamStructs.sol";
interface IDytmPeriphery {
  function getAccountPosition(
    uint256 account,
    uint88 market
  ) external view returns (DytmParamStructs.AccountPosition memory position);
}

contracts/interfaces/flatMoney/swapper/ISwapper.sol

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

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

interface ISwapper {
  enum TransferMethod {
    ALLOWANCE,
    PERMIT2,
    NATIVE
  }

  struct AggregatorData {
    bytes32 routerKey;
    bytes swapData;
  }

  struct SrcTokenSwapDetails {
    IERC20 token;
    uint256 amount;
    AggregatorData aggregatorData;
  }

  struct TransferMethodData {
    TransferMethod method;
    bytes methodData;
  }

  struct SrcData {
    SrcTokenSwapDetails[] srcTokenSwapDetails;
    TransferMethodData transferMethodData;
  }

  struct DestData {
    IERC20 destToken;
    uint256 minDestAmount;
  }

  struct InOutData {
    SrcData[] srcData;
    DestData destData;
  }

  function swap(InOutData calldata swapStruct) external payable;

  /// @return router The whitelisted router for `routerKey`, or the zero address if none is set.
  function getRouter(bytes32 routerKey) external view returns (address router);
}

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/IAddAssetCheckGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma experimental ABIEncoderV2;

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

interface IAddAssetCheckGuard {
  function isAddAssetCheckGuard() external view returns (bool);
  function addAssetCheck(address poolLogic, IHasSupportedAsset.Asset calldata asset) external view;
}

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/IComplexAssetGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma experimental ABIEncoderV2;

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

interface IComplexAssetGuard {
  /// @notice Processes the withdrawal of a complex asset
  /// @param pool The PoolLogic address
  /// @param asset The asset to be withdrawn
  /// @param withdrawPortion The portion of asset to be withdrawn
  /// @param to The recipient address
  /// @param withdrawData Custom withdraw data specific to the asset
  /// @return withdrawAsset Asset received after processing the withdrawal
  /// @return withdrawBalance Portion of withdraw asset which goes to depositor
  /// @return transactions Transaction data to execute in the PoolLogic
  function withdrawProcessing(
    address pool,
    address asset,
    uint256 withdrawPortion,
    address to,
    bytes memory withdrawData
  )
    external
    returns (address withdrawAsset, uint256 withdrawBalance, IAssetGuard.MultiTransaction[] memory transactions);
}

contracts/interfaces/guards/IDytmWithdrawalCalculator.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma experimental ABIEncoderV2;

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

/// @title IDytmWithdrawalCalculator
/// @notice Calculator-side surface for DYTM-as-collateral withdrawals. Exposes a single
///         simulation-only entrypoint (`previewWithdrawal`) that emits a flat per-asset
///         view of the withdrawal — one `AssetData` entry per collateral and per debt slot
///         across all withdrawable markets. The frontend uses this to plan both off-chain work
///         (DEX swaps, Pendle redeems, Ondo attestations) and on-chain `WithdrawParams` /
///         `RepayParams` calldata in a single round-trip.
/// @dev    The runtime withdrawal payload is `DytmWithdrawLib.UnwindPlan` — a flat list of
///         `(target, calldata)` actions plus an output-asset slippage floor. The library runs in
///         the WithdrawalVault and executes the action sequence as the owner of the freshly-split
///         DYTM accounts; the frontend builds the actions and minOutputAmount offchain.
interface IDytmWithdrawalCalculator is IComplexAssetGuard {
  /// @notice Emit the per-asset planning view for a withdrawal of `poolTokenAmount` from `pool`.
  /// @dev    State-mutating in practice (mints manager fee + accrues DYTM market interest);
  ///         intended to be called via `callStatic` / `eth_call` so neither commits.
  /// @param  pool            Pool logic address.
  /// @param  poolTokenAmount Pool tokens the user intends to withdraw.
  /// @return assetData       Flat list of withdrawal-planning entries across all withdrawable markets.
  function previewWithdrawal(
    address pool,
    uint256 poolTokenAmount
  ) external returns (DytmParamStructs.AssetData[] memory assetData);
}

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/INftTrackerConsumerGuard.sol

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

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

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

contracts/interfaces/midas/IMidasRedemptionVault.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma experimental ABIEncoderV2;

/// @notice Minimal interface for a Midas RedemptionVault (mToken redemption entrypoint).
/// @dev The custom-recipient overloads are intentionally omitted: dHEDGE guards only ever
///      allow the msg.sender variant so redeemed tokens / pending claims stay with the pool.
interface IMidasRedemptionVault {
  /// @notice Request status as defined by Midas `IManageableVault.RequestStatus`.
  ///         Encoded as uint8 across the ABI.
  enum RequestStatus {
    Pending, // 0
    Processed, // 1
    Canceled // 2
  }

  /// @notice Instantly redeems `amountMTokenIn` (18-decimals) of mToken to `tokenOut`, paid to msg.sender.
  function redeemInstant(address tokenOut, uint256 amountMTokenIn, uint256 minReceiveAmount) external;

  /// @notice Opens an asynchronous (curator-approved) redemption request for `amountMTokenIn` mToken.
  /// @return requestId The id assigned to the created request.
  function redeemRequest(address tokenOut, uint256 amountMTokenIn) external returns (uint256 requestId);

  /// @notice The mToken redeemed by this vault.
  function mToken() external view returns (address);

  /// @notice Monotonic counter; the next request will be assigned this value, so the most recent
  ///         request created in a transaction has id `currentRequestId() - 1`.
  function currentRequestId() external view returns (uint256);

  /// @notice Public getter for the request storage mapping.
  /// @dev `status` is the ABI encoding of `RequestStatus` (0 = Pending, 1 = Processed, 2 = Canceled).
  function redeemRequests(
    uint256 requestId
  )
    external
    view
    returns (
      address sender,
      address tokenOut,
      uint8 status,
      uint256 amountMToken,
      uint256 mTokenRate,
      uint256 tokenOutRate
    );
}

contracts/interfaces/midas/IMidasRedemptionVaultContractGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma experimental ABIEncoderV2;

/// @notice Interface exposing the async-redemption request tracking maintained by the
///         Midas redemption vault contract guard, consumed by the pending-redemption asset guard.
interface IMidasRedemptionVaultContractGuard {
  /// @notice Returns the redemption request ids opened by `pool` on `vault` that the guard has recorded.
  /// @dev The list is pruned of Processed requests as new requests are opened, but may still contain
  ///      non-Pending ids between requests; consumers must confirm status against the vault before
  ///      relying on an id being Pending. Canceled ids stay until `reconcileCanceledRequests`.
  function getPendingRequestIds(address pool, address vault) external view returns (uint256[] memory requestIds);

  /// @notice Permissionless cleanup: removes recorded ids whose request is Processed.
  function pruneSettledRequests(address pool, address vault) external;

  /// @notice Guard-owner-only cleanup of Canceled ids, lifting the pricing freeze after Midas ops
  ///         returned the rejected mTokens to the pool.
  function reconcileCanceledRequests(address pool, address vault) external;
}

contracts/interfaces/ondo/IGMTokenManager.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma abicoder v2;

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

interface IGMTokenManager {
  enum QuoteSide {
    BUY,
    SELL
  }

  function sanityCheckOracle() external view returns (IOndoSanityCheckOracle);

  function gmTokenMintingPaused(address gmToken) external view returns (bool);

  function gmTokenRedemptionsPaused(address gmToken) external view returns (bool);

  struct Quote {
    uint256 chainId;
    uint256 attestationId;
    bytes32 userId;
    address asset;
    uint256 price;
    uint256 quantity;
    uint256 expiration;
    uint8 side;
    bytes32 additionalData;
  }

  function mintWithAttestation(
    Quote calldata quote,
    bytes calldata signature,
    address depositToken,
    uint256 depositTokenAmount
  ) external returns (uint256);

  function redeemWithAttestation(
    Quote calldata quote,
    bytes calldata signature,
    address receiveToken,
    uint256 minimumReceiveAmount
  ) external returns (uint256);

  function getDomainSeparator() external view returns (bytes32);

  function hasRole(bytes32 role, address account) external view returns (bool);

  // solhint-disable-next-line func-name-mixedcase
  function ATTESTATION_SIGNER_ROLE() external view returns (bytes32);
}

contracts/interfaces/ondo/IOndoGMSwap.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma abicoder v2;

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

interface IOndoGMSwap {
  function gmTokenManager() external view returns (IGMTokenManager);

  function usdc() external view returns (address);

  function swapExactInWithAttestation(
    address tokenIn,
    uint256 amountIn,
    address tokenOut,
    uint256 amountOutMinimum,
    bytes calldata attestationSignature,
    IGMTokenManager.Quote calldata quote
  ) external;
}

contracts/interfaces/ondo/IOndoSanityCheckOracle.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma abicoder v2;

interface IOndoSanityCheckOracle {
  struct PriceData {
    uint256 price; // 18 decimals, already includes sValue
    uint64 lastUpdated;
    uint32 maxTimeDelay;
    uint16 allowedDeviationBps;
  }

  function prices(address asset) external view returns (PriceData memory);
}

contracts/interfaces/tokenizedOptions/ITokenizedOptionsMarket.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma abicoder v2;

/// @notice Types below mirror the TokenizedOptionsMarket (options-onchain) storage types verbatim —
///         see `Types.sol` in the options-onchain repo. Layouts must not drift: the `intents`/
///         `series`/`instruments` storage getters return them positionally and `marketConfig()`
///         ABI-decodes the full struct.

enum TokenizedOptionsIntentKind {
  Open, // user buys the long claim; escrow = max premium (USDC)
  Close, // user sells the long claim back; escrow = series tokens
  OpenShort, // user writes (fully collateralized); escrow = strike x amount collateral (USDC)
  CloseShort, // user buys the short back; escrow = short tokens, cost paid from released collateral
  OpenStrategy, // escrowed maximum net debit, USDC 6dp (`submitStrategyIntent` only)
  CloseStrategy // escrowed strategy tokens, minimum net proceeds (`submitStrategyIntent` only)
}

enum TokenizedOptionsIntentState {
  None,
  Pending,
  Executed,
  Refunded
}

enum TokenizedOptionsSeriesState {
  None, // no claim token or live strategy exposure
  Open, // trading
  Expired, // past expiry, awaiting settlement print
  Settled // print stored; tokens are a fixed USDC claim via redeem()
}

/// @notice Canonical instrument identity — mirrors Derive exactly.
struct TokenizedOptionsInstrumentId {
  address optionAsset; // Derive OPTION_ADDRESS for the underlying
  uint96 subId;
}

/// @notice A strategy token owns these signed quantities of each instrument. Legs are canonical:
///         one underlying, one expiry, strictly increasing subIds, ratios in [-2, 2].
struct TokenizedOptionsStrategyLeg {
  TokenizedOptionsInstrumentId instrument;
  int8 ratio;
}

/// @notice One-call operator snapshot of the market's config knobs and live ledgers.
/// @dev Copied field-for-field from the market's `Types.sol`; consumed only for `nextIntentId`
///      (the market exposes no standalone getter). The market only appends to this struct, and an
///      appended field is ignored by the decode. A removed or reordered field breaks it — new
///      intents get blocked while refunds (permissionless, direct) still work.
struct TokenizedOptionsMarketConfig {
  bool openPaused;
  bool closePaused;
  bool driftPaused;
  uint256 hourlyOpenCapGlobal;
  uint256 hourlyCloseCapGlobal;
  uint256 sigmaLowWad;
  uint256 sigmaHighWad;
  uint256 minTxValue;
  uint256 settlementFallbackDelay;
  uint256 refundFeeBps;
  uint256 refundFeeFixed;
  address bridgeKeeper;
  address l1Custodian;
  address lister;
  uint256 listMinMoneynessBps;
  uint256 listMaxMoneynessBps;
  uint256 listMaxTenor;
  uint256 maxListedInstruments;
  uint256 dailyVolumeCap;
  uint256 dailyVolumeUsed;
  address orderSigner;
  uint256 settlementSanityBps;
  uint256 bufferTargetBalance;
  uint256 chainlinkMaxAge;
  address cctpMessenger;
  uint32 cctpDestDomain;
  uint256 cctpMaxFee;
  uint256 feeBps;
  uint256 intentTtl;
  uint256 sigmaReserveWad;
  uint256 sigmaFloorWad;
  uint256 bandPadBps;
  address settlementSigner;
  uint256 nextIntentId;
  uint256 totalEscrowed;
  uint256 settlementReserved;
  bool shortOpenPaused;
  uint256 shortCollateral6;
}

interface ITokenizedOptionsMarket {
  /// @notice The single intent entry point for all four kinds. `limit` per kind: Open — escrowed
  ///         max premium incl. fee; Close — min proceeds net of fee; OpenShort — min premium
  ///         accepted net of fee (the escrow is strike x amount collateral, pulled here);
  ///         CloseShort — max buy-back cost incl. fee, paid from the released collateral.
  function submitIntent(
    TokenizedOptionsIntentKind kind,
    TokenizedOptionsInstrumentId calldata instrument,
    uint256 amount,
    uint256 limit
  ) external returns (uint256 id);

  /// @notice Intent entry point for strategy bundles. `kind` is OpenStrategy (`limit` = escrowed
  ///         maximum net debit incl. fee) or CloseStrategy (escrows strategy tokens, `limit` = minimum
  ///         net proceeds).
  function submitStrategyIntent(
    TokenizedOptionsIntentKind kind,
    TokenizedOptionsStrategyLeg[] calldata legs,
    uint256 amount,
    uint256 limit
  ) external returns (uint256 id);

  function refundIntent(uint256 id) external;

  function settleSeries(TokenizedOptionsInstrumentId calldata instrument) external;

  function redeem(TokenizedOptionsInstrumentId calldata instrument, uint256 amount, bool shortClaim) external;

  function settleStrategy(bytes32 key) external;

  function redeemStrategy(bytes32 key, uint256 amount) external;

  function instrumentKey(TokenizedOptionsInstrumentId memory instrument) external pure returns (bytes32);

  function intents(
    uint256 id
  )
    external
    view
    returns (
      address user,
      TokenizedOptionsIntentKind kind,
      TokenizedOptionsIntentState state,
      uint64 createdAt,
      uint16 feeBps,
      uint64 deadline,
      bytes32 key,
      uint256 amount,
      uint256 limit
    );

  function instruments(bytes32 key) external view returns (bool allowed, bool isCall, uint64 expiry, uint128 strike);

  function instrumentIds(bytes32 key) external view returns (address optionAsset, uint96 subId);

  function series(
    bytes32 key
  )
    external
    view
    returns (
      address token,
      address shortToken,
      bool settled,
      uint256 settlementValue,
      uint256 shortValue,
      uint256 reservedRemaining,
      uint256 collateralRemaining,
      uint256 strategyLongLeg,
      uint256 strategyShortLeg
    );

  function seriesState(bytes32 key) external view returns (TokenizedOptionsSeriesState);

  function strategies(
    bytes32 key
  ) external view returns (address token, bool settled, uint256 settlementValue, uint256 reservedRemaining);

  function strategyLegs(bytes32 key) external view returns (TokenizedOptionsStrategyLeg[] memory legs);

  function strategyKey(TokenizedOptionsStrategyLeg[] calldata legs) external pure returns (bytes32);

  function underlyings(
    address optionAsset
  )
    external
    view
    returns (address feed, uint8 feedDecimals, uint64 anchorMaxAge, string memory symbol, uint64 spotMaxAge);

  function expiryPriceKey(address optionAsset, uint64 expiry) external pure returns (bytes32);

  function expiryPrices(bytes32 key) external view returns (uint256);

  function bsBand(TokenizedOptionsInstrumentId calldata instrument) external view returns (uint256 lo, uint256 hi);

  function listedInstruments() external view returns (bytes32[] memory);

  function marketConfig() external view returns (TokenizedOptionsMarketConfig memory);

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

contracts/interfaces/tokenizedOptions/ITokenizedOptionsMarketContractGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma abicoder v2;

/// @notice One claim token of a tracked series or strategy, as the market reports it.
struct TokenizedOptionsTrackedClaim {
  bytes32 key; // the series key, or the strategy key when `isStrategy`
  address token; // zero when the market has not deployed this claim
  bool isStrategy;
  bool shortClaim; // the series' short (collateral) claim; always false for a strategy
  bool settled;
  uint256 settledValue; // frozen USDC value per token once settled, 18 decimals
}

/// @notice 0.7.6-compatible surface of the TokenizedOptionsMarketContractGuard, consumed by the
///         tokenized-options asset guard (NAV), `ERC20Guard` (USDC removal interlock) and the
///         EasySwapperV2 withdrawal library.
interface ITokenizedOptionsMarketContractGuard {
  function priceOracle() external view returns (address);

  function getPendingIntentIds(address pool, address market) external view returns (uint256[] memory intentIds);

  function getTrackedSeriesKeys(address pool, address market) external view returns (bytes32[] memory seriesKeys);

  function getTrackedStrategyKeys(address pool, address market) external view returns (bytes32[] memory strategyKeys);

  /// @notice Every claim token of the pool's tracked series and strategies: the long then the short
  ///         claim of each tracked series, in tracked order, then the token of each tracked strategy.
  ///         Always `2 x series + strategies` entries; an undeployed claim has a zero `token`.
  function getTrackedClaims(
    address pool,
    address market
  ) external view returns (TokenizedOptionsTrackedClaim[] memory claims);

  /// @notice True while any of the pool's tracked intents is Pending on the market.
  function hasPendingIntent(address pool, address market) external view returns (bool);

  function hasOutstandingExposure(address pool, address market) external view returns (bool);

  function pruneIntents(address pool, address market) external;

  function pruneSeries(address pool, address market, bytes32 seriesKey) external;

  function pruneStrategy(address pool, address market, bytes32 strategyKey) external;
}

contracts/swappers/easySwapperV2/interfaces/IEasySwapperV2.sol

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

import {ISwapper} from "../../../interfaces/flatMoney/swapper/ISwapper.sol";
import {IPoolLogic} from "../../../interfaces/IPoolLogic.sol";
import {IWithdrawalVault} from "./IWithdrawalVault.sol";

interface IEasySwapperV2 {
  // ============ Types ============

  enum WithdrawalVaultType {
    SINGLE_ASSET_WITHDRAWAL,
    LIMIT_ORDER
  }

  // ============ State Variable Getters ============

  function swapper() external view returns (ISwapper swapper_);

  function withdrawalContracts(address _depositor) external view returns (address withdrawalVault_);

  function limitOrderContracts(address _depositor) external view returns (address limitOrderVault_);

  function customCooldown() external view returns (uint256 cooldown_);

  function customCooldownDepositsWhitelist(address _vault) external view returns (bool isWhitelisted_);

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

  function isdHedgeVault(address _dHedgeVault) external view returns (bool isVault_);

  function depositQuote(
    address _dHedgeVault,
    address _vaultDepositToken,
    uint256 _depositAmount
  ) external view returns (uint256 expectedAmountReceived_);

  function getTrackedAssets(
    address _depositor
  ) external view returns (IWithdrawalVault.TrackedAsset[] memory trackedAssets_);

  function getTrackedAssetsFromLimitOrders(
    address _depositor
  ) external view returns (IWithdrawalVault.TrackedAsset[] memory trackedAssets_);

  // ============ Mutating Functions ============

  function partialWithdraw(uint256 _portion, address _to, WithdrawalVaultType _vaultType) external;

  function dHedgePoolFactory() external view returns (address);

  function initLimitOrderWithdrawalFor(
    address _user,
    address _dHedgeVault,
    uint256 _amountIn,
    IPoolLogic.ComplexAsset[] memory _complexAssetsData
  ) external returns (IWithdrawalVault.TrackedAsset[] memory trackedAssets_, address vault_);

  function completeLimitOrderWithdrawalFor(
    address _user,
    IWithdrawalVault.MultiInSingleOutData calldata _swapData,
    uint256 _expectedDestTokenAmount
  ) external returns (uint256 destTokenAmount_);
}

contracts/swappers/easySwapperV2/interfaces/IWithdrawalVault.sol

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

import {ISwapper} from "../../../interfaces/flatMoney/swapper/ISwapper.sol";
import {IPoolLogic} from "../../../interfaces/IPoolLogic.sol";

interface IWithdrawalVault {
  struct MultiInSingleOutData {
    ISwapper.SrcTokenSwapDetails[] srcData;
    ISwapper.DestData destData;
  }

  struct TrackedAsset {
    address token;
    uint256 balance;
  }

  /// @notice A close intent submitted by this vault, which may still be Pending.
  struct PendingOptionsIntent {
    address market;
    uint256 intentId;
  }

  function recoverAssets() external;

  function recoverAssets(uint256 _portion, address _to) external;

  function swapToSingleAsset(
    MultiInSingleOutData calldata _swapData,
    uint256 _expectedDestTokenAmount
  ) external returns (uint256 destTokenAmount);

  function unrollAssets(address _dHedgeVault, IPoolLogic.ComplexAsset[] memory _complexAssetsData) external;

  function getTrackedAssets() external view returns (TrackedAsset[] memory trackedAssets);

  function getPendingOptionsIntents() external view returns (PendingOptionsIntent[] memory intents);

  function depositor() external view returns (address);

  function withdrawDhedgeVault(
    address _dHedgeVault,
    uint256 _amountIn,
    IPoolLogic.ComplexAsset[] memory _complexAssetsData
  ) external;
}

contracts/utils/BytesLib.sol

// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * @title Solidity Bytes Arrays Utils
 * @author Gonçalo Sá <[email protected]>
 *
 * @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.7.6;

/* solhint-disable */
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/utils/TxDataUtils.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;

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

abstract contract TxDataUtils {
  using BytesLib for bytes;

  function getMethod(bytes memory data) internal pure returns (bytes4) {
    return read4left(data, 0);
  }

  function getParams(bytes memory data) internal pure returns (bytes memory) {
    return data.slice(4, data.length - 4);
  }

  function getInput(bytes memory data, uint8 inputNum) internal pure returns (bytes32) {
    return read32(data, 32 * inputNum + 4, 32);
  }

  function getArrayLast(bytes memory data, uint8 inputNum) internal pure returns (bytes32) {
    bytes32 arrayPos = read32(data, 32 * inputNum + 4, 32);
    bytes32 arrayLen = read32(data, uint256(arrayPos) + 4, 32);
    require(arrayLen > 0, "input is not array");
    return read32(data, uint256(arrayPos) + 4 + (uint256(arrayLen) * 32), 32);
  }

  function getArrayIndex(bytes memory data, uint8 inputNum, uint8 arrayIndex) internal pure returns (bytes32) {
    bytes32 arrayPos = read32(data, 32 * inputNum + 4, 32);
    bytes32 arrayLen = read32(data, uint256(arrayPos) + 4, 32);
    require(arrayLen > 0, "input is not array");
    require(uint256(arrayLen) > arrayIndex, "invalid array position");
    return read32(data, uint256(arrayPos) + 4 + ((1 + uint256(arrayIndex)) * 32), 32);
  }

  function read4left(bytes memory data, uint256 offset) internal pure returns (bytes4 o) {
    require(data.length >= offset + 4, "Reading bytes out of bounds");
    assembly {
      o := mload(add(data, add(32, offset)))
    }
  }

  function read32(bytes memory data, uint256 offset, uint256 length) internal pure returns (bytes32 o) {
    require(data.length >= offset + length, "Reading bytes out of bounds");
    assembly {
      o := mload(add(data, add(32, offset)))
      let lb := sub(32, length)
      if lb {
        o := div(o, exp(2, mul(lb, 8)))
      }
    }
  }

  function convert32toAddress(bytes32 data) internal pure returns (address o) {
    return address(uint160(uint256(data)));
  }
}

contracts/utils/WithdrawalHelperLib.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;

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

import {IPoolLogic} from "../interfaces/IPoolLogic.sol";
import {IPoolManagerLogic} from "../interfaces/IPoolManagerLogic.sol";
import {IERC20Extended} from "../interfaces/IERC20Extended.sol";

/// @title Shared helpers for withdrawal processing in asset guards
library WithdrawalHelperLib {
  using SafeMath for uint256;

  uint256 private constant BPS_DENOMINATOR = 10_000;

  /// @notice Reduces an amount by 0.01% (1 bps) to account for fee accrual between
  ///         off-chain simulation (`callStatic`) and on-chain execution.
  function applyPortionShrinkBuffer(uint256 _amount) internal pure returns (uint256) {
    return _amount.mul(BPS_DENOMINATOR.sub(1)).div(BPS_DENOMINATOR);
  }

  /// @notice Mints manager fee, applies exit fee, and calculates withdrawal portion
  /// @param _pool The pool (or vault token) address
  /// @param _tokenAmount The amount of pool tokens to be withdrawn
  /// @return portion The portion of totalSupply being withdrawn (scaled by 1e18)
  /// @return poolManagerLogic The pool manager logic address
  function calculateWithdrawalPortion(
    address _pool,
    uint256 _tokenAmount
  ) internal returns (uint256 portion, address poolManagerLogic) {
    // Mint manager fee to update totalSupply for accurate portion calculation
    IPoolLogic(_pool).mintManagerFee();

    poolManagerLogic = IPoolLogic(_pool).poolManagerLogic();

    // If the pool has exit fee set, token amount processed for withdrawal will be reduced by the exit fee
    (uint256 exitFeeNumerator, , uint256 denominator) = IPoolManagerLogic(poolManagerLogic).getExitFeeInfo();
    if (exitFeeNumerator > 0) {
      _tokenAmount = _tokenAmount.sub(_tokenAmount.mul(exitFeeNumerator).div(denominator));
    }

    // Calculate what portion of pool tokens is intended for withdrawal
    portion = _tokenAmount.mul(1e18).div(IERC20Extended(_pool).totalSupply());
  }
}

contracts/utils/chainlink/AutomationBase.sol

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

contract AutomationBase {
  /**
   * @notice method that allows it to be simulated via eth_call by checking that
   * the sender is the zero address.
   */
  function _preventExecution() internal view {
    require(
      // solhint-disable-next-line avoid-tx-origin
      tx.origin == address(0) || tx.origin == address(0x1111111111111111111111111111111111111111),
      "only simulated call"
    );
  }

  /**
   * @notice modifier that allows it to be simulated via eth_call by checking
   * that the sender is the zero address.
   */
  modifier cannotExecute() {
    _preventExecution();
    _;
  }
}

contracts/utils/dytm/DytmHelperLib.sol

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

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

library DytmHelperLib {
  /// @dev Accrue interest for all collateral and debt reserves of a single position
  /// @return collateralCount Number of collateral entries in this position
  function accruePositionInterest(
    IDytmOffice _dytmOffice,
    uint256 _account,
    uint88 _marketId
  ) internal returns (uint256 collateralCount) {
    uint256[] memory collateralIds = _dytmOffice.getAllCollateralIds(_account, _marketId);
    for (uint256 j; j < collateralIds.length; ++j) {
      _dytmOffice.accrueInterest(getReserveKey(collateralIds[j]));
    }
    uint256 debtId = _dytmOffice.getDebtId(_account, _marketId);
    if (debtId > 0) {
      _dytmOffice.accrueInterest(getReserveKey(debtId));
    }
    collateralCount = collateralIds.length;
  }

  function getAssetFromTokenId(uint256 tokenId) internal pure returns (address asset) {
    return address(uint160(tokenId));
  }
  function getReserveKey(uint256 tokenId) internal pure returns (uint248 rawReserveKey) {
    return uint248(tokenId);
  }

  function getMarketId(uint248 rawReserveKey) internal pure returns (uint88 rawMarketId) {
    rawMarketId = uint88(rawReserveKey >> 160);
  }

  function getAsset(uint248 rawReserveKey) internal pure returns (address asset) {
    return address(uint160(rawReserveKey));
  }

  enum AccountType {
    INVALID_ACCOUNT, // 0
    USER_ACCOUNT, // 1
    ISOLATED_ACCOUNT // 2
  }

  function getAccountType(uint256 rawAccount) internal pure returns (AccountType accountType) {
    uint160 addressField = uint160(rawAccount);
    uint96 accountCount = uint96(rawAccount >> 160);

    if (addressField == 0 && accountCount != 0) {
      return AccountType.ISOLATED_ACCOUNT; // Isolated account
    } else if (addressField != 0 && accountCount == 0) {
      return AccountType.USER_ACCOUNT; // User account
    } else {
      revert("Invalid raw account ID");
    }
  }

  function isUserAccount(uint256 rawAccount) internal pure returns (bool isUser) {
    return getAccountType(rawAccount) == AccountType.USER_ACCOUNT;
  }

  function toUserAddress(uint256 rawAccount) internal pure returns (address user) {
    // Validate that the account is a user account.
    require(isUserAccount(rawAccount), "invalid account type");

    return address(uint160(rawAccount));
  }

  function toUserAccount(address user) internal pure returns (uint256 account) {
    require(user != address(0), "empty user account");
    return uint256(uint160(user));
  }
}

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;
  }

  /// @notice Per-asset withdrawal planning entry emitted by `DytmWithdrawalCalculator.previewWithdrawal`.
  /// @dev    Flat list across all withdrawable DYTM markets; one entry per collateral slot and
  ///         per debt slot (when non-zero). Carries everything the frontend needs to:
  ///           - Plan off-chain work (DEX aggregator / Pendle redeem / Ondo attestation) using
  ///             `asset`, `amount`, `assetType`, `isPool`.
  ///           - Build the on-chain `WithdrawParams` / `RepayParams` calldata using
  ///             `accountId`, `marketId`, `tokenId` (collateral) or `debtKey` (debt), and `shares`.
  ///         Collateral entries: `tokenId` set, `debtKey == 0`, `isDebt == false`.
  ///         Debt entries:       `tokenId == 0`, `debtKey` set, `isDebt == true`.
  ///         dHEDGE-vault collateral: `isPool == true`. The frontend handles the vault token's
  ///         underlying-resolution + per-underlying off-chain handling itself.
  struct AssetData {
    address asset;
    uint256 amount;
    uint16 assetType;
    bool isPool;
    bool isDebt;
    uint88 marketId;
    uint256 accountId;
    uint256 tokenId;
    uint248 debtKey;
    uint256 shares;
  }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 20,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.