Skip to content
Verified contractPartialBUSL-1.1

VaultExecutor

Address0x552c97fd28a39b3d70079bf0468293ecf1a791ba
Balance

0 ETH

 

Transactions

48

 

Compiler

solc 0.7.6

 

Same code

Only this contract

 

Details

Compiler
solc 0.7.6+commit.7338295f
Language
solidity
Optimization
Yes, 800 runs
EVM version
istanbul
License
BUSL-1.1
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,221,125
Creation transaction
0xe3e52b182f…736107d851

contracts/VaultExecutor.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.7.6;
pragma abicoder v2;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { RebalanceGuard } from "./lib/RebalanceGuard.sol";

interface IVault {
    // Routine ops — rebalancer / advisor
    function rebalance(
        int24 _baseLower, int24 _baseUpper,
        int24 _limitLower, int24 _limitUpper,
        address _feeRecipient,
        uint256[4] memory mintMins,
        uint256[4] memory burnMins
    ) external;
    function pullPositionLiquidity(
        int24 tickLower, int24 tickUpper, uint128 shares, uint256[2] memory burnMins
    ) external returns (uint256, uint256);
    function addLiquidity(
        int24 tickLower, int24 tickUpper, uint256 amount0, uint256 amount1, uint256[2] memory mintMins
    ) external;
    function compound(uint256[4] memory mintMins) external;

    // Admin ops
    function setDepositor(address) external;
    function clearDepositor() external;
    function setFeeDivisor(uint8) external;
    function setFeeRecipient(address) external;
    function toggleAutoStake() external;
    function proposeOwnership(address) external;
    function acceptOwnership() external;

    // Views
    function owner() external view returns (address);
    function pendingOwner() external view returns (address);
    function baseLower() external view returns (int24);
    function baseUpper() external view returns (int24);
    function limitLower() external view returns (int24);
    function limitUpper() external view returns (int24);
}

/// @title VaultExecutor
/// @author fluxIQ
/// @notice Thin role-separating wrapper between a multisig owner and a fluxIQ Vault.
/// @dev Architecture:
///
///   - The Vault's `owner` is set to *this Executor* (via Vault.proposeOwnership +
///     executor.acceptVaultOwnership). The multisig stays in control of the Vault by
///     being the Executor's `admin`.
///
///   - Per-Vault roles distribute authority:
///       * rebalancer       — periodic rebalance, addLiquidity, pullPositionLiquidity
///       * advisor          — compound only (lighter-trust harvester)
///       * circuitBreaker   — emergency: clear the deposit gate, pull liquidity back
///       * admin            — sensitive (depositor / fee divisor / fee recipient /
///                            autoStake / ownership transfer / role rotation)
///
///   - Routine roles do NOT inherit admin authority. If a keeper key is lost the admin
///     must first `setRebalancer(...)` (or `setAdvisor`) to rotate.
///
///   - `fixOwnership()` permanently locks Vault ownership transfers through this
///     Executor. (This is the original Admin pattern with the bug fixed — the original set
///     the flag to `false` instead of `true`, making the lock a no-op.)
///
/// @dev Solidity 0.7.6 — no `unchecked`, no custom errors. Plain `require` strings.
contract VaultExecutor {

    // ─────────────────────────────────────────────────────────────────────
    // STATE
    // ─────────────────────────────────────────────────────────────────────

    address public admin;
    address public pendingAdmin;

    /// @notice Once set to true via `fixOwnership()`, this Executor can no longer
    /// `proposeVaultOwnership` for any managed Vault. One-way switch.
    bool public ownerFixed;

    mapping(address => address) public rebalancers;
    mapping(address => address) public advisors;
    mapping(address => address) public circuitBreakers;

    // ─── Per-vault rebalance guard config (see RebalanceGuard.sol) ──────
    //
    // Defaults are all zero, which means "no check" — the guard is opt-in
    // per vault. Admin enables protection by calling the corresponding setter.
    //
    // Full-range rebalances (Uniswap V3 ±887272) ALWAYS bypass translation /
    // width checks regardless of these settings — you can always reset to
    // safe ground.

    /// @notice Max absolute drift (in ticks) of the base-position midpoint
    /// between consecutive rebalances. `0` disables the check.
    mapping(address => uint256) public maxTranslation;

    /// @notice Max change (in ticks) of the base-position width between
    /// consecutive rebalances. `0` disables the check.
    mapping(address => uint256) public maxWidth;

    /// @notice Minimum seconds between rebalances for this vault. `0` disables.
    mapping(address => uint256) public minInterval;

    /// @notice Timestamp of the last guard-checked rebalance for this vault.
    /// Auto-updated by `rebalance()` even if all guards are disabled, so
    /// flipping them on later applies the throttle from "now".
    mapping(address => uint256) public lastRebalance;

    /// @notice If true, the vault skips translation / width checks entirely
    /// (interval still applies). Useful for vaults that swing widely by design.
    mapping(address => bool) public rebalanceExempt;

    // ─────────────────────────────────────────────────────────────────────
    // EVENTS
    // ─────────────────────────────────────────────────────────────────────

    event RebalancerSet(address indexed vault, address indexed previous, address indexed current);
    event AdvisorSet(address indexed vault, address indexed previous, address indexed current);
    event CircuitBreakerSet(address indexed vault, address indexed previous, address indexed current);

    event AdminTransferStarted(address indexed previousAdmin, address indexed newAdmin);
    event AdminTransferCancelled(address indexed previousPending);
    event AdminTransferred(address indexed previousAdmin, address indexed newAdmin);
    event OwnershipFixed();

    event VaultOwnershipProposed(address indexed vault, address indexed newOwner);
    event VaultOwnershipAccepted(address indexed vault);
    event VaultOwnershipProposalCancelled(address indexed vault, address indexed previousPending);

    event ERC20Rescued(address indexed token, address indexed recipient, uint256 amount);

    event RebalanceGuardConfigSet(
        address indexed vault,
        uint256 maxTranslation,
        uint256 maxWidth,
        uint256 minInterval,
        bool exempt
    );

    // ─────────────────────────────────────────────────────────────────────
    // MODIFIERS
    // ─────────────────────────────────────────────────────────────────────

    modifier onlyAdmin() {
        require(msg.sender == admin, "only admin");
        _;
    }

    /// @dev Per-vault keeper. NO admin fallback — keeper rotation requires
    /// admin to call setRebalancer first. Clean separation of duties.
    modifier onlyRebalancer(address vault) {
        require(msg.sender == rebalancers[vault], "only rebalancer");
        _;
    }

    modifier onlyAdvisor(address vault) {
        require(msg.sender == advisors[vault], "only advisor");
        _;
    }

    modifier onlyCircuitBreaker(address vault) {
        require(msg.sender == circuitBreakers[vault], "only circuitBreaker");
        _;
    }

    // ─────────────────────────────────────────────────────────────────────
    // CONSTRUCTION
    // ─────────────────────────────────────────────────────────────────────

    constructor(address _admin) {
        require(_admin != address(0), "admin zero");
        admin = _admin;
        emit AdminTransferred(address(0), _admin);
    }

    // ─────────────────────────────────────────────────────────────────────
    // ROUTINE OPS — rebalancer
    // ─────────────────────────────────────────────────────────────────────

    /// @notice Rebalance via the rebalancer. `_feeRecipient` is intentionally not a
    /// caller-supplied parameter (AUDIT FIX E-9): the Executor reads the current
    /// `Vault.feeRecipient` itself and passes it through, so a compromised rebalancer
    /// key cannot reroute the protocol cut. Admin controls `feeRecipient` via
    /// `setVaultFeeRecipient`.
    ///
    /// @dev Before delegating, applies the per-vault rebalance guard:
    ///       - min-interval throttle (always applies if non-zero)
    ///       - translation-delta cap (skipped if `rebalanceExempt[vault]` or
    ///         full-range or the vault has never been rebalanced)
    ///       - width-delta cap (same skip conditions)
    ///      Each cap is `0` by default = disabled, so existing tests / new
    ///      vaults pass through transparently until admin opts in.
    function rebalance(
        address vault,
        int24 _baseLower, int24 _baseUpper,
        int24 _limitLower, int24 _limitUpper,
        uint256[4] memory mintMins,
        uint256[4] memory burnMins
    ) external onlyRebalancer(vault) {
        _checkRebalanceGuard(vault, _baseLower, _baseUpper);
        lastRebalance[vault] = block.timestamp;

        address currentRecipient = _readFeeRecipient(vault);
        IVault(vault).rebalance(
            _baseLower, _baseUpper,
            _limitLower, _limitUpper,
            currentRecipient, mintMins, burnMins
        );
    }

    /// @dev Internal — applies the rebalance guard. Reverts on violation.
    function _checkRebalanceGuard(
        address vault,
        int24 _baseLower,
        int24 _baseUpper
    ) internal view {
        // Throttle (always — when non-zero).
        uint256 interval = minInterval[vault];
        if (interval > 0 && lastRebalance[vault] > 0) {
            require(
                block.timestamp >= lastRebalance[vault] + interval,
                "rebalance: too soon"
            );
        }

        // Translation + width checks. Skip on:
        //   - first rebalance from the empty (baseLower == baseUpper) state, OR
        //   - explicit per-vault exemption, OR
        //   - new range is full-range (you can always reset to safety).
        int24 lastLower = IVault(vault).baseLower();
        int24 lastUpper = IVault(vault).baseUpper();
        bool firstRebalance = (lastLower == lastUpper);
        if (firstRebalance || rebalanceExempt[vault] ||
            RebalanceGuard.isFullRange(_baseLower, _baseUpper)) {
            return;
        }

        uint256 maxT = maxTranslation[vault];
        if (maxT > 0) {
            require(
                RebalanceGuard.isWithinTranslation(maxT, lastLower, lastUpper, _baseLower, _baseUpper),
                "rebalance: translation"
            );
        }
        uint256 maxW = maxWidth[vault];
        if (maxW > 0) {
            require(
                RebalanceGuard.isWidthChangeWithin(maxW, lastLower, lastUpper, _baseLower, _baseUpper),
                "rebalance: width"
            );
        }
    }

    function _readFeeRecipient(address vault) internal view returns (address) {
        (bool ok, bytes memory r) = vault.staticcall(abi.encodeWithSignature("feeRecipient()"));
        require(ok && r.length >= 32, "feeRecipient read failed");
        return abi.decode(r, (address));
    }

    /// @notice AUDIT FIX (#1): the per-vault RebalanceGuard only constrains `rebalance()`,
    /// but the same `onlyRebalancer` role can `addLiquidity` / `pullPositionLiquidity`. Without
    /// a tick constraint, a compromised rebalancer could mint the vault's balance into an
    /// OFF-BOOK Uniswap range — one that is neither the base nor the limit position — which
    /// `Vault.getTotalAmounts()` and `Vault.withdraw()` do not account for, stranding funds and
    /// corrupting NAV-based share pricing despite the strictest guard being set.
    ///
    /// We close this by requiring the routine (rebalancer) add/pull to operate ONLY on the
    /// vault's current base or limit range. Both are NAV-visible and withdrawable, so the
    /// rebalancer can no longer relocate funds somewhere accounting can't see. The emergency
    /// `circuitBreaker` path (`emergencyPullPositionLiquidity`) is intentionally NOT constrained
    /// so any pre-existing off-book position remains recoverable.
    /// @dev `rebalance()` is unchanged — it sets the base/limit ticks itself and is gated by the
    /// existing RebalanceGuard; this constraint is purely on the two sibling functions.
    function _requireKnownRange(address vault, int24 tickLower, int24 tickUpper) internal view {
        bool isBase  = (tickLower == IVault(vault).baseLower()  && tickUpper == IVault(vault).baseUpper());
        bool isLimit = (tickLower == IVault(vault).limitLower() && tickUpper == IVault(vault).limitUpper());
        require(isBase || isLimit, "range not base/limit");
    }

    function addLiquidity(
        address vault,
        int24 tickLower, int24 tickUpper,
        uint256 amount0, uint256 amount1,
        uint256[2] memory mintMins
    ) external onlyRebalancer(vault) {
        _requireKnownRange(vault, tickLower, tickUpper);
        IVault(vault).addLiquidity(tickLower, tickUpper, amount0, amount1, mintMins);
    }

    function pullPositionLiquidity(
        address vault,
        int24 tickLower, int24 tickUpper,
        uint128 shares,
        uint256[2] memory burnMins
    ) external onlyRebalancer(vault) returns (uint256 a0, uint256 a1) {
        _requireKnownRange(vault, tickLower, tickUpper);
        (a0, a1) = IVault(vault).pullPositionLiquidity(tickLower, tickUpper, shares, burnMins);
    }

    // ─────────────────────────────────────────────────────────────────────
    // ROUTINE OPS — advisor
    // ─────────────────────────────────────────────────────────────────────

    function compound(address vault, uint256[4] memory mintMins)
        external onlyAdvisor(vault)
    {
        IVault(vault).compound(mintMins);
    }

    // ─────────────────────────────────────────────────────────────────────
    // EMERGENCY OPS — circuitBreaker
    // ─────────────────────────────────────────────────────────────────────

    /// @notice Emergency: stop new deposits by clearing the depositor.
    /// Existing withdrawals still work. Reversible by admin via setVaultDepositor.
    function emergencyClearDepositor(address vault) external onlyCircuitBreaker(vault) {
        IVault(vault).clearDepositor();
    }

    /// @notice Emergency: evacuate a position's liquidity back to the Vault balance.
    /// Reversible by a subsequent rebalance / addLiquidity.
    function emergencyPullPositionLiquidity(
        address vault,
        int24 tickLower, int24 tickUpper,
        uint128 shares,
        uint256[2] memory burnMins
    ) external onlyCircuitBreaker(vault) returns (uint256 a0, uint256 a1) {
        (a0, a1) = IVault(vault).pullPositionLiquidity(tickLower, tickUpper, shares, burnMins);
    }

    // ─────────────────────────────────────────────────────────────────────
    // VAULT ADMIN OPS — admin
    // ─────────────────────────────────────────────────────────────────────

    function setVaultDepositor(address vault, address newDepositor) external onlyAdmin {
        IVault(vault).setDepositor(newDepositor);
    }

    function clearVaultDepositor(address vault) external onlyAdmin {
        IVault(vault).clearDepositor();
    }

    function setVaultFeeDivisor(address vault, uint8 newDivisor) external onlyAdmin {
        IVault(vault).setFeeDivisor(newDivisor);
    }

    function setVaultFeeRecipient(address vault, address newRecipient) external onlyAdmin {
        IVault(vault).setFeeRecipient(newRecipient);
    }

    function toggleVaultAutoStake(address vault) external onlyAdmin {
        IVault(vault).toggleAutoStake();
    }

    /// @notice Two-step transfer of Vault ownership. Calls `proposeOwnership` on the
    /// Vault. The new owner must then call `acceptOwnership` directly on the Vault.
    /// @dev Reverts if `fixOwnership()` was previously called.
    /// @dev AUDIT FIX (Focus 3 P4a): if a prior pending owner exists, emit
    /// `VaultOwnershipProposalCancelled` before the new proposal lands so off-chain
    /// monitors that key on that event don't miss the implicit cancellation.
    function proposeVaultOwnership(address vault, address newOwner) external onlyAdmin {
        require(!ownerFixed, "ownership fixed");
        require(newOwner != address(0), "newOwner zero");
        address prior = IVault(vault).pendingOwner();
        if (prior != address(0) && prior != newOwner) {
            emit VaultOwnershipProposalCancelled(vault, prior);
        }
        IVault(vault).proposeOwnership(newOwner);
        emit VaultOwnershipProposed(vault, newOwner);
    }

    /// @notice Accept Vault ownership that was previously proposed to this Executor.
    /// Used during initial setup: deployer proposes ownership to executor → admin
    /// calls executor.acceptVaultOwnership(vault) → Vault.owner becomes the Executor.
    function acceptVaultOwnership(address vault) external onlyAdmin {
        IVault(vault).acceptOwnership();
        emit VaultOwnershipAccepted(vault);
    }

    /// @notice AUDIT FIX E-8: cancel an in-flight outbound Vault-ownership proposal.
    /// The Vault's proposeOwnership requires a non-zero target, so we cancel by
    /// proposing this Executor itself as the new owner — which effectively no-ops
    /// (Executor is already the owner). Any prior pendingOwner is overwritten and
    /// can no longer call Vault.acceptOwnership().
    /// @dev Works even after `fixOwnership()` because this is a *cancellation*, not a
    /// fresh proposal. Admin-only.
    function cancelVaultOwnershipProposal(address vault) external onlyAdmin {
        address prior = IVault(vault).pendingOwner();
        require(prior != address(0), "no pending");
        IVault(vault).proposeOwnership(address(this));
        emit VaultOwnershipProposalCancelled(vault, prior);
    }

    /// @notice Permanently disable Vault ownership transfers initiated by this Executor.
    /// One-way. After this, `proposeVaultOwnership` always reverts.
    /// @dev FIXED from the original Admin-style contract — its `fixOwnership` set the flag to `false`,
    /// leaving the require check inert. We set to `true` so the lock actually engages.
    function fixOwnership() external onlyAdmin {
        require(!ownerFixed, "already fixed");
        ownerFixed = true;
        emit OwnershipFixed();
    }

    // ─────────────────────────────────────────────────────────────────────
    // ROLE MANAGEMENT — admin
    // ─────────────────────────────────────────────────────────────────────

    function setRebalancer(address vault, address newRebalancer) external onlyAdmin {
        address prev = rebalancers[vault];
        rebalancers[vault] = newRebalancer;
        emit RebalancerSet(vault, prev, newRebalancer);
    }

    function setAdvisor(address vault, address newAdvisor) external onlyAdmin {
        address prev = advisors[vault];
        advisors[vault] = newAdvisor;
        emit AdvisorSet(vault, prev, newAdvisor);
    }

    function setCircuitBreaker(address vault, address newBreaker) external onlyAdmin {
        address prev = circuitBreakers[vault];
        circuitBreakers[vault] = newBreaker;
        emit CircuitBreakerSet(vault, prev, newBreaker);
    }

    // ─────────────────────────────────────────────────────────────────────
    // REBALANCE GUARD — admin-only per-vault config
    // ─────────────────────────────────────────────────────────────────────

    /// @notice Set the full per-vault rebalance guard config in one call.
    /// @param vault Vault address.
    /// @param _maxTranslation Max midpoint drift in ticks; `0` disables the check.
    /// @param _maxWidth Max width-change in ticks; `0` disables the check.
    /// @param _minInterval Min seconds between rebalances; `0` disables.
    /// @param _exempt If true, skip translation + width checks (interval still applies).
    /// @dev AUDIT FIX (Focus 5 #8): translation and width caps must be set as a pair
    /// (either both zero or both non-zero). Either alone is misleading partial
    /// protection — see SECURITY.md Threat 11.
    function setRebalanceGuard(
        address vault,
        uint256 _maxTranslation,
        uint256 _maxWidth,
        uint256 _minInterval,
        bool _exempt
    ) external onlyAdmin {
        require(
            (_maxTranslation == 0) == (_maxWidth == 0),
            "translation and width must be paired"
        );
        maxTranslation[vault] = _maxTranslation;
        maxWidth[vault]       = _maxWidth;
        minInterval[vault]    = _minInterval;
        rebalanceExempt[vault] = _exempt;
        emit RebalanceGuardConfigSet(vault, _maxTranslation, _maxWidth, _minInterval, _exempt);
    }

    /// @notice Convenience setter — update only `maxTranslation`. The other fields stay.
    /// @dev AUDIT FIX (Focus 5 #8, R2-B): translation-cap alone is misleading — a keeper can
    /// collapse the range width while keeping the midpoint stable, passing the cap. The
    /// invariant `(maxTranslation == 0) == (maxWidth == 0)` must hold at all times:
    ///   - Enable (v > 0): requires width cap already enabled, OR use `setRebalanceGuard`.
    ///   - Disable (v == 0): requires width cap already disabled, OR use `setRebalanceGuard`.
    /// To go from (T, W) -> (0, 0) atomically, call `setRebalanceGuard(vault, 0, 0, ...)`.
    function setMaxTranslation(address vault, uint256 v) external onlyAdmin {
        if (v == 0) require(maxWidth[vault] == 0, "disable width first");
        else        require(maxWidth[vault] > 0,  "set maxWidth first");
        maxTranslation[vault] = v;
        emit RebalanceGuardConfigSet(vault, v, maxWidth[vault], minInterval[vault], rebalanceExempt[vault]);
    }

    /// @notice Convenience setter — update only `maxWidth`. The other fields stay.
    /// @dev AUDIT FIX (Focus 5 #8, R2-B): same pairing invariant as `setMaxTranslation`.
    function setMaxWidth(address vault, uint256 v) external onlyAdmin {
        if (v == 0) require(maxTranslation[vault] == 0, "disable translation first");
        else        require(maxTranslation[vault] > 0,  "set maxTranslation first");
        maxWidth[vault] = v;
        emit RebalanceGuardConfigSet(vault, maxTranslation[vault], v, minInterval[vault], rebalanceExempt[vault]);
    }

    function setMinInterval(address vault, uint256 v) external onlyAdmin {
        minInterval[vault] = v;
        emit RebalanceGuardConfigSet(vault, maxTranslation[vault], maxWidth[vault], v, rebalanceExempt[vault]);
    }

    function setRebalanceExempt(address vault, bool v) external onlyAdmin {
        rebalanceExempt[vault] = v;
        emit RebalanceGuardConfigSet(vault, maxTranslation[vault], maxWidth[vault], minInterval[vault], v);
    }

    // ─────────────────────────────────────────────────────────────────────
    // ADMIN TRANSITION — two-step
    // ─────────────────────────────────────────────────────────────────────

    function proposeAdmin(address newAdmin) external onlyAdmin {
        require(newAdmin != address(0), "newAdmin zero");
        pendingAdmin = newAdmin;
        emit AdminTransferStarted(admin, newAdmin);
    }

    function acceptAdmin() external {
        require(msg.sender == pendingAdmin, "not pending");
        address previousAdmin = admin;
        admin = pendingAdmin;
        pendingAdmin = address(0);
        emit AdminTransferred(previousAdmin, admin);
    }

    /// @notice Legacy single-step admin transfer, retained for compat. Prefer
    /// proposeAdmin + acceptAdmin.
    /// @dev AUDIT FIX E-4: emit `AdminTransferCancelled` when a pending transfer is
    /// silently overwritten by this path, so monitoring on `AdminTransferStarted` /
    /// `AdminTransferCancelled` can detect the bypass.
    function transferAdmin(address newAdmin) external onlyAdmin {
        require(newAdmin != address(0), "newAdmin zero");
        address previousAdmin = admin;
        address previousPending = pendingAdmin;
        admin = newAdmin;
        pendingAdmin = address(0);
        if (previousPending != address(0)) {
            emit AdminTransferCancelled(previousPending);
        }
        emit AdminTransferred(previousAdmin, newAdmin);
    }

    // ─────────────────────────────────────────────────────────────────────
    // RESCUE — admin
    // ─────────────────────────────────────────────────────────────────────

    /// @notice Rescue tokens accidentally sent to this Executor contract.
    /// @dev The Executor is a relayer — it should never hold tokens during normal
    /// operation. If tokens land here (e.g. someone transfers by mistake) admin can
    /// sweep them. Cannot touch tokens inside any managed Vault.
    function rescueERC20(IERC20 token, address recipient) external onlyAdmin {
        require(recipient != address(0), "recipient zero");
        uint256 bal = token.balanceOf(address(this));
        require(bal > 0, "nothing to rescue");
        require(token.transfer(recipient, bal), "transfer failed");
        emit ERC20Rescued(address(token), recipient, bal);
    }
}

contracts/lib/RebalanceGuard.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;

/// @title RebalanceGuard
/// @notice Pure-math validators for vault rebalance requests. Derived from the
///         upstream `RebalanceProxy.sol` checks, simplified, bug-fixed, and
///         hoisted into a library so the caller (typically `VaultExecutor`) can
///         apply them without inheriting any state.
///
/// Why a library instead of a contract:
///   - These checks are stateless and reusable across vaults.
///   - Per-vault configuration (max translation, max width, min interval,
///     exemption, last-rebalance timestamp) lives on the caller, where it
///     belongs with the rest of the per-vault keeper config.
///   - No upgrade-path drama: the lib is internal-call only (no DELEGATECALL).
///
/// Differences from upstream `RebalanceProxy`:
///   - **Midpoint formula simplified.** Upstream had a special branch for the
///     case `lower < 0 < upper` that algebraically reduces to the same value
///     as the general formula. Removed.
///   - **Full-range threshold kept at upstream's `±886800`** because that bound
///     is divisible by 10/60/200 (the standard Uniswap V3 tickSpacings) — the
///     true Uniswap V3 max of `±887272` is not aligned to any common spacing
///     and would reject legitimate full-range rebalances at common pools.
///   - **Symmetric full-range required.** A new `FULL_RANGE_ASYMMETRY_LIMIT`
///     check rejects asymmetric "full-range" pairs like `(-887220, 886800)`
///     that previously bypassed translation caps with a 210-tick midpoint
///     shift (Focus 5 #9 / R2-B fix).
///   - **Zero means disabled.** Per-vault max-translation / max-width /
///     min-interval default to `0`, which the caller MUST interpret as "no
///     limit applies." This makes the guard opt-in per vault rather than
///     surprising operators with strict defaults.
library RebalanceGuard {

    // Threshold for "effectively full-range." Uniswap V3's absolute max tick is
    // ±887272, but in practice operators pass tick-spacing-aligned versions —
    // ±887270 (spacing 10), ±887220 (spacing 60), ±887200 (spacing 200). At
    // spacing 200 the truly-as-wide-as-possible position is ±887200, so a
    // threshold above that would reject legitimate "full-range" rebalances.
    //
    // 886800 is divisible by 10/60/200 — the standard Uniswap V3 spacings —
    // and is the same threshold the upstream RebalanceProxy used. A vault
    // crossing this bound on both sides has effectively covered the full
    // price space; further translation/width caps would be meaningless.
    int24 internal constant FULL_RANGE_LOWER = -886800;
    int24 internal constant FULL_RANGE_UPPER =  886800;

    // Maximum allowed asymmetry for a "full-range" rebalance (in ticks). An
    // asymmetric full-range (e.g. `(-887220, 886800)` with midpoint −210) was
    // exploited by Focus 5 finding #9 to bypass arbitrarily tight translation
    // caps. We require `|lower + upper| <= FULL_RANGE_ASYMMETRY_LIMIT` so the
    // bypass only applies to ranges that are truly symmetric within typical
    // tick-spacing alignment slack. 200 is the max common tickSpacing (1% pool),
    // so any aligned full-range pair lands within ±200 of zero midpoint.
    int24 internal constant FULL_RANGE_ASYMMETRY_LIMIT = 200;

    /// @notice Returns true if `(lowerTick, upperTick)` covers the full tick range
    ///         AND is approximately symmetric around zero.
    /// @dev The symmetry requirement (`|lower + upper| <= FULL_RANGE_ASYMMETRY_LIMIT`)
    ///      blocks the Focus-5-#9 exploit where an asymmetric range like
    ///      `(-887220, 886800)` qualified as "full" while shifting the midpoint
    ///      by 210 ticks per call. With the symmetry cap, any legitimate
    ///      tickSpacing-aligned full-range still passes (max midpoint magnitude is
    ///      bounded by half the largest tickSpacing = 100).
    function isFullRange(int24 lowerTick, int24 upperTick) internal pure returns (bool) {
        if (lowerTick > FULL_RANGE_LOWER || upperTick < FULL_RANGE_UPPER) return false;
        int256 sum = int256(lowerTick) + int256(upperTick);
        int256 absSum = sum >= 0 ? sum : -sum;
        return absSum <= int256(FULL_RANGE_ASYMMETRY_LIMIT);
    }

    /// @notice |midpoint(new) − midpoint(old)| ≤ maxTranslation.
    /// @dev `maxTranslation == 0` means the caller MUST treat this check as
    ///      disabled. We still compute and return a truthful answer here so the
    ///      library remains pure; the caller does the disabled-check.
    /// @param maxTranslation Maximum absolute drift in ticks.
    /// @param lastLowerTick Existing base-position lower tick.
    /// @param lastUpperTick Existing base-position upper tick.
    /// @param newLowerTick Proposed base-position lower tick.
    /// @param newUpperTick Proposed base-position upper tick.
    function isWithinTranslation(
        uint256 maxTranslation,
        int24 lastLowerTick,
        int24 lastUpperTick,
        int24 newLowerTick,
        int24 newUpperTick
    ) internal pure returns (bool) {
        int256 lastMid = (int256(lastLowerTick) + int256(lastUpperTick)) / 2;
        int256 newMid  = (int256(newLowerTick)  + int256(newUpperTick))  / 2;
        int256 diff    = newMid > lastMid ? newMid - lastMid : lastMid - newMid;
        return diff <= int256(maxTranslation);
    }

    /// @notice |width(new) − width(old)| ≤ maxWidth.
    /// @dev `maxWidth == 0` means the caller MUST treat this check as disabled.
    function isWidthChangeWithin(
        uint256 maxWidth,
        int24 lastLowerTick,
        int24 lastUpperTick,
        int24 newLowerTick,
        int24 newUpperTick
    ) internal pure returns (bool) {
        int256 oldWidth = int256(lastUpperTick) - int256(lastLowerTick);
        int256 newWidth = int256(newUpperTick)  - int256(newLowerTick);
        int256 diff     = newWidth > oldWidth ? newWidth - oldWidth : oldWidth - newWidth;
        return diff <= int256(maxWidth);
    }
}

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.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);
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 800,
    "enabled": true
  },
  "evmVersion": "istanbul",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@uniswap/v3-core/=lib/v3-core/",
    "@uniswap/v3-periphery/=lib/v3-periphery/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
    "v3-core/=lib/v3-core/",
    "v3-periphery/=lib/v3-periphery/contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.