Skip to content
Verified contractExactMIT

MidasRedemptionVaultContractGuard

Address0xd71b7136dd2ee8a00b94e97cbf8df59627a044d9
Balance

0 ETH

 

Transactions

2

 

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
25,830,597
Creation transaction
0xd70e784877…e56f1ba334

contracts/guards/contractGuards/midas/MidasRedemptionVaultContractGuard.sol

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

pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import {IHasSupportedAsset} from "../../../interfaces/IHasSupportedAsset.sol";
import {IMidasRedemptionVault} from "../../../interfaces/midas/IMidasRedemptionVault.sol";
import {IMidasRedemptionVaultContractGuard} from "../../../interfaces/midas/IMidasRedemptionVaultContractGuard.sol";
import {ITransactionTypes} from "../../../interfaces/ITransactionTypes.sol";
import {PoolsWhitelist} from "../../../utils/PoolsWhitelist.sol";
import {SlippageAccumulator, SlippageAccumulatorUser} from "../../../utils/SlippageAccumulatorUser.sol";
import {TxDataUtils} from "../../../utils/TxDataUtils.sol";

/// @title MidasRedemptionVaultContractGuard
/// @notice Contract guard for a Midas RedemptionVault. Allows a manager to either instantly redeem an
///         mToken to `tokenOut` (fee-bearing, atomic) or open an async redemption request, settled
///         later at the curator-approved rate. Custom-recipient overloads are blocked so redeemed
///         tokens and pending claims always belong to the pool.
/// @dev `redeemInstant` output is checked against the shared `SlippageAccumulator` using measured
///      pre/post balance deltas (the manager-supplied `minReceiveAmount` is not trusted).
///      `redeemRequest` carries no min amount (settled later at the curator-approved rate) and is
///      tracked per pool instead, so the pending-redemption asset guard (type 43) can value the
///      outstanding claim and service withdrawals while it is unsettled.
/// @dev A request can only be settled (`approveRequest`) or rejected (`rejectRequest`) by the Midas
///      vault admin — the request author cannot cancel it, so no cancel path exists in this guard.
///      On rejection the mToken is NOT auto-returned: the request just turns Canceled (terminal) and
///      Midas ops transfer the tokens back manually via `ManageableVault.withdrawToken`, which is
///      gated by `onlyVaultAdmin` (Midas vault admin role) and carries no on-chain link between the
///      transfer and the request. Until the return, the claim's value is not representable on-chain,
///      so the pending-redemption asset guard FREEZES the pool's pricing (totalFundValue — and thus
///      deposits, withdrawals and trading — reverts) the moment a tracked request turns Canceled:
///      a vault must never transact at an understated total value. Once the tokens are verifiably
///      back in the pool, the guard owner lifts the freeze via `reconcileCanceledRequests`. Both the
///      mToken and the request's `tokenOut` must stay enabled while a request is unresolved so the
///      incoming tokens are accounted — enforced by `ERC20Guard._checkMidasPendingRedemptions`.
/// @dev This guard is also the single owned contract of the Midas integration: it holds the pool
///      whitelist (`PoolsWhitelist`), enforced at configuration time (both Midas asset guards'
///      `addAssetCheck`) and, for consistency, in this guard's `txGuard`.
/// @dev REDEPLOYMENT RISK: `pendingRequestIds` (and the pool whitelist) live in this guard's storage.
///      Replacing this guard (`Governance.setContractGuard`) while any pool has a Pending request
///      makes the claim invisible to the new instance — its NAV contribution vanishes and withdrawals
///      proceed as if nothing were pending. Settle or reject all outstanding requests before swapping
///      this guard.
contract MidasRedemptionVaultContractGuard is
  TxDataUtils,
  ITransactionTypes,
  SlippageAccumulatorUser,
  PoolsWhitelist,
  IMidasRedemptionVaultContractGuard
{
  /// @notice Bounds the tracked request list per (pool, vault): every id in it costs an external
  ///         status check in each NAV computation, so unbounded growth would let a manager bloat
  ///         (and eventually brick) the pool's pricing loop with dust redemptions.
  uint256 public constant MAX_TRACKED_REQUESTS = 10;

  // Recorded async redemption request ids per pool per redemption vault (ids are vault-local
  // monotonic counters, so they must never be mixed across vaults). Pruned of settled ids as new
  // requests are opened; consumers must re-check status against the vault.
  mapping(address => mapping(address => uint256[])) private pendingRequestIds;

  constructor(
    address _slippageAccumulator,
    address[] memory _whitelistedPools
  ) SlippageAccumulatorUser(_slippageAccumulator) PoolsWhitelist(_whitelistedPools) {}

  /// @inheritdoc IMidasRedemptionVaultContractGuard
  function getPendingRequestIds(
    address _pool,
    address _vault
  ) external view override returns (uint256[] memory requestIds) {
    requestIds = pendingRequestIds[_pool][_vault];
  }

  /// @inheritdoc IMidasRedemptionVaultContractGuard
  /// @dev Between a settlement and the next `redeemRequest`, stale ids cost an external status check
  ///      in every NAV computation of the pool — anyone can call this to stop paying for them.
  ///      Only removes Processed ids, so it's safe to be permissionless; Canceled ids are deliberately
  ///      kept (they freeze pricing) and can only be removed via `reconcileCanceledRequests`.
  function pruneSettledRequests(address _pool, address _vault) external override {
    _pruneByStatus(_pool, _vault, IMidasRedemptionVault.RequestStatus.Processed);
  }

  /// @inheritdoc IMidasRedemptionVaultContractGuard
  /// @dev Owner (or a signer of the owning Safe) only: called after ops verify Midas returned the
  ///      rejected mTokens to the pool. Reconciling BEFORE the return would leave the vault's total
  ///      value understated — exactly the catastrophe the freeze exists to prevent — so this is
  ///      deliberately not permissionless and not manager-callable.
  function reconcileCanceledRequests(address _pool, address _vault) external override onlyOwnerOrSafeSigner(owner()) {
    _pruneByStatus(_pool, _vault, IMidasRedemptionVault.RequestStatus.Canceled);
  }

  /// @notice Validates a manager transaction routed to a Midas RedemptionVault.
  /// @param _poolManagerLogic Pool manager logic address.
  /// @param _to The RedemptionVault being called.
  /// @param _data Calldata of the transaction.
  /// @return txType Transaction type (Exchange) when allowed.
  /// @return isPublic Always false (manager-only).
  function txGuard(
    address _poolManagerLogic,
    address _to,
    bytes memory _data
  ) external override returns (uint16 txType, bool isPublic) {
    address poolLogic = _accessControl(_poolManagerLogic);

    // Consistent with the asset-adding gate: only whitelisted pools can transact with the vault.
    require(poolsWhitelist[poolLogic], "pool not whitelisted");

    bytes4 method = getMethod(_data);

    // `tokenOut` is the first argument of both allowed methods and must be accounted by the pool.
    address tokenOut = convert32toAddress(getInput(_data, 0));

    if (method == IMidasRedemptionVault.redeemInstant.selector) {
      require(IHasSupportedAsset(_poolManagerLogic).isSupportedAsset(tokenOut), "unsupported destination asset");

      address mToken = IMidasRedemptionVault(_to).mToken();

      // Record pre-execution balances; the inherited `afterTxGuard` measures the actual delta.
      intermediateSwapData = SlippageAccumulator.SwapData({
        srcAsset: mToken,
        dstAsset: tokenOut,
        srcAmount: _getBalance(mToken, poolLogic),
        dstAmount: _getBalance(tokenOut, poolLogic)
      });

      txType = uint16(TransactionType.Exchange);
    } else if (method == IMidasRedemptionVault.redeemRequest.selector) {
      // `tokenOut` must stay enabled until settlement pays it in. That stay-enabled protection
      // (`ERC20Guard._checkMidasPendingRedemptions`) lives in tokenOut's ASSET guard, so it assumes
      // tokenOut's asset type resolves to a guard inheriting ERC20Guard — true for plain ERC20
      // stablecoins like USDC, which is what Midas uses as payment tokens.
      require(IHasSupportedAsset(_poolManagerLogic).isSupportedAsset(tokenOut), "unsupported destination asset");
      // The pending claim is paid out of (and, on rejection, returned to) the pool's mToken position,
      // so the mToken must be an accounted asset for the claim's whole lifecycle.
      require(
        IHasSupportedAsset(_poolManagerLogic).isSupportedAsset(IMidasRedemptionVault(_to).mToken()),
        "unsupported source asset"
      );
      // The vault must be enabled as a pending-redemption position asset so the outstanding claim
      // is valued and withdrawals against it are serviced until the request settles.
      require(IHasSupportedAsset(_poolManagerLogic).isSupportedAsset(_to), "pending redemption not supported");

      txType = uint16(TransactionType.Exchange);
    }

    return (txType, false);
  }

  /// @notice Post-transaction processing.
  /// @dev For `redeemInstant`: delegates to the inherited measured-delta slippage accumulation.
  ///      For `redeemRequest`: records the newly opened async request so the pending-redemption asset
  ///      guard can value it and service withdrawals against it. Called by `PoolLogic` after execution.
  function afterTxGuard(address _poolManagerLogic, address _to, bytes memory _data) public override {
    if (getMethod(_data) == IMidasRedemptionVault.redeemRequest.selector) {
      address poolLogic = _accessControl(_poolManagerLogic);

      // The just-created request was assigned the id preceding the incremented counter.
      uint256 assignedId = IMidasRedemptionVault(_to).currentRequestId() - 1;

      _pruneByStatus(poolLogic, _to, IMidasRedemptionVault.RequestStatus.Processed);
      require(pendingRequestIds[poolLogic][_to].length < MAX_TRACKED_REQUESTS, "too many pending requests");
      pendingRequestIds[poolLogic][_to].push(assignedId);
    } else {
      SlippageAccumulatorUser.afterTxGuard(_poolManagerLogic, _to, _data);
    }
  }

  /// @dev Removes ids whose request has the given status, bounding the stored list size. Iterates
  ///      backwards with swap-and-pop: an element swapped in from the tail was already inspected.
  function _pruneByStatus(address _pool, address _vault, IMidasRedemptionVault.RequestStatus _status) internal {
    uint256[] storage ids = pendingRequestIds[_pool][_vault];

    for (uint256 i = ids.length; i > 0; i--) {
      (, , uint8 status, , , ) = IMidasRedemptionVault(_vault).redeemRequests(ids[i - 1]);

      if (status == uint8(_status)) {
        ids[i - 1] = ids[ids.length - 1];
        ids.pop();
      }
    }
  }
}

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "../utils/Context.sol";
/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor () {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

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

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}

@openzeppelin/contracts/math/Math.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a >= b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow, so we distribute
        return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
    }
}

@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/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/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with GSN meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address payable) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes memory) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}

@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/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/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/ISafe.sol

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

interface ISafe {
  function isOwner(address owner) external view returns (bool);
  function getOwners() external view returns (address[] memory);
}

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

contracts/interfaces/guards/IAccountedTokenAssetGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;

/// @notice Optional asset guard capability: declares receipt tokens the guard already values.
/// @dev For guards valuing a position via receipt tokens the pool holds (e.g. aToken balances) instead of
///      the supported asset's own balance. Such receipts are unregistered, so `isSupportedAsset` checks
///      miss them; swap guards use this to refuse selling them.
interface IAccountedTokenAssetGuard {
  /// @notice Capability flag, probed before `isAccountedToken`.
  function isAccountedTokenAssetGuard() external view returns (bool);

  /// @param asset The supported (umbrella) asset this guard is registered for.
  /// @return accounted True if `token`'s value is already counted by this guard for `pool`.
  function isAccountedToken(address pool, address asset, address token) external view returns (bool accounted);
}

contracts/interfaces/guards/IGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;

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

contracts/interfaces/guards/ITxTrackingGuard.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.7.6;

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

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

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

contracts/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/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/PoolsWhitelist.sol

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

pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

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

/// @title PoolsWhitelist
/// @notice Owner-managed whitelist of pools, for guards that gate an integration to
///         protocol-chosen vaults. Seeded at deployment and adjustable afterwards by the owner —
///         or, when the owner is a Safe, by any of its signers (`SafeSignerAccess`).
abstract contract PoolsWhitelist is Ownable, SafeSignerAccess {
  struct WhitelistSetting {
    address poolLogic;
    bool whitelisted;
  }

  /// @notice Pools allowed to use the integration protected by the inheriting guard.
  mapping(address => bool) public poolsWhitelist;

  event PoolWhitelistSet(address poolLogic, bool whitelisted);

  constructor(address[] memory _whitelistedPools) {
    for (uint256 i; i < _whitelistedPools.length; ++i) {
      _setPoolWhitelisted(_whitelistedPools[i], true);
    }
  }

  function setPoolsWhitelist(WhitelistSetting[] calldata _settings) external onlyOwnerOrSafeSigner(owner()) {
    for (uint256 i; i < _settings.length; ++i) {
      _setPoolWhitelisted(_settings[i].poolLogic, _settings[i].whitelisted);
    }
  }

  function _setPoolWhitelisted(address _poolLogic, bool _whitelisted) private {
    require(_poolLogic != address(0), "invalid pool");

    poolsWhitelist[_poolLogic] = _whitelisted;

    emit PoolWhitelistSet(_poolLogic, _whitelisted);
  }
}

contracts/utils/SafeSignerAccess.sol

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

import {ISafe} from "../interfaces/ISafe.sol";

/// @title SafeSignerAccess
/// @notice Abstract contract that allows any Safe owner (as returned by `ISafe.isOwner`) to call restricted functions.
/// @dev The `onlyOwnerOrSafeSigner` modifier takes the owner address as a parameter.
///      If the owner is a Safe, any account registered as a Safe owner can pass the check.
///      If the owner is not a Safe (e.g., an EOA), only the owner address itself is accepted.
abstract contract SafeSignerAccess {
  modifier onlyOwnerOrSafeSigner(address _owner) {
    _checkOwnerOrSafeSigner(_owner);
    _;
  }

  function _checkOwnerOrSafeSigner(address _owner) internal view {
    if (msg.sender == _owner) return;

    // Try to check if the owner is a Safe and if msg.sender is one of its owners.
    // Note: If `_owner` is an EOA (no code), the external call reverts with
    // "function call to a non-contract account" which is NOT caught by try/catch
    // (the extcodesize check runs before the CALL opcode, outside the try/catch boundary).
    // This is safe because the `msg.sender == _owner` check above already handles the EOA owner case.
    try ISafe(_owner).isOwner(msg.sender) returns (bool isOwner_) {
      require(isOwner_, "not owner or Safe owner");
    } catch {
      // Owner is not a Safe (or doesn't implement isOwner), fall back to strict owner check.
      revert("not owner or Safe owner");
    }
  }
}

contracts/utils/SlippageAccumulator.sol

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

pragma solidity 0.7.6;
pragma abicoder v2;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Math} from "@openzeppelin/contracts/math/Math.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol";

import {IERC20Extended} from "../interfaces/IERC20Extended.sol";
import {IHasAssetInfo} from "../interfaces/IHasAssetInfo.sol";
import {IHasGuardInfo} from "../interfaces/IHasGuardInfo.sol";
import {IHasSupportedAsset} from "../interfaces/IHasSupportedAsset.sol";

/// @notice Contract to check for accumulated slippage impact for a pool manager.
/// @author dHEDGE
contract SlippageAccumulator is Ownable {
  using SafeMath for *;
  using Math for *;
  using SafeCast for *;

  /// @dev Struct for passing swap related data to the slippage accumulator function.
  /// @param srcAsset Source asset (asset to be exchanged).
  /// @param dstAsset Destination asset (asset being exchanged for).
  /// @param srcAmount Source asset amount.
  /// @param dstAmount Destination asset amount.
  struct SwapData {
    address srcAsset;
    address dstAsset;
    uint256 srcAmount;
    uint256 dstAmount;
  }

  /// @dev Struct to track the slippage data for a poolManager.
  /// @param lastTradeTimestamp Last successful trade's timestamp.
  /// @param accumulatedSlippage The accumulated slippage impact of a poolManager.
  struct ManagerSlippageData {
    uint64 lastTradeTimestamp;
    uint128 accumulatedSlippage;
  }

  event DecayTimeChanged(uint64 oldDecayTime, uint64 newDecayTime);
  event MaxCumulativeSlippageChanged(uint128 oldMaxCumulativeSlippage, uint128 newMaxCumulativeSlippage);

  /// @dev Constant used to multiply the slippage loss percentage with 4 decimal precision.
  uint128 private constant SCALING_FACTOR = 1e6;

  /// @dev dHEDGE poolFactory address.
  address public immutable poolFactory;

  /// @notice Maximum acceptable cumulative trade slippage impact within a period of time (upto 4 decimal precision).
  /// @dev Eg. 5% = 5e4
  uint128 public maxCumulativeSlippage;

  /// @notice Price accumulator decay time.
  /// @dev Eg 6 hours = 21600.
  uint64 public decayTime;

  /// @notice Tracks the last trade timestamp and accumulated slippage for each poolManager.
  mapping(address => ManagerSlippageData) public managerData;

  /// @dev Modifier to make sure caller is a contract guard.
  modifier onlyContractGuard(address to) {
    address contractGuard = IHasGuardInfo(poolFactory).getContractGuard(to);

    require(contractGuard == msg.sender, "Not authorised guard");
    _;
  }

  constructor(address _poolFactory, uint64 _decayTime, uint128 _maxCumulativeSlippage) {
    require(_poolFactory != address(0), "Null address");

    poolFactory = _poolFactory;
    decayTime = _decayTime;
    maxCumulativeSlippage = _maxCumulativeSlippage;
  }

  /// @notice Updates the cumulative slippage impact and reverts if it's beyond limit.
  /// @dev NOTE: It's important that the calling guard checks if the msg.sender in it's scope is authorised.
  /// @dev If the caller is not checked for in the guard, anyone can trigger the `txGuard` transaction and update slippage impact.
  /// @param poolManagerLogic Address of the poolManager whose cumulative impact is stored.
  /// @param router Address of the router contract used for swapping.
  /// @param swapData Common swap data for all guards.
  function updateSlippageImpact(
    address poolManagerLogic,
    address router,
    SwapData calldata swapData
  ) external onlyContractGuard(router) {
    require(swapData.srcAmount != 0, "0 src amount");

    if (IHasSupportedAsset(poolManagerLogic).isSupportedAsset(swapData.srcAsset)) {
      uint256 srcValue = assetValue(swapData.srcAsset, swapData.srcAmount);
      uint256 dstValue = assetValue(swapData.dstAsset, swapData.dstAmount);

      // Only update the cumulative slippage in case the amount received is lesser than amount sent/traded.
      if (dstValue < srcValue) {
        _accumulateSlippage(poolManagerLogic, srcValue.sub(dstValue), srcValue);
      }
    }
  }

  /// @notice Cumulative slippage check based on the pool's total fund value delta across an operation.
  /// @dev Complements `updateSlippageImpact` for swaps with an unsupported source asset, where per-asset
  ///      pricing is skipped and value could leave unmeasured. Any net DROP counts as slippage; preserving
  ///      or increasing fund value (e.g. selling an unaccounted reward token) is a no-op.
  /// @dev NOTE: It's important that the calling guard checks that the msg.sender in its scope is authorised.
  /// @param poolManagerLogic Address of the poolManager whose cumulative impact is stored.
  /// @param router Address of the router contract used for swapping.
  /// @param totalValueBefore Pool total fund value before the swap.
  /// @param totalValueAfter Pool total fund value after the swap.
  function updateSlippageImpactByValue(
    address poolManagerLogic,
    address router,
    uint256 totalValueBefore,
    uint256 totalValueAfter
  ) external onlyContractGuard(router) {
    // Only a net DROP is accounted (this also covers totalValueBefore == 0).
    if (totalValueAfter < totalValueBefore) {
      _accumulateSlippage(poolManagerLogic, totalValueBefore.sub(totalValueAfter), totalValueBefore);
    }
  }

  /// @dev Adds `valueLost / valueBase` (scaled) to the decaying cumulative slippage and reverts if over the
  ///      cap. Callers must ensure `valueBase != 0`.
  function _accumulateSlippage(address poolManagerLogic, uint256 valueLost, uint256 valueBase) internal {
    uint128 newSlippage = valueLost.mul(SCALING_FACTOR).div(valueBase).toUint128();

    uint128 newCumulativeSlippage = (uint256(newSlippage).add(getCumulativeSlippageImpact(poolManagerLogic)))
      .toUint128();

    require(newCumulativeSlippage < maxCumulativeSlippage, "slippage impact exceeded");

    managerData[poolManagerLogic].lastTradeTimestamp = (block.timestamp).toUint64();

    managerData[poolManagerLogic].accumulatedSlippage = newCumulativeSlippage;
  }

  /// Function to calculate an asset amount's value in usd.
  /// @param asset The asset whose price oracle exists.
  /// @param amount The amount of the `asset`.
  function assetValue(address asset, uint256 amount) public view returns (uint256 value) {
    value = amount.mul(IHasAssetInfo(poolFactory).getAssetPrice(asset)).div(10 ** IERC20Extended(asset).decimals()); // to USD amount
  }

  /// @notice Function to get the cumulative slippage adjusted using decayTime (current cumulative slippage impact).
  /// @param poolManagerLogic Address of the poolManager whose cumulative impact is stored.
  function getCumulativeSlippageImpact(address poolManagerLogic) public view returns (uint128 cumulativeSlippage) {
    ManagerSlippageData memory managerSlippageData = managerData[poolManagerLogic];

    return
      (
        uint256(managerSlippageData.accumulatedSlippage)
          .mul(decayTime.sub(decayTime.min(block.timestamp.sub(managerSlippageData.lastTradeTimestamp))))
          .div(decayTime)
      ).toUint128();
  }

  /**********************************************
   *             Owner Functions                *
   *********************************************/

  /// @notice Function to change decay time for calculating price impact.
  /// @param newDecayTime The new decay time (in seconds).
  function setDecayTime(uint64 newDecayTime) external onlyOwner {
    uint64 oldDecayTime = decayTime;

    decayTime = newDecayTime;

    emit DecayTimeChanged(oldDecayTime, newDecayTime);
  }

  /// @notice Function to change the max acceptable cumulative slippage impact.
  /// @param newMaxCumulativeSlippage The new max acceptable cumulative slippage impact.
  function setMaxCumulativeSlippage(uint128 newMaxCumulativeSlippage) external onlyOwner {
    uint128 oldMaxCumulativeSlippage = maxCumulativeSlippage;

    maxCumulativeSlippage = newMaxCumulativeSlippage;

    emit MaxCumulativeSlippageChanged(oldMaxCumulativeSlippage, newMaxCumulativeSlippage);
  }
}

contracts/utils/SlippageAccumulatorUser.sol

// SPDX-License-Identifier: MIT

pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;

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

import {IPoolFactory} from "../interfaces/IPoolFactory.sol";
import {IPoolManagerLogic} from "../interfaces/IPoolManagerLogic.sol";
import {IHasSupportedAsset} from "../interfaces/IHasSupportedAsset.sol";
import {IHasGuardInfo} from "../interfaces/IHasGuardInfo.sol";
import {IAccountedTokenAssetGuard} from "../interfaces/guards/IAccountedTokenAssetGuard.sol";
import {ITxTrackingGuard} from "../interfaces/guards/ITxTrackingGuard.sol";

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

abstract contract SlippageAccumulatorUser is ITxTrackingGuard {
  using SafeMath for *;

  bool public override isTxTrackingGuard = true;

  SlippageAccumulator public immutable slippageAccumulator;

  /// @dev Note that the intermediateSwapData is used to store the data temporarily
  ///      after a swap is completed, this is used to update the slippage impact.
  ///      the `dstAmount` stored in this struct before execution of `afterTxGuard` is the prior balance of the pool for the destination asset.
  SlippageAccumulator.SwapData internal intermediateSwapData;

  /// @dev Total fund value before a swap with an unsupported source asset; consumed by `afterTxGuard`.
  uint256 internal intermediateTotalValueBefore;

  constructor(address _slippageAccumulator) {
    require(_slippageAccumulator != address(0), "invalid address");

    slippageAccumulator = SlippageAccumulator(_slippageAccumulator);
  }

  function afterTxGuard(address poolManagerLogic, address to, bytes memory /* data */) public virtual override {
    address poolLogic = _accessControl(poolManagerLogic);

    slippageAccumulator.updateSlippageImpact(
      poolManagerLogic,
      to,
      SlippageAccumulator.SwapData({
        srcAsset: intermediateSwapData.srcAsset,
        dstAsset: intermediateSwapData.dstAsset,
        srcAmount: intermediateSwapData.srcAmount.sub(_getBalance(intermediateSwapData.srcAsset, poolLogic)),
        dstAmount: _getBalance(intermediateSwapData.dstAsset, poolLogic).sub(intermediateSwapData.dstAmount)
      })
    );
    intermediateSwapData = SlippageAccumulator.SwapData(address(0), address(0), 0, 0);

    // Unsupported source: per-asset pricing above is skipped, so catch value leaving via the fund-value delta.
    uint256 totalValueBefore = intermediateTotalValueBefore;
    if (totalValueBefore != 0) {
      intermediateTotalValueBefore = 0;
      slippageAccumulator.updateSlippageImpactByValue(
        poolManagerLogic,
        to,
        totalValueBefore,
        IPoolManagerLogic(poolManagerLogic).totalFundValue()
      );
    }
  }

  /// @dev Swap guards MUST call this in `txGuard` with the swap's source asset. For an unsupported source
  ///      (which the `SlippageAccumulator` cannot price) it forbids selling an already-accounted token and
  ///      snapshots total fund value for the net-value check in `afterTxGuard`.
  function _beforeSwapSourceGuard(address poolManagerLogic, address srcAsset) internal virtual {
    if (!IHasSupportedAsset(poolManagerLogic).isSupportedAsset(srcAsset)) {
      _requireSrcNotAccounted(poolManagerLogic, srcAsset);
      intermediateTotalValueBefore = IPoolManagerLogic(poolManagerLogic).totalFundValue();
    }
  }

  /// @dev Forbids selling a token already counted by an "umbrella" asset guard (e.g. an Aave aToken); such
  ///      positions must be unwound through their protocol. Protocol-agnostic: guards declare their own
  ///      receipts via `IAccountedTokenAssetGuard`, so a new integration needs no change here. Same
  ///      capability probe as `PoolManagerLogic._addAsset`, via `staticcall` as this is a view.
  function _requireSrcNotAccounted(address poolManagerLogic, address srcAsset) internal view {
    address factory = slippageAccumulator.poolFactory();
    address poolLogic = IPoolManagerLogic(poolManagerLogic).poolLogic();
    IHasSupportedAsset.Asset[] memory supportedAssets = IHasSupportedAsset(poolManagerLogic).getSupportedAssets();

    for (uint256 i; i < supportedAssets.length; ++i) {
      address assetGuard = IHasGuardInfo(factory).getAssetGuard(supportedAssets[i].asset);

      if (assetGuard == address(0)) continue;

      // solhint-disable-next-line avoid-low-level-calls
      (bool hasFunction, bytes memory answer) = assetGuard.staticcall(
        abi.encodeWithSignature("isAccountedTokenAssetGuard()")
      );

      if (hasFunction && answer.length == 32 && abi.decode(answer, (bool))) {
        require(
          !IAccountedTokenAssetGuard(assetGuard).isAccountedToken(poolLogic, supportedAssets[i].asset, srcAsset),
          "accounted token source"
        );
      }
    }
  }

  function _getBalance(address token, address holder) internal view returns (uint256) {
    // This is to avoid reverts during wrap/unwrap attempts via 1inch (which still should revert downstream)
    return (token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) ? holder.balance : IERC20(token).balanceOf(holder);
  }

  function _accessControl(address poolManagerLogic) internal view returns (address poolLogic) {
    poolLogic = IPoolManagerLogic(poolManagerLogic).poolLogic();

    require(
      msg.sender == poolLogic && IPoolFactory(slippageAccumulator.poolFactory()).isPool(poolLogic),
      "not pool logic"
    );
  }
}

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)));
  }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 20,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.