Skip to content
Verified contractPartialMIT

DytmWithdrawLib

Address0xfbd451dc0699e932c28640a4d44542d8483c8d5d
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.7.6

 

Same code

1 more contract

 

Details

Compiler
solc 0.7.6+commit.7338295f
Language
solidity
Optimization
Yes, 20 runs
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,246,195
Creation transaction
0x6c3cf5f64f…67a0fe3de0
Main copy (most transactions)
0x4f55cf37…670c566a

36 files

contracts/swappers/easySwapperV2/libraries/dytm/DytmWithdrawLib.sol

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

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

import {IPoolLogic} from "../../../../interfaces/IPoolLogic.sol";
import {IHasGuardInfo} from "../../../../interfaces/IHasGuardInfo.sol";
import {IHasAssetInfo} from "../../../../interfaces/IHasAssetInfo.sol";
import {IERC20} from "../../../../interfaces/IERC20.sol";
import {IERC20Extended} from "../../../../interfaces/IERC20Extended.sol";
import {IDytmOffice} from "../../../../interfaces/dytm/IDytmOffice.sol";
import {IDytmPeriphery} from "../../../../interfaces/dytm/IDytmPeriphery.sol";
import {IDytmWithdrawProcessor} from "../../../../interfaces/dytm/IDytmWithdrawProcessor.sol";
import {IEasySwapperV2} from "../../interfaces/IEasySwapperV2.sol";
import {DytmParamStructs} from "../../../../utils/dytm/DytmParamStructs.sol";
import {DytmSplitTokenIdTracker} from "../../../../guards/assetGuards/dytm/DytmSplitTokenIdTracker.sol";
import {DytmOfficeAssetGuard} from "../../../../guards/assetGuards/dytm/DytmOfficeAssetGuard.sol";

/// @title DytmWithdrawLib
/// @notice Dispatcher invoked from `WithdrawalVault._unrollAssets` for the DYTM branch. Reads
///         the split positions populated during `withdrawProcessing`, transfers them to the
///         `DytmWithdrawProcessor`, and forwards the user's `UnwindPlan` to it.
library DytmWithdrawLib {
  using SafeMath for uint256;

  uint256 internal constant MAX_SLIPPAGE_TOLERANCE_BPS = 200; // 2% protocol-side cap
  uint256 internal constant BPS_DENOMINATOR = 10_000;
  /// @dev Absolute cap (USD, 1e18) on the dust remnant a split account may be left holding
  ///      when a sub-$1 GM leg can't be swapped via Ondo attestation. Bounds how much value
  ///      a plan can orphan back into the pool as an untracked isolated account.
  uint256 internal constant MAX_REMNANT_VALUE_USD = 3e18; // $3

  /// @notice One step in the unwind plan. Same shape as `IAssetGuard.MultiTransaction`.
  struct Action {
    address to;
    bytes data;
  }

  /// @notice User's withdrawal plan, encoded into `IPoolLogic.ComplexAsset.withdrawData`.
  struct UnwindPlan {
    Action[] actions;
    address outputAsset;
    uint256 minOutputAmount;
  }

  /// @notice Process DYTM position unwinding during EasySwapper withdrawal
  /// @param _dytmOffice DYTM Office address (asset type 106)
  /// @param _complexAsset Complex asset entry for the DYTM Office (positionally aligned with pool's supportedAssets upstream)
  /// @param _creator EasySwapperV2 address
  /// @param _dHedgeVault Pool the withdrawal is unrolling — used to constrain `outputAsset` to a pool-supported token
  /// @return tokensToTrack Tokens expected in vault after processing
  function processDytmPosition(
    address _dytmOffice,
    IPoolLogic.ComplexAsset memory _complexAsset,
    address _creator,
    address _dHedgeVault
  ) external returns (address[] memory tokensToTrack) {
    // 1. Read split positions — split accounts were transferred to this vault by the pool's withdrawProcessing.
    //    `address(this)` is the WithdrawalVault since this library runs in vault context.
    address assetGuard = _getAssetGuard(_dytmOffice, _creator);
    DytmSplitTokenIdTracker.SplitPosition[] memory splitPositions = DytmSplitTokenIdTracker(assetGuard)
      .getSplitPositions(address(this));
    if (splitPositions.length == 0) return tokensToTrack;

    require(_complexAsset.supportedAsset == _dytmOffice, "invalid asset");

    UnwindPlan memory plan = abi.decode(_complexAsset.withdrawData, (UnwindPlan));

    // 2. Transfer the split accounts to the processor and hand off the unwind.
    address processor = DytmOfficeAssetGuard(assetGuard).dytmWithdrawProcessor();

    // Lock the output asset to the processor's configured USDC: keeps the slippage cap below in
    // USD terms, prevents non-DEX-tradeable outputs (PT, dHEDGE pool tokens) from being handed
    // to the user, and removes the GM-output edge case that would denominate the cap in mint units.
    require(plan.outputAsset == IDytmWithdrawProcessor(processor).usdc(), "outputAsset must be USDC");

    // Protocol-side cap on slippage tolerance — caller can set tighter, never looser.
    require(_complexAsset.slippageTolerance <= MAX_SLIPPAGE_TOLERANCE_BPS, "slippage > 2%");

    // Snapshot `outputAsset` and the split positions' USD value before the unwind runs.
    address dytmPeriphery = DytmOfficeAssetGuard(assetGuard).dytmPeriphery();
    uint256 balanceBefore = IERC20(plan.outputAsset).balanceOf(address(this));
    uint256 expectedValueUSD = _sumSplitPositionsValueUSD(splitPositions, dytmPeriphery);

    for (uint256 i; i < splitPositions.length; ++i) {
      IDytmOffice(_dytmOffice).transfer(processor, splitPositions[i].tokenId, 1);
    }

    IDytmWithdrawProcessor(processor).process(
      IDytmWithdrawProcessor.UnwindPlanRequest({
        dytmOffice: _dytmOffice,
        pool: _dHedgeVault,
        splitPositions: splitPositions,
        actions: plan.actions,
        outputAsset: plan.outputAsset
      })
    );

    // A sub-$1 GM leg can't be swapped via Ondo attestation, so the processor may hand a dust
    // remnant back to the pool instead of fully draining a split account. Bound that remnant's
    // gross collateral; the depositor's forfeit of it is already covered by the slippage check.
    require(
      _sumSplitPositionsCollateralUSD(splitPositions, dytmPeriphery) <= MAX_REMNANT_VALUE_USD,
      "remnant too large"
    );

    uint256 received = IERC20(plan.outputAsset).balanceOf(address(this)).sub(balanceBefore);
    uint256 expectedOutput = _usdToOutputAmount(expectedValueUSD, plan.outputAsset, _dHedgeVault);
    require(
      received >= plan.minOutputAmount &&
        received.mul(BPS_DENOMINATOR) >= expectedOutput.mul(BPS_DENOMINATOR.sub(_complexAsset.slippageTolerance)),
      "high slippage"
    );

    tokensToTrack = new address[](1);
    tokensToTrack[0] = plan.outputAsset;
  }

  function _getAssetGuard(address _dytmOffice, address _creator) private view returns (address) {
    address poolFactory = IEasySwapperV2(_creator).dHedgePoolFactory();
    return IHasGuardInfo(poolFactory).getAssetGuard(_dytmOffice);
  }

  /// @dev Sum the net USD value (collateral − debt) of every split position the unwind owns,
  ///      using DYTM Periphery as the source of truth for position valuation.
  function _sumSplitPositionsValueUSD(
    DytmSplitTokenIdTracker.SplitPosition[] memory _splitPositions,
    address _dytmPeriphery
  ) private view returns (uint256 totalUSD) {
    for (uint256 i; i < _splitPositions.length; ++i) {
      DytmParamStructs.AccountPosition memory pos = IDytmPeriphery(_dytmPeriphery).getAccountPosition(
        _splitPositions[i].tokenId,
        _splitPositions[i].marketId
      );
      if (pos.totalCollateralValueUSD > pos.debt.debtValueUSD) {
        totalUSD = totalUSD.add(pos.totalCollateralValueUSD.sub(pos.debt.debtValueUSD));
      }
    }
  }

  /// @dev Sum the gross collateral USD of every split position. Called after the unwind to bound
  ///      the sub-$1 GM dust remnant the processor may leave behind; drained accounts add zero.
  function _sumSplitPositionsCollateralUSD(
    DytmSplitTokenIdTracker.SplitPosition[] memory _splitPositions,
    address _dytmPeriphery
  ) private view returns (uint256 totalUSD) {
    for (uint256 i; i < _splitPositions.length; ++i) {
      DytmParamStructs.AccountPosition memory pos = IDytmPeriphery(_dytmPeriphery).getAccountPosition(
        _splitPositions[i].tokenId,
        _splitPositions[i].marketId
      );
      totalUSD = totalUSD.add(pos.totalCollateralValueUSD);
    }
  }

  /// @dev Convert a USD value (1e18-scaled) to `_outputAsset` units. Only enforces the
  ///      staleness bound when the asset has a configured `maxPriceAge` (0 = no freshness
  ///      check, same convention as `PoolManagerLogic.totalFundValueWithMaxAge`).
  function _usdToOutputAmount(
    uint256 _usdValue,
    address _outputAsset,
    address _dHedgeVault
  ) private view returns (uint256) {
    address factory = IPoolLogic(_dHedgeVault).factory();
    (uint256 priceUSD, uint256 updatedAt, uint256 maxPriceAge) = IHasAssetInfo(factory).getAssetPriceWithTime(
      _outputAsset
    );
    if (maxPriceAge > 0) {
      require(block.timestamp.sub(updatedAt) <= maxPriceAge, "stale outputAsset price");
    }
    uint256 outputDecimals = IERC20Extended(_outputAsset).decimals();
    return _usdValue.mul(10 ** outputDecimals).div(priceUSD);
  }
}

@openzeppelin/contracts/math/SafeMath.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

@openzeppelin/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/dytm/DytmOfficeAssetGuard.sol

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

import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {SafeCast} from "@openzeppelin/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 {DytmHelperLib} from "../../../utils/dytm/DytmHelperLib.sol";
import {IPoolLogic} from "../../../interfaces/IPoolLogic.sol";
import {IAddAssetCheckGuard} from "../../../interfaces/guards/IAddAssetCheckGuard.sol";
import {IHasSupportedAsset} from "../../../interfaces/IHasSupportedAsset.sol";

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

  bool public override isAddAssetCheckGuard = true;

  /// @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) external view override {
    require(!_asset.isDeposit, "deposit not supported");
    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/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/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/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/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), or OndoGMTokenAssetGuard.OndoWithdrawData (Ondo GM, type 41)
    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/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/dytm/IDytmWithdrawProcessor.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;
pragma experimental ABIEncoderV2;

import {DytmSplitTokenIdTracker} from "../../guards/assetGuards/dytm/DytmSplitTokenIdTracker.sol";
import {DytmWithdrawLib} from "../../swappers/easySwapperV2/libraries/dytm/DytmWithdrawLib.sol";

/// @title IDytmWithdrawProcessor
/// @notice External surface for the DYTM unwind processor. Sits between `WithdrawalVault`
///         (which transfers freshly-split DYTM accounts to it) and the DYTM Office
///         (which it calls back into via `delegationCall`).
interface IDytmWithdrawProcessor {
  /// @notice Full payload for one unwind. `dytmOffice`, `pool` and `splitPositions` are supplied
  ///         by the calling lib (runtime context); `actions` and `outputAsset` come from the
  ///         user-supplied `DytmWithdrawLib.UnwindPlan` in `ComplexAsset.withdrawData`.
  /// @dev    `pool` is where the processor returns any sub-$1 GM dust remnant a split account
  ///         can't be fully drained of (Ondo rejects sub-$1 attestation swaps).
  struct UnwindPlanRequest {
    address dytmOffice;
    address pool;
    DytmSplitTokenIdTracker.SplitPosition[] splitPositions;
    DytmWithdrawLib.Action[] actions;
    address outputAsset;
  }

  /// @notice Execute the user's DYTM unwind plan in the processor's isolated context.
  /// @dev    Caller must be a `WithdrawalVault` registered with `easySwapperV2`. The caller must
  ///         have already transferred the split DYTM accounts (matching `splitPositions`) to the
  ///         processor before calling.
  /// @return received  `outputAsset` gain produced by the unwind, transferred back to the caller.
  function process(UnwindPlanRequest calldata params) external returns (uint256 received);

  /// @notice Canonical settlement token enforced by `DytmWithdrawLib` as `plan.outputAsset`.
  function usdc() external view returns (address);
}

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

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

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