Skip to content
Verified contractPartialBUSL-1.1

AutoRangeVaultV1

Address0xcc8364c9a1d92296deabe5b6f1925a84de407572
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 1 runs
EVM version
cancun
Via IR
yes
License
BUSL-1.1
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,965,859
Creation transaction
0x646773b085…da2c0a5045

24 files

src/official/AutoRangeVaultV1.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {INonfungiblePositionManager} from "../interfaces/INonfungiblePositionManager.sol";
import {ISwapRouter02} from "../interfaces/ISwapRouter02.sol";
import {IPlatformConfig} from "../interfaces/IPlatformConfig.sol";
import {IAggregatorV3} from "../interfaces/IAggregatorV3.sol";

/// @title AutoRangeVaultV1
/// @notice Non-custodial Uniswap V3 concentrated-liquidity vault. The owner
/// deposits/withdraws/configures; the operator (or any wallet in the
/// platform's own operator pool) may only rebalance within the guardrails
/// the owner set — it can never move funds to an arbitrary address.
///
/// Key mechanisms:
///   - `exitTopRecenterMarginBps` — a dedicated recenter margin for the
///     out-of-range-top case, decoupled from `recenterMarginBps` (used by
///     every other recenter case: periodic, out-of-range-bottom,
///     ownerRebalance, operatorForceRebalance). Off-chain-consumed only,
///     stored purely as an owner-configurable knob for the keeper to read.
///     Set via configureTarget()'s 11th parameter, emitted as
///     TargetConfigured's 11th field.
///   - `isOperator` — a wallet-pool redundancy layer, additive on top of the
///     single `operator` slot (unchanged): every wallet in the platform's
///     own operator pool, seeded once from AutoRangePlatformConfigV1's
///     `operatorPool()` at initialize() time, becomes a valid operator for
///     this vault, so it's never stuck just because one assigned wallet is
///     temporarily out of gas or rate-limited. `setOperatorStatus()`
///     (onlyOwner) lets the owner adjust the set later. `setPaused()`
///     remains the one real emergency kill switch, blocking every
///     `onlyOperator` function regardless of how many wallets are
///     authorized.
///
/// Hard ceiling/floor: if the volatile asset's price crosses an owner-
/// configured absolute bound, the position is closed, optionally converted
/// to the stable asset, and the vault auto-pauses — recoverable at any time
/// via withdraw()/withdrawAll()/emergencyWithdrawPosition()/
/// rescuePosition(), none of which are ever gated on `paused`.
///
/// Known tradeoff, documented explicitly: `isOperator` widens the blast
/// radius of a single compromised operator wallet from "one vault" to
/// "every vault that had that wallet in its own operator pool at creation
/// time" (the mapping is seeded once, never re-synced — removing a wallet
/// from the platform-wide pool later does not retroactively revoke it from
/// vaults that already seeded it). Mitigated, not eliminated: (a)
/// `setPaused(true)`, owner-only, per-vault, instantly blocks ALL operator
/// access on that one vault; (b) every withdrawal path is always available
/// to the owner regardless of pause state; (c) none of the `onlyOperator`
/// functions (rebalance, operatorForceRebalance, reinjectIntoPosition)
/// accept an arbitrary recipient — every fund movement stays inside the
/// vault's own position/ledgers, the only external transfers are the fixed
/// operator/treasury performance-fee and creation-fee cuts.
contract AutoRangeVaultV1 is Initializable, ReentrancyGuardUpgradeable, IERC721Receiver {
    using SafeERC20 for IERC20;

    // ---------------------------------------------------------------------
    // Errors
    // ---------------------------------------------------------------------

    error NotOwner();
    error NotOperator();
    error Paused();
    error AlreadyInitializedPosition();
    error NoPosition();
    error TargetNotConfigured();
    error RangeTooFarFromMarket();
    error TooSoonToRebalance();
    error RebalanceLimitReached();
    error InsufficientReserve();
    error InvalidSwapInstruction();
    error DepositExceedsPlatformCap();
    error ZeroAddress();
    error NotPositionManager();
    error VaultClosed();
    error VaultNotEmpty();
    error ReinjectionExceedsCap();
    error InvalidShareBps();
    error AutoCompoundNotEnabled();
    /// @notice The "invertible" bucket can only ever be funded before the
    /// first position exists. Use increasePosition()/increasePositionWithToken()
    /// to add capital to an already-open position instead.
    error InvestableAfterPositionExists();
    /// @notice dustAmount0/dustAmount1 in withdraw() exceeded what's actually
    /// sitting unaccounted-for in the vault's raw balance.
    error InvalidDustAmount();
    /// investableAmount + gasReserveAmount exceeds the real value (stable
    /// received + volatile received, valued at spot price) this call
    /// actually brought into the vault.
    error DeclaredExceedsRealBalance();
    /// hardCeilingTick once both are enabled (direction-aware — see
    /// _hardStopOrderValid()).
    error InvalidHardStopOrder();
    /// token, same as every pair this project has today; the gas-oracle
    /// conversion's fixed /1e20 divisor assumes it (see _ethUsdFromOracle).
    error UnsupportedStableDecimals();

    // ---------------------------------------------------------------------
    // Immutable-ish config (set once in initialize())
    // ---------------------------------------------------------------------

    address public owner;
    address public platformConfig;

    IUniswapV3Pool public pool;
    address public token0; // Uniswap's real token0 — the LOWER of the two addresses, not necessarily the stablecoin
    address public token1; // Uniswap's real token1
    bool public stableIsToken0; // true on Celo (USDT<WETH), false on Arbitrum (WETH<USDC)
    uint24 public feeTier;

    INonfungiblePositionManager public positionManager;
    ISwapRouter02 public swapRouter;
    /// reimbursement — deliberately NOT the vault's own pool (see
    /// _ethUsdFromOracle's own docstring for why that was wrong for any
    /// non-WETH volatile asset). Set once here, same immutable-at-creation
    /// pattern as positionManager/swapRouter — no setter, same precedent
    /// already accepted for platformConfig ("vaults created keep the config
    /// they were born with, forever").
    address public gasPriceOracle;

    // ---------------------------------------------------------------------
    // Operator
    // ---------------------------------------------------------------------

    address public operator;

    /// above. Seeded once from AutoRangePlatformConfigV1.operatorPool() at
    /// initialize() time (see that function), adjustable afterward via
    /// setOperatorStatus(). See this contract's own top docstring for the
    /// full rationale.
    mapping(address => bool) public isOperator;

    // ---------------------------------------------------------------------
    // Ledgers — all three are carved out of the same stable-leg balance but
    // must never be spent on each other's behalf.
    // ---------------------------------------------------------------------

    uint256 public investableUsdt; // capital not yet deployed into a position
    uint256 public reserveBalance; // capital available for the keeper to reinject into a position, over time
    // Dedicated, owner-funded budget for rebalance()'s keeper gas
    // reimbursement — deliberately separate from investableUsdt.
    uint256 public gasReserveBalance;

    /// @notice `investableUsdt` mixes two things that must be treated
    /// differently for B1 (cumulative investment) accounting off-chain:
    /// genuinely new capital from a LATER deposit()/depositToken() call (made
    /// after a position already exists) that hasn't been folded into the
    /// position yet, vs. leftover stable-side residue from a prior mint that
    /// was already counted once. `uncountedInvestable` tracks ONLY the
    /// former. A LATER deposit()/depositToken() call with investableAmount > 0
    /// always reverts (see InvestableAfterPositionExists), so this counter
    /// can now only ever grow via increasePosition()/increasePositionWithToken().
    ///
    /// Every function that reassigns investableUsdt from a freshly MEASURED
    /// balance (sweepIdleDust, rebalance, ownerRebalance, _reinjectFees,
    /// increasePosition, increasePositionWithToken, reinjectIntoPosition)
    /// clamps uncountedInvestable to never exceed it afterward — this is the
    uint256 public uncountedInvestable;

    /// fee-eligible dollar ever contributed to this vault: investableAmount
    /// at deposit()/depositToken(), usdtAmount AND the volatile leg's USD
    /// value at increasePosition()/increasePositionWithToken(), and
    /// reinjectAmount at _rebalanceCore's reinject step. Raw 6-decimal
    /// stable units. Deliberately NEVER decremented by withdraw() — a gross
    /// lifetime-inflow counter, not a live balance — so an owner can't cycle
    /// withdraw()+redeposit() to keep re-qualifying a large vault for
    /// bracket-1 (flat-fee-only) treatment. Written ONLY by
    /// _creationFeeFor(), which is the sole place that reads/advances it.
    uint256 public cumulativeFeeableUsd;

    // ---------------------------------------------------------------------
    // Interés compuesto — todos off-chain-only knobs salvo autoCompoundFees.
    // ---------------------------------------------------------------------

    bool public autoCompoundFees;
    /// @notice Only meaningful when autoCompoundFees == false — left settable
    /// regardless (not gated on autoCompoundFees being off) so the owner can
    /// pre-arm it before flipping the other switch, one fewer tx. Applies
    /// automatically, without any per-call choice, whenever a fee gets paid
    /// DIRECTLY to the owner: collectFees()'s non-compounding branch, and
    /// rebalance()/ownerRebalance()'s non-compounding branch — needed as a
    /// persistent on-chain flag specifically because rebalance() is
    /// keeper-triggered, not owner-triggered, so the keeper has no way to
    /// receive a per-call choice from the owner at the moment it runs.
    bool public payoutFeesInStableOnly;
    uint256 public feeClaimThresholdBps;
    uint256 public feeClaimIntervalSeconds;
    uint256 public lastFeeClaimTimestamp;

    // ---------------------------------------------------------------------
    // Hard ceiling — absolute price stop for the volatile asset
    // ---------------------------------------------------------------------

    /// @notice A separate bool instead of a sentinel tick value (e.g.
    /// type(int24).max) — avoids any ambiguity over which raw tick value
    /// means "disabled", and matches this contract's own established pattern
    /// (autoCompoundFees, payoutFeesInStableOnly) of a dedicated enabled flag.
    bool public hardCeilingEnabled;
    /// @notice Stored as a tick (Uniswap's native on-chain unit), same as
    /// targetTickLower/targetTickUpper — the frontend already converts a
    /// human price input to a tick for every other range field, same pattern
    /// here. IMPORTANT: a higher tick does NOT always mean a higher price —
    /// it depends on stableIsToken0 (documented gotcha in this exact
    /// direction unconditionally). See _hardStopTriggered() below for the
    /// direction-aware comparison — never compare hardCeilingTick to the
    /// current tick directly anywhere else.
    int24 public hardCeilingTick;

    // ---------------------------------------------------------------------
    // Hard floor — absolute price stop, mirrors hard ceiling
    // ---------------------------------------------------------------------

    bool public hardFloorEnabled;
    /// @notice Same direction gotcha as hardCeilingTick, opposite comparison —
    /// see _hardStopTriggered() below, never compare this tick directly anywhere else.
    int24 public hardFloorTick;
    /// @notice false (default) = exit with whatever composition results
    /// naturally, no forced swap — avoids selling into a panic. true = real
    /// stop-loss, converts 100% to stable via the same _convertPayoutToStable
    /// the ceiling always uses.
    bool public hardFloorConvertToStable;

    // ---------------------------------------------------------------------
    // B1 seed, on-chain declared "capital to recover"
    // ---------------------------------------------------------------------

    /// @notice Owner-declared B1 (raw stable units, same format as
    /// investableUsdt) for a vault created to migrate a devalued position's
    /// capital from elsewhere. Purely informational to this contract — read
    /// by the keeper as the B1 it hands uni-lab.xyz for this vault's first
    /// rebalance, exactly like a real B1 would behave from then on (grows/
    /// shrinks with real deposits/withdrawals same as any other vault — this
    /// field is only ever the STARTING point, off-chain B1 accounting still
    /// walks the normal event history layered on top of it).
    uint256 public b1SeedRaw;

    // ---------------------------------------------------------------------
    // Target config — owner-set, what the agent should build/maintain
    // ---------------------------------------------------------------------

    bool public targetConfigured;
    int24 public targetTickLower;
    int24 public targetTickUpper;
    uint256 public maxRebalances;
    uint256 public reinjectionAmount;
    uint256 public periodicRebalanceInterval;
    uint256 public recenterMarginBps;
    uint256 public exitTopCeilingMarginBps;
    /// out-of-range-top case, decoupled from recenterMarginBps above (which
    /// every OTHER recenter case keeps using). Off-chain-only, read by the
    /// keeper's runRebalanceExitTop(), never on-chain. See this contract's
    /// own top docstring.
    uint256 public exitTopRecenterMarginBps;

    // ---------------------------------------------------------------------
    // Risk params — owner-set bounds the operator must stay within
    // ---------------------------------------------------------------------

    uint256 public maxSlippageBps;
    uint256 public minRebalanceInterval;
    uint256 public maxRangeDeviationBps;

    // ---------------------------------------------------------------------
    // Runtime state
    // ---------------------------------------------------------------------

    uint256 public positionTokenId;
    uint256 public rebalanceCount;
    uint256 public lastRebalanceTimestamp;
    // operatorForceRebalance()'s own dedicated bookkeeping — deliberately
    // separate from rebalanceCount/lastRebalanceTimestamp above, see this
    // contract's own classdoc for why (never eats into the owner's
    // maxRebalances budget, never shares the owner's minRebalanceInterval
    // cooldown).
    uint256 public forceRebalanceCount;
    uint256 public lastForceRebalanceTimestamp;
    bool public paused;
    bool public closed;

    struct SwapInstruction {
        bool token0ToToken1;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint24 fee;
    }

    // ---------------------------------------------------------------------
    // Events
    // ---------------------------------------------------------------------

    /// @notice `positionAlreadyExists` is now ALWAYS false — kept in the
    /// event signature regardless for off-chain event-decoding compatibility
    event Deposited(uint256 investableAmount, uint256 reserveAmount, uint256 gasReserveAmount, bool positionAlreadyExists);
    event CreationFeeCharged(uint256 amount);
    event TargetConfigured(
        uint256 investmentAmountUsd,
        int24 targetTickLower,
        int24 targetTickUpper,
        uint256 maxRebalances,
        uint256 reinjectionAmount,
        uint256 periodicRebalanceInterval,
        uint256 recenterMarginBps,
        uint256 exitTopCeilingMarginBps,
        uint256 feeClaimThresholdBps,
        uint256 feeClaimIntervalSeconds,
        uint256 exitTopRecenterMarginBps
    );
    event OperatorStatusUpdated(address indexed operator, bool authorized);
    event PositionInitialized(uint256 tokenId, uint256 amount0, uint256 amount1);
    /// @notice `consumedUncounted` — how much of this cycle's fold-in was
    /// genuinely new, not-yet-counted investable capital (see
    /// uncountedInvestable's own docstring). Shared by rebalance() and
    /// ownerRebalance(). newTokenId == 0 signals the hard-ceiling/hard-floor
    /// exit path (position closed, no new position minted) — see
    /// HardCeilingTriggered/HardFloorTriggered below for the dedicated
    /// events that accompany it instead of the usual mint-related fields.
    event Rebalanced(
        uint256 indexed newTokenId, int24 tickLower, int24 tickUpper, uint256 reinjectedAmount, uint256 consumedUncounted
    );
    event KeeperGasReimbursed(uint256 amountUsd, uint256 gasUsed, uint256 effectiveGasPrice);
    event LpFeesPaidToOwner(uint256 amount0, uint256 amount1);
    event FeesCollected(uint256 amount0, uint256 amount1);
    event PerformanceFeeCollected(uint256 amount0, uint256 amount1);
    event Withdrawn(uint256 amount0, uint256 amount1, uint256 principalUsd);
    /// @notice `consumedUncounted`, same meaning as Rebalanced's — shared by
    /// increasePosition() and increasePositionWithToken(). `volatileFoldedUsd`
    /// volatile top-up actually got folded into the mint this same call (0
    /// when no volatile top-up was involved) — see this contract's own class
    /// docstring, item 3, for why this can never double-count pre-existing
    /// dust.
    event PositionIncreased(
        uint256 usdtAmount, uint256 used0, uint256 used1, uint256 consumedUncounted, uint256 volatileFoldedUsd
    );
    event ReinjectedIntoPosition(uint256 amount, uint256 used0, uint256 used1);
    /// @notice `consumedUncounted`, same meaning as Rebalanced's.
    event IdleDustSwept(uint256 used0, uint256 used1, uint256 consumedUncounted);
    event OperatorUpdated(address newOperator);
    event RiskParamsUpdated(uint256 maxSlippageBps, uint256 minRebalanceInterval, uint256 maxRangeDeviationBps);
    event PausedSet(bool isPaused);
    event EmergencyWithdraw(uint256 amount0, uint256 amount1, uint256 principalUsd);
    event Closed();
    event AutoCompoundFeesSet(bool enabled);
    event FeesReinjected(uint256 netFee0, uint256 netFee1, uint256 used0, uint256 used1, uint256 netFeeUsd);
    event PayoutFeesInStableOnlySet(bool enabled);
    event HardCeilingSet(bool enabled, int24 tick);
    /// @notice Emitted instead of Rebalanced when the hard ceiling triggers a
    /// close-and-park-in-stable exit. `stableAmount` is the vault's
    /// resulting investableUsdt right after (raw stable-decimal units) — the
    /// capital isn't paid out, it stays in the vault, retrievable via
    /// withdraw()/withdrawAll() same as any other idle investable balance.
    event HardCeilingTriggered(uint256 stableAmount);
    event HardFloorSet(bool enabled, int24 tick, bool convertToStable);
    /// @notice Emitted instead of Rebalanced when the hard floor triggers a
    /// close-and-pause exit. `stableAmount` mirrors HardCeilingTriggered's
    /// own field — the resulting investableUsdt right after (only reflects
    /// the STABLE leg; if hardFloorConvertToStable is false, any volatile leg
    /// sits as raw balance instead, retrievable via the dust bucket in
    /// withdraw()).
    event HardFloorTriggered(uint256 stableAmount);
    event B1SeedSet(uint256 seedRaw);
    event PositionRescued(uint256 tokenId);

    // ---------------------------------------------------------------------
    // Modifiers
    // ---------------------------------------------------------------------

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    modifier onlyOperator() {
        if (msg.sender != operator && !isOperator[msg.sender]) revert NotOperator();
        _;
    }

    modifier whenNotPaused() {
        if (paused) revert Paused();
        _;
    }

    modifier notClosed() {
        if (closed) revert VaultClosed();
        _;
    }

    constructor() {
        _disableInitializers();
    }

    /// @notice Called once by AutoRangeVaultFactoryV1 right after cloning.
    function initialize(
        address _owner,
        address _platformConfig,
        address _pool,
        address _token0,
        address _token1,
        bool _stableIsToken0,
        uint24 _feeTier,
        address _positionManager,
        address _swapRouter,
        address _gasPriceOracle
    ) external initializer {
        if (
            _owner == address(0) || _platformConfig == address(0) || _pool == address(0)
                || _positionManager == address(0) || _swapRouter == address(0) || _gasPriceOracle == address(0)
        ) {
            revert ZeroAddress();
        }
        __ReentrancyGuard_init();

        owner = _owner;
        platformConfig = _platformConfig;
        pool = IUniswapV3Pool(_pool);
        token0 = _token0;
        token1 = _token1;
        stableIsToken0 = _stableIsToken0;
        feeTier = _feeTier;
        positionManager = INonfungiblePositionManager(_positionManager);
        swapRouter = ISwapRouter02(_swapRouter);
        gasPriceOracle = _gasPriceOracle;

        // stable (see _ethUsdFromOracle's /1e20 divisor: wei[18d] ×
        // answer[8d] / 1e18[wei→ETH] × 1e6[USD→stable-6d] / 1e8[feed
        // decimals]) — every stable this project uses today (USDC, USDT0)
        // is 6 decimals. Reverting HERE, at vault creation (cheap, no funds
        // at risk yet) is far safer than a silent runtime mis-scale
        // discovered live in production, the way fix #6 itself was found.
        if (IERC20Metadata(_stableAddr()).decimals() != 6) revert UnsupportedStableDecimals();

        operator = IPlatformConfig(_platformConfig).defaultOperator();

        // contract's own top docstring and AutoRangePlatformConfigV1.operatorPool's
        // docstring). Read once, here, never re-synced later — a wallet
        // added to the pool AFTER this vault already exists only covers
        // vaults created from that point on, same "immutable clone" limit
        // every other per-vault-at-creation field in this project already
        // has. Bounded by the pool's own real size (a handful of keeper
        // wallets), never large enough to risk a gas-limit issue here.
        address[] memory pool = IPlatformConfig(_platformConfig).operatorPool();
        for (uint256 i = 0; i < pool.length; i++) {
            isOperator[pool[i]] = true;
        }

        IERC20(_token0).forceApprove(_positionManager, type(uint256).max);
        IERC20(_token1).forceApprove(_positionManager, type(uint256).max);
        IERC20(_token0).forceApprove(_swapRouter, type(uint256).max);
        IERC20(_token1).forceApprove(_swapRouter, type(uint256).max);
    }

    // ---------------------------------------------------------------------
    // Owner: capital + configuration
    // ---------------------------------------------------------------------

    /// @notice Reverts if investableAmount > 0 and a position already
    /// exists — the "invertible" bucket can only ever be funded once, before
    /// initPosition() has run. Use increasePosition() (or
    /// increasePositionWithToken()) afterward instead. reserveAmount/
    /// gasReserveAmount are unaffected — those buckets stay fundable anytime.
    function deposit(uint256 reserveAmount, uint256 investableAmount, uint256 gasReserveAmount)
        external
        onlyOwner
        notClosed
        nonReentrant
    {
        if (positionTokenId != 0 && investableAmount > 0) revert InvestableAfterPositionExists();

        uint256 total = reserveAmount + investableAmount + gasReserveAmount;
        _enforceDepositCap(total, true);

        // capital that's genuinely entering "capital under management" right
        // away. gasReserveAmount never charges (pure keeper-gas budget,
        // never becomes managed capital) and reserveAmount no longer charges
        // HERE either — it charges later, at the moment it's actually
        // reinjected into the position (see _rebalanceCore's reinject
        // block) — same principle B1 accounting already uses for the
        // reserve bucket (see CLAUDE.md's "B1/A1" section: reserve never
        // counts until it's genuinely folded in). _creationFeeFor is now
        uint256 creationFee = _creationFeeFor(investableAmount);
        IERC20(_stableAddr()).safeTransferFrom(msg.sender, address(this), total + creationFee);
        _payCreationFee(creationFee);

        _creditDepositLedgers(investableAmount, reserveAmount, gasReserveAmount);
    }

    /// @notice Depósito flexible, generalizado sobre _stableAddr()/_volatileAddr()
    /// en vez de asumir token0==stable. `tokenIn == _volatileAddr()`: swapIx
    /// vende el excedente o compra el faltante contra el rango objetivo, sin
    /// tocar la porción de volátil que ya calza. Cualquier otro token
    /// no-stable: se vende TODO al stable vía el router genérico.
    ///
    /// Vender el excedente PRODUCE stable nuevo — se acredita más abajo vía
    /// reserveAmount/investableAmount/gasReserveAmount, igual que un
    /// deposit() normal. Comprar el faltante, en cambio, GASTA investableUsdt
    /// ya acreditado (mismo capital ledgereado, no dinero nuevo) — hay que
    /// debitarlo explícitamente ANTES del swap, o el ledger terminaría
    /// sobreestimando el respaldo real en exactamente swapIx.amountIn (mismo
    /// tipo de bug de contabilidad que el resto del contrato evita en
    /// _reinjectFees/reinjectIntoPosition zerando investableUsdt primero).
    ///
    /// Same investableAmount-after-first-position restriction as deposit()
    /// above.
    function depositToken(
        address tokenIn,
        uint256 amountIn,
        SwapInstruction calldata swapIx,
        uint24 thirdPartyFee,
        uint256 thirdPartyAmountOutMinimum,
        uint256 reserveAmount,
        uint256 investableAmount,
        uint256 gasReserveAmount
    ) external onlyOwner notClosed nonReentrant {
        if (positionTokenId != 0 && investableAmount > 0) revert InvestableAfterPositionExists();

        // Checked BEFORE any transfer/swap runs (same order deposit() itself
        // uses) — a deposit that's certain to exceed the cap fails fast,
        // instead of spending gas on a transferFrom + swap it's just going to
        // unwind anyway. Doesn't depend on the swap's outcome either way:
        // reserveAmount/investableAmount/gasReserveAmount are caller-supplied,
        // independent of what tokenIn actually converts to.
        uint256 total = reserveAmount + investableAmount + gasReserveAmount;
        _enforceDepositCap(total, true);

        address stableAddr = _stableAddr();
        address volatileAddr = _volatileAddr();
        // snapshot BOTH legs before the transfer, so realValue below is
        // always measured from an actual balance delta, never trusted from
        // the caller-declared `amountIn`. Closes a fee-on-transfer/
        // deflationary-token gap (a token that delivers less than `amountIn`
        // would otherwise let the ledgers credit more than what really
        // arrived) — not exploitable against this project's real tokens
        // (USDC/USDT0/WETH/WBTC/LINK, none fee-on-transfer) and onlyOwner
        // regardless (self-only risk even if it were), but free to close
        // properly rather than leave as a documented assumption.
        uint256 stableBefore = IERC20(stableAddr).balanceOf(address(this));
        uint256 volatileBefore = IERC20(volatileAddr).balanceOf(address(this));

        if (amountIn > 0) IERC20(tokenIn).safeTransferFrom(msg.sender, address(this), amountIn);

        // per branch. Deliberately NOT a post-SWAP balance-delta measurement
        // for the volatile branch (an earlier version of this fix used one,
        // and had a real hole: in the "buying" branch below, the swap spends
        // PRE-EXISTING investableUsdt to buy MORE volatile — a post-swap
        // volatile-balance delta would count that bought amount as if it
        // were new value, letting an owner launder already-counted capital
        // through a self-swap to fabricate an arbitrarily large fake
        // Deposited event, defeating the entire point of this fix. Found and
        // fixed before deploy via manual audit, not caught by the original
        // test suite). Measuring the volatile delta right here — after the
        // transfer, but strictly BEFORE _executeSwap runs below — sidesteps
        // that hole while still using a real measurement instead of trusting
        // `amountIn` blindly.
        uint256 realValue =
            tokenIn == volatileAddr ? _nativeWeiToStableRaw(IERC20(volatileAddr).balanceOf(address(this)) - volatileBefore) : 0;

        if (tokenIn == volatileAddr) {
            bool sellingVolatile = _sellsVolatileForStable(swapIx);
            if (!sellingVolatile && swapIx.amountIn > 0) {
                investableUsdt -= swapIx.amountIn;
                // This debit spends already-ledgered investableUsdt without
                // distinguishing whether it draws from the counted or
                // uncounted portion — clamp defensively so
                // uncountedInvestable can never end up exceeding
                // investableUsdt (which would later underflow-revert in
                // withdraw()/withdrawAll()). Errs toward undercounting B1 in
                // this specific edge case, never toward a stuck vault.
                if (uncountedInvestable > investableUsdt) uncountedInvestable = investableUsdt;
            }
            _executeSwap(swapIx);
        } else if (tokenIn == stableAddr) {
            // Measured, not trusted — same fee-on-transfer hardening as the
            // volatile branch above. No swap runs in this branch, so the
            // delta is exact and safe (no laundering risk here either way).
            realValue = IERC20(stableAddr).balanceOf(address(this)) - stableBefore;
        } else if (amountIn > 0) {
            _swapThirdPartyToStable(tokenIn, amountIn, thirdPartyFee, thirdPartyAmountOutMinimum, stableAddr);
            // Real swap proceeds, genuinely new — no pre-existing capital is
            // ever touched in this branch, so a post-swap delta is safe here
            // (unlike the volatile-buying branch above).
            realValue = IERC20(stableAddr).balanceOf(address(this)) - stableBefore;
        }

        if (realValue < total) revert DeclaredExceedsRealBalance();

        // deducted from the vault's own resulting stable balance (post-swap)
        // rather than pulled extra — same convention the old flat fee used.
        _payCreationFee(_creationFeeFor(investableAmount));

        _creditDepositLedgers(investableAmount, reserveAmount, gasReserveAmount);
    }

    /// safeTransferFrom, measured before/after — never trusted, same Fix #1
    /// pattern depositToken() already uses). Both legs now pay the tiered
    /// creation fee off the SAME cumulativeFeeableUsd counter — see this
    /// contract's own class docstring, items 3-4.
    ///
    /// `usdtAmount == 0` with `volatileTopUpRaw > 0` is ACCEPTED (doesn't
    /// revert here) but only actually MINTS in the same tx when the
    /// position is CURRENTLY one-sided (100% volatile) at the pool's live
    /// price — for a normal two-sided position, Uniswap's own mint()
    /// reverts on the resulting hard-zero stable side, independent of
    /// anything this contract does (confirmed via a real Foundry test
    /// during development). The frontend is expected to require some
    /// minimal usdtAmount alongside any volatile top-up as a result (see
    /// VaultDetail.tsx's own handleIncreasePosition) — this is NOT a
    /// general-purpose "always works" pure-volatile path, unlike what an
    /// earlier draft of this docstring claimed. The volatile leg's fee is
    /// simply added to the same _payCreationFee(...) transfer
    /// as the stable leg's — same "pull from whatever real stable balance
    /// already exists" convention depositToken()/_rebalanceCore's
    /// reinjection fee already use, not a dedicated swap (an earlier design
    /// used a caller-sized feeSwapIx here; dropped before deploy purely for
    /// EIP-170 bytecode budget — see this file's own class docstring).
    /// Reverts safely (never a stuck vault, just a failed tx to retry with
    /// any small stable top-up) if a pure-volatile call's fee genuinely has
    /// no real stable balance to draw from anywhere in the vault.
    function increasePosition(
        SwapInstruction calldata swapIx,
        uint256 usdtAmount,
        uint256 volatileTopUpRaw,
        uint256 amount0Min,
        uint256 amount1Min
    ) external onlyOwner notClosed nonReentrant {
        if (positionTokenId == 0) revert NoPosition();
        if (usdtAmount == 0 && volatileTopUpRaw == 0) return;

        address volatileAddr = _volatileAddr();
        // increasePositionWithToken() below. Extending this to also value
        // the volatile leg was considered and dropped: real bytecode cost
        // (another _nativeWeiToStableRaw() call inlined here) for a soft
        // cap that a determined owner could already work around by simply
        // EIP-170 margin.
        uint256 preExistingInvestable = _beginIncreasePosition(usdtAmount);

        uint256 feeStable = _creationFeeFor(usdtAmount);
        if (usdtAmount > 0) {
            IERC20(_stableAddr()).safeTransferFrom(msg.sender, address(this), usdtAmount + feeStable);
        }

        uint256 volatileBefore = IERC20(volatileAddr).balanceOf(address(this));
        if (volatileTopUpRaw > 0) IERC20(volatileAddr).safeTransferFrom(msg.sender, address(this), volatileTopUpRaw);
        uint256 realVolatileTopUp = IERC20(volatileAddr).balanceOf(address(this)) - volatileBefore;

        _finishAndEmitIncrease(usdtAmount, realVolatileTopUp, preExistingInvestable, feeStable, swapIx, amount0Min, amount1Min);
    }

    /// @notice Same as increasePosition() but accepts any ERC20 — reuses
    /// depositToken()'s third-party-swap pattern (sell 100% of tokenIn into
    /// the vault's own stable), then feeds the result into the exact same
    /// increaseLiquidity() tail. `tokenIn == the vault's own stable` degrades
    /// to a no-swap passthrough, so this is a strict superset of
    /// increasePosition().
    ///
    /// depositToken() — left un-swapped (never routed through
    /// _swapThirdPartyToStable, whose EXACT router approval would otherwise
    /// get fully consumed and zero out this vault's persistent
    /// type(uint256).max approval forever, see this contract's own class
    /// docstring item 2). The balance sweep in _finishIncreasePosition
    /// folds it into the mint only when the position's live composition
    /// allows it (see that function's own docstring, and
    /// increasePosition()'s, for the same real one-sided-mint constraint —
    /// this is NOT guaranteed "regardless"). Also charges the volatile
    /// leg's tiered creation fee, same convention as increasePosition() —
    /// see that function's own docstring for why there's no dedicated swap
    /// for it.
    function increasePositionWithToken(
        address tokenIn,
        uint256 amountIn,
        uint24 thirdPartyFee,
        uint256 thirdPartyAmountOutMinimum,
        SwapInstruction calldata swapIx,
        uint256 usdtAmount,
        uint256 amount0Min,
        uint256 amount1Min
    ) external onlyOwner notClosed nonReentrant {
        if (positionTokenId == 0) revert NoPosition();
        if (usdtAmount == 0 && amountIn == 0) return;

        address stableAddr = _stableAddr();
        address volatileAddr = _volatileAddr();
        bool isVolatileTopUp = tokenIn == volatileAddr;

        // leg" scope as increasePosition() above (see that function's own
        // comment on why extending it to the volatile leg was dropped).
        uint256 preExistingInvestable = _beginIncreasePosition(usdtAmount);

        // already uses. Only meaningful when tokenIn is the vault's own
        // volatile; realVolatileTopUp stays 0 for any other tokenIn.
        uint256 volatileBefore = isVolatileTopUp ? IERC20(volatileAddr).balanceOf(address(this)) : 0;
        if (amountIn > 0) IERC20(tokenIn).safeTransferFrom(msg.sender, address(this), amountIn);
        uint256 realVolatileTopUp = isVolatileTopUp ? IERC20(volatileAddr).balanceOf(address(this)) - volatileBefore : 0;

        if (tokenIn != stableAddr && !isVolatileTopUp && amountIn > 0) {
            _swapThirdPartyToStable(tokenIn, amountIn, thirdPartyFee, thirdPartyAmountOutMinimum, stableAddr);
        }

        uint256 feeStable = _creationFeeFor(usdtAmount);

        _finishAndEmitIncrease(usdtAmount, realVolatileTopUp, preExistingInvestable, feeStable, swapIx, amount0Min, amount1Min);
    }

    /// @dev Shared tail of increasePosition()/increasePositionWithToken() —
    /// identical from fee-charging onward in both (only how tokenIn/
    /// volatileTopUpRaw got pulled and feeStable got computed/collected
    /// differs, before this point — see each caller's own body). Factored
    /// contract well over EIP-170's limit before this consolidation — see
    /// this file's own class docstring), no behavior change beyond what's
    /// already documented at each caller.
    ///
    /// `feeVolatile` is simply added to feeStable and paid in the same
    /// _payCreationFee(...) transfer — pulling from whatever real stable
    /// balance the vault already has, same convention depositToken()/
    /// _rebalanceCore's reinjection fee already use (see increasePosition()'s
    /// own docstring for why this isn't a dedicated swap).
    ///
    /// `min(realVolatileTopUp, volatile actually used in this mint)` bounds
    /// `volatileFoldedUsd` so pre-existing dust already sitting in the vault
    /// (fungible, indistinguishable from this call's own top-up by balance
    /// alone) can never be double-counted — see this contract's own class
    /// docstring, item 3.
    ///
    /// of) THIS call's own `realVolatileTopUp` for stable — the mechanism
    /// that lets a 100%-volatile top-up still mint on both legs even when
    /// the position is currently two-sided, since `_executeSwap` below runs
    /// on the vault's own token0/token1 via the persistent max approval
    /// from initialize(), never the exact-approval path Fix #1 protects —
    /// that sold slice's USD value is already charged via `feeStable`
    /// (`usdtAmount` is expected to reflect the swap's own proceeds, same
    /// caller-declared-cap convention `usdtAmount` already has everywhere
    /// else in this function). Charging `feeVolatile` on the FULL
    /// `realVolatileTopUp` on top of that would double-charge the sold
    /// closed here. `volatileSoldRaw` is bounded by `realVolatileTopUp`
    /// itself, so a sale that happens to also touch pre-existing volatile
    /// dust can only ever UNDER-charge the volatile leg's fee, never
    /// over-charge — same safe-direction convention as everywhere else in
    /// this contract.
    function _finishIncreasePosition(
        uint256 usdtAmount,
        uint256 realVolatileTopUp,
        uint256 preExistingInvestable,
        uint256 feeStable,
        SwapInstruction calldata swapIx,
        uint256 amount0Min,
        uint256 amount1Min
    ) internal returns (uint256 used0, uint256 used1, uint256 consumedUncounted, uint256 volatileFoldedUsd) {
        uint256 volatileSoldRaw =
            _sellsVolatileForStable(swapIx) ? (swapIx.amountIn < realVolatileTopUp ? swapIx.amountIn : realVolatileTopUp) : 0;
        uint256 feeVolatile = _creationFeeFor(_nativeWeiToStableRaw(realVolatileTopUp - volatileSoldRaw));

        // función que incremente algún contador también tenga la de
        // decrementarlo" — same standing instruction that caught a real
        // stable sitting in reserveBalance/gasReserveBalance/investableUsdt
        // — the realistic case for a 100%-volatile top-up, the exact
        // scenario this version's own fix exists for), swapIx is the ONLY
        // source of the stable needed to pay feeVolatile — paying first
        // means _payCreationFee's plain safeTransfer reverts with
        // "ERC20: transfer amount exceeds balance" on a genuinely
        // well-formed call, even though the swap right after would have
        // produced more than enough. Confirmed live with a dedicated test
        // before this fix (a real vault, 5 ETH contributed, 2.5 ETH sold,
        // reverted every time) and confirmed fixed after (same call
        // succeeds). Executing the swap first only ever ADDS to what's
        // available to pay from — never removes anything that was already
        // there — so this is strictly safer for every other caller too
        // (increasePosition()'s mixed top-up, any third-party-token sale),
        // not just the new pure-volatile case.
        _executeSwap(swapIx);
        _payCreationFee(feeStable + feeVolatile);

        (uint256 stableBal, uint256 volatileBal) = _measureAvailable(preExistingInvestable, 0);
        if (stableBal > usdtAmount) stableBal = usdtAmount;
        (uint256 amount0, uint256 amount1) = _toToken01(stableBal, volatileBal);

        // Increment by the MEASURED amount that actually arrived (stableBal),
        // never the caller-declared usdtAmount — see uncountedInvestable's
        // own docstring for why the distinction matters.
        uncountedInvestable += stableBal;

        (used0, used1) = _increaseLiquidity(amount0, amount1, amount0Min, amount1Min);

        consumedUncounted = _foldCapitalAndClamp(preExistingInvestable, stableBal, _stableOf(used0, used1));

        if (realVolatileTopUp > 0) {
            uint256 volatileUsedInMint = stableIsToken0 ? used1 : used0;
            uint256 volatileCountedRaw = realVolatileTopUp < volatileUsedInMint ? realVolatileTopUp : volatileUsedInMint;
            volatileFoldedUsd = _nativeWeiToStableRaw(volatileCountedRaw);
        }
    }

    function configureTarget(
        uint256 investmentAmountUsd,
        int24 _targetTickLower,
        int24 _targetTickUpper,
        uint256 _maxRebalances,
        uint256 _reinjectionAmount,
        uint256 _periodicRebalanceInterval,
        uint256 _recenterMarginBps,
        uint256 _exitTopCeilingMarginBps,
        uint256 _feeClaimThresholdBps,
        uint256 _feeClaimIntervalSeconds,
        uint256 _exitTopRecenterMarginBps
    ) external onlyOwner notClosed {
        targetTickLower = _targetTickLower;
        targetTickUpper = _targetTickUpper;
        maxRebalances = _maxRebalances;
        reinjectionAmount = _reinjectionAmount;
        periodicRebalanceInterval = _periodicRebalanceInterval;
        recenterMarginBps = _recenterMarginBps;
        exitTopCeilingMarginBps = _exitTopCeilingMarginBps;
        feeClaimThresholdBps = _feeClaimThresholdBps;
        feeClaimIntervalSeconds = _feeClaimIntervalSeconds;
        exitTopRecenterMarginBps = _exitTopRecenterMarginBps;
        targetConfigured = true;

        emit TargetConfigured(
            investmentAmountUsd,
            _targetTickLower,
            _targetTickUpper,
            _maxRebalances,
            _reinjectionAmount,
            _periodicRebalanceInterval,
            _recenterMarginBps,
            _exitTopCeilingMarginBps,
            _feeClaimThresholdBps,
            _feeClaimIntervalSeconds,
            _exitTopRecenterMarginBps
        );
    }

    /// never enforced on-chain (see this file's own class docstring, item 2,
    /// reverted before deploy).
    function setRiskParams(uint256 _maxSlippageBps, uint256 _minRebalanceInterval, uint256 _maxRangeDeviationBps)
        external
        onlyOwner
        notClosed
    {
        maxSlippageBps = _maxSlippageBps;
        minRebalanceInterval = _minRebalanceInterval;
        maxRangeDeviationBps = _maxRangeDeviationBps;
        emit RiskParamsUpdated(_maxSlippageBps, _minRebalanceInterval, _maxRangeDeviationBps);
    }

    /// silently lock out every onlyOperator entrypoint (all automated
    /// rebalancing) until the owner corrects it. Self-inflicted and
    /// recoverable either way, but pointless to allow.
    function setOperator(address newOperator) external onlyOwner {
        if (newOperator == address(0)) revert ZeroAddress();
        operator = newOperator;
        emit OperatorUpdated(newOperator);
    }

    /// on top of `operator` above (never touched by this — use
    /// setOperator() for that). One function instead of an add/remove pair
    /// (bytecode discipline, same reasoning as every other merged setter in
    /// this project — see setRiskParams above for the same shape). No
    /// zero-address guard: an accidental setOperatorStatus(address(0), true)
    /// is inert (address(0) can never be msg.sender), same reasoning as
    /// AutoRangePlatformConfigV1.setOperatorPool()'s own comment. pause() (below)
    /// remains the real all-operators kill switch regardless of how many
    /// addresses are currently authorized.
    function setOperatorStatus(address a, bool authorized) external onlyOwner {
        isOperator[a] = authorized;
        emit OperatorStatusUpdated(a, authorized);
    }

    /// bytecode-discipline reasoning as setOperatorStatus() above.
    function setPaused(bool _paused) external onlyOwner {
        paused = _paused;
        emit PausedSet(_paused);
    }

    function setAutoCompoundFees(bool enabled) external onlyOwner notClosed {
        autoCompoundFees = enabled;
        emit AutoCompoundFeesSet(enabled);
    }

    /// @notice Settable regardless of autoCompoundFees's current value (see
    /// this field's own docstring above for why) — only actually changes
    /// behavior while autoCompoundFees is false.
    function setPayoutFeesInStableOnly(bool enabled) external onlyOwner notClosed {
        payoutFeesInStableOnly = enabled;
        emit PayoutFeesInStableOnlySet(enabled);
    }

    /// setHardFloor() — a higher tick means a HIGHER price when
    /// stableIsToken0 is false, but a LOWER price when stableIsToken0 is true
    /// (same gotcha documented on hardCeilingTick/_hardStopTriggered() below
    /// — never compare these two ticks directly anywhere else). Returns true
    /// iff the ceiling's price is genuinely above the floor's price.
    function _hardStopOrderValid(int24 ceilingTick, int24 floorTick) internal view returns (bool) {
        return stableIsToken0 ? ceilingTick < floorTick : ceilingTick > floorTick;
    }

    /// @notice `tick` is only meaningful while `enabled` is true — see
    /// enabling a ceiling that would sit on the wrong side of an already-
    /// enabled floor (direction-aware, see _hardStopOrderValid()).
    /// @notice TEMP EXPERIMENT — merged setHardCeiling/setHardFloor to
    /// measure bytecode impact. `isCeiling=true` ignores convertToStable
    /// (ceiling always converts).
    function setHardStop(bool isCeiling, bool enabled, int24 tick, bool convertToStable) external onlyOwner notClosed {
        if (isCeiling) {
            if (enabled && hardFloorEnabled && !_hardStopOrderValid(tick, hardFloorTick)) revert InvalidHardStopOrder();
            hardCeilingEnabled = enabled;
            hardCeilingTick = tick;
            emit HardCeilingSet(enabled, tick);
        } else {
            if (enabled && hardCeilingEnabled && !_hardStopOrderValid(hardCeilingTick, tick)) revert InvalidHardStopOrder();
            hardFloorEnabled = enabled;
            hardFloorTick = tick;
            hardFloorConvertToStable = convertToStable;
            emit HardFloorSet(enabled, tick, convertToStable);
        }
    }

    /// @notice No gate beyond onlyOwner — purely informational, moves no
    /// funds, same risk profile as every other config setter here.
    function setB1Seed(uint256 seedRaw) external onlyOwner notClosed {
        b1SeedRaw = seedRaw;
        emit B1SeedSet(seedRaw);
    }

    /// emergencyWithdrawPosition() all share the same decreaseLiquidity()+
    /// collect() path against positionManager; if that path ever breaks for
    /// a reason this vault can't route around, the owner can still pull the
    /// raw NFT out directly and manage it from their own wallet. Deliberately
    /// skips ALL of this vault's internal accounting (no fee split, no ledger
    /// updates, no B1 event) — the tradeoff is losing the platform's
    /// performance fee on whatever's inside the position at that moment,
    /// accepted as the price of a genuine last resort. No whenNotPaused, same
    /// reasoning as withdraw()/withdrawAll() — the owner must always be able
    /// to retrieve their own assets regardless of pause state.
    ///
    /// Uses the RAW transferFrom, not safeTransferFrom — found during the
    /// pre-deploy audit: safeTransferFrom reverts if `owner` is a contract
    /// without onERC721Received (confirmed live against a real EIP-7702-
    /// delegated address on an Arbitrum fork during this same audit), which
    /// would make this "last resort" itself blockable for exactly the kind
    /// of wallet most likely to need it. Same "never depend on something
    /// that can fail for reasons outside the vault's control" principle
    /// emergencyWithdrawPosition() already uses for its own swap-free design.
    function rescuePosition() external onlyOwner nonReentrant {
        if (positionTokenId == 0) revert NoPosition();
        uint256 tokenId = positionTokenId;
        positionTokenId = 0;
        paused = true;
        positionManager.transferFrom(address(this), owner, tokenId);
        emit PositionRescued(tokenId);
    }

    // ---------------------------------------------------------------------
    // Operator: build the initial position
    // ---------------------------------------------------------------------

    function initPosition(SwapInstruction calldata swapIx, uint256 amount0Min, uint256 amount1Min)
        external
        onlyOperator
        whenNotPaused
        notClosed
        nonReentrant
        returns (uint256 tokenId)
    {
        uint256 gasStart = gasleft();

        if (positionTokenId != 0) revert AlreadyInitializedPosition();
        if (!targetConfigured) revert TargetNotConfigured();
        _checkRangeNearMarket(targetTickLower, targetTickUpper);

        uint256 investable = investableUsdt;
        investableUsdt = 0;

        _executeSwap(swapIx);

        (uint256 stableBal, uint256 volatileBal) = _measureAvailable(0, 0);
        if (stableBal > investable) {
            stableBal = investable;
        }
        (uint256 amount0, uint256 amount1) = _toToken01(stableBal, volatileBal);

        uint256 used0;
        uint256 used1;
        (tokenId, used0, used1) =
            _mintPosition(targetTickLower, targetTickUpper, amount0, amount1, amount0Min, amount1Min);

        positionTokenId = tokenId;
        lastRebalanceTimestamp = block.timestamp;

        (uint256 swept0, uint256 swept1) = _sweepDustIntoPosition(tokenId, amount0 - used0, amount1 - used1);

        investableUsdt = stableBal - _stableOf(used0, used1) - _stableOf(swept0, swept1);
        if (uncountedInvestable > investableUsdt) uncountedInvestable = investableUsdt;

        _reimburseKeeperGas(gasStart);

        emit PositionInitialized(tokenId, used0 + swept0, used1 + swept1);
    }

    // ---------------------------------------------------------------------
    // Operator: rebalance
    // ---------------------------------------------------------------------

    /// @notice `feePayoutSwapIx` is dual-purpose (mutually exclusive uses, so
    /// one param covers both): (a) normal case, non-compounding,
    /// payoutFeesInStableOnly enabled — sizes the fee's volatile-leg-to-stable
    /// conversion. (b) hard-ceiling/hard-floor-triggered case — sizes the
    /// FULL close-out-to-stable conversion (principal + fees combined)
    /// instead. `swapIx` (existing) is untouched — still only for the new
    /// mint's own balancing swap, never runs at all in the triggered case
    /// since no new mint happens there.
    function rebalance(
        int24 newTickLower,
        int24 newTickUpper,
        SwapInstruction calldata swapIx,
        SwapInstruction calldata feePayoutSwapIx,
        uint256 reinjectAmount,
        uint256 amount0Min,
        uint256 amount1Min
    ) external onlyOperator whenNotPaused notClosed nonReentrant returns (uint256 newTokenId) {
        uint256 gasStart = gasleft();

        if (positionTokenId == 0) revert NoPosition();
        if (rebalanceCount >= maxRebalances) revert RebalanceLimitReached();

        bool periodicDue = periodicRebalanceInterval != 0
            && block.timestamp >= lastRebalanceTimestamp + periodicRebalanceInterval;
        bool cooldownPassed = block.timestamp >= lastRebalanceTimestamp + minRebalanceInterval;
        if (!cooldownPassed) revert TooSoonToRebalance();
        if (!periodicDue && !_isOutOfRange()) revert TooSoonToRebalance();

        newTokenId =
            _rebalanceCore(newTickLower, newTickUpper, swapIx, feePayoutSwapIx, reinjectAmount, amount0Min, amount1Min);

        _reimburseKeeperGas(gasStart);
    }

    // ---------------------------------------------------------------------
    // Owner: force a rebalance on demand
    // ---------------------------------------------------------------------

    /// @notice Same effect as rebalance(), but the owner triggers it
    /// directly — no need to wait for the operator's next cycle to pick up
    /// a config change (recenterMarginBps, periodicRebalanceInterval, etc.).
    /// The new range still has to come from uni-lab.xyz's real calculation
    /// (computed off-chain, same as for rebalance()) — this function never
    /// derives newTickLower/newTickUpper itself, same as rebalance().
    /// Deliberately skips rebalance()'s periodicDue/_isOutOfRange() gate:
    /// the owner is choosing this is worth doing, not the keeper's automated
    /// heuristic — but the cooldown and rebalanceCount cap still apply, so
    /// this can't be spammed or used to exceed the owner's own configured
    /// limit. No _reimburseKeeperGas() — the owner pays their own gas
    /// directly, same reasoning as collectFees() (owner, no reimbursement)
    /// vs. harvestFees() (operator, reimbursed). Same feePayoutSwapIx
    /// dual-purpose param and hard-ceiling/hard-floor handling as rebalance()
    /// — see that function's own docstring.
    function ownerRebalance(
        int24 newTickLower,
        int24 newTickUpper,
        SwapInstruction calldata swapIx,
        SwapInstruction calldata feePayoutSwapIx,
        uint256 reinjectAmount,
        uint256 amount0Min,
        uint256 amount1Min
    ) external onlyOwner whenNotPaused notClosed nonReentrant returns (uint256 newTokenId) {
        if (positionTokenId == 0) revert NoPosition();
        if (rebalanceCount >= maxRebalances) revert RebalanceLimitReached();

        bool cooldownPassed = block.timestamp >= lastRebalanceTimestamp + minRebalanceInterval;
        if (!cooldownPassed) revert TooSoonToRebalance();

        newTokenId =
            _rebalanceCore(newTickLower, newTickUpper, swapIx, feePayoutSwapIx, reinjectAmount, amount0Min, amount1Min);
    }

    /// @notice Platform-operator equivalent of ownerRebalance() (inherited
    /// rebalance() enforces, but callable by the OPERATOR (the platform's
    /// the platform's own schedule rather than the owner's.
    ///
    /// Deliberately does NOT check rebalanceCount >= maxRebalances (unlike
    /// both rebalance() and ownerRebalance()) — this is a platform-wide
    /// lever, not something a per-vault owner-configured cap should
    /// constrain. Since _rebalanceCore() unconditionally bumps
    /// rebalanceCount by exactly 1 regardless of caller, that bump is
    /// cancelled right after the call (always safe — it can only ever have
    /// gone up by 1), and this path's own activity is tracked separately via
    /// forceRebalanceCount instead. This keeps the owner's own budget
    /// (rebalanceCount vs. maxRebalances) fully decoupled from platform
    /// action — an owner who set maxRebalances=20 still gets 20 of their
    /// own rebalance()/ownerRebalance() cycles, unaffected by how many times
    /// the platform separately force-rebalanced this vault.
    ///
    /// Cooldown is its own, dedicated gate (lastForceRebalanceTimestamp +
    /// PlatformConfig.forceRebalanceCooldownSeconds(), read live so the
    /// platform owner can retune it without a redeploy) — never
    /// minRebalanceInterval, which the vault's OWNER controls and could zero
    /// out for their own ownerRebalance() without meaning to also strip
    /// protection from this platform-level path.
    ///
    /// _reimburseKeeperGas() runs, same as rebalance() — this is a real
    /// operator-sent transaction, paid from this vault's own
    /// gasReserveBalance same as any other operator action.
    function operatorForceRebalance(
        int24 newTickLower,
        int24 newTickUpper,
        SwapInstruction calldata swapIx,
        SwapInstruction calldata feePayoutSwapIx,
        uint256 reinjectAmount,
        uint256 amount0Min,
        uint256 amount1Min
    ) external onlyOperator whenNotPaused notClosed nonReentrant returns (uint256 newTokenId) {
        uint256 gasStart = gasleft();

        if (positionTokenId == 0) revert NoPosition();
        uint256 cooldown = IPlatformConfig(platformConfig).forceRebalanceCooldownSeconds();
        if (block.timestamp < lastForceRebalanceTimestamp + cooldown) revert TooSoonToRebalance();

        newTokenId =
            _rebalanceCore(newTickLower, newTickUpper, swapIx, feePayoutSwapIx, reinjectAmount, amount0Min, amount1Min);

        lastForceRebalanceTimestamp = block.timestamp;
        rebalanceCount -= 1;
        forceRebalanceCount += 1;

        _reimburseKeeperGas(gasStart);
    }

    /// @dev Extracted from _rebalanceCore()/_withdrawPositionShare()/
    /// _closePositionRaw() — the decreaseLiquidity()+collect() pair was
    /// Factored out purely to keep bytecode down, no behavior change from
    /// having it inline at any of the 3 call sites.
    function _decreaseAndCollect(uint256 tokenId, uint128 liquidityToRemove, uint256 amount0Min, uint256 amount1Min)
        internal
        returns (uint256 removed0, uint256 removed1, uint256 collected0, uint256 collected1)
    {
        if (liquidityToRemove > 0) {
            (removed0, removed1) = positionManager.decreaseLiquidity(
                INonfungiblePositionManager.DecreaseLiquidityParams({
                    tokenId: tokenId,
                    liquidity: liquidityToRemove,
                    amount0Min: amount0Min,
                    amount1Min: amount1Min,
                    deadline: block.timestamp
                })
            );
        }
        (collected0, collected1) = _collectAll(tokenId);
    }

    /// mint an identical MintParams struct, differing only in which range
    /// (targetTick*/newTick*) and token id they use. Factored out purely to
    /// keep bytecode down, no behavior change.
    function _mintPosition(
        int24 tickLower,
        int24 tickUpper,
        uint256 amount0Desired,
        uint256 amount1Desired,
        uint256 amount0Min,
        uint256 amount1Min
    ) internal returns (uint256 tokenId, uint256 used0, uint256 used1) {
        (tokenId,, used0, used1) = positionManager.mint(
            INonfungiblePositionManager.MintParams({
                token0: token0,
                token1: token1,
                fee: feeTier,
                tickLower: tickLower,
                tickUpper: tickUpper,
                amount0Desired: amount0Desired,
                amount1Desired: amount1Desired,
                amount0Min: amount0Min,
                amount1Min: amount1Min,
                recipient: address(this),
                deadline: block.timestamp
            })
        );
    }

    /// shape (against positionTokenId, current-block deadline) was duplicated
    /// 4 times (_increaseLiquidityAndAccount, reinjectIntoPosition,
    /// sweepIdleDust, _reinjectFees). Factored out purely to keep bytecode
    /// down, no behavior change. Deliberately NOT reused by
    /// _sweepDustIntoPosition(), which needs the try/catch wrapper around the
    /// raw call and hardcoded 0,0 mins — different enough shape that sharing
    /// would cost more than it saves.
    function _increaseLiquidity(uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min)
        internal
        returns (uint256 used0, uint256 used1)
    {
        (, used0, used1) = positionManager.increaseLiquidity(
            INonfungiblePositionManager.IncreaseLiquidityParams({
                tokenId: positionTokenId,
                amount0Desired: amount0Desired,
                amount1Desired: amount1Desired,
                amount0Min: amount0Min,
                amount1Min: amount1Min,
                deadline: block.timestamp
            })
        );
    }

    /// destructure, keeping only `liquidity`, was duplicated 3 times
    /// (_rebalanceCore, _withdrawPositionShare, _closePositionRaw).
    /// Factored out purely to keep bytecode down, no behavior change.
    /// Deliberately NOT reused by _isOutOfRange(), which needs
    /// tickLower/tickUpper from the same call too — different enough shape
    /// that sharing would cost more than it saves.
    function _currentLiquidity() internal view returns (uint128 liquidity) {
        (,,,,,,, liquidity,,,,) = positionManager.positions(positionTokenId);
    }

    /// tokenId" (amount0Max/amount1Max both type(uint128).max) was
    /// duplicated identically 3 times (_rebalanceCore, collectFees,
    /// harvestFees). Factored out purely to keep bytecode down, no behavior
    /// change.
    function _collectAll(uint256 tokenId) internal returns (uint256 amount0, uint256 amount1) {
        (amount0, amount1) = positionManager.collect(
            INonfungiblePositionManager.CollectParams({
                tokenId: tokenId,
                recipient: address(this),
                amount0Max: type(uint128).max,
                amount1Max: type(uint128).max
            })
        );
    }

    /// live position, then split off the platform's performance-fee cut"
    /// was duplicated identically in collectFees() and harvestFees().
    /// Factored out purely to keep bytecode down, no behavior change.
    function _collectAllAndSplitFee() internal returns (uint256 amount0, uint256 amount1) {
        (uint256 collected0, uint256 collected1) = _collectAll(positionTokenId);
        (amount0, amount1) = _splitPerformanceFee(collected0, collected1);
    }

    /// what this fold-in used, set investableUsdt to whatever's left over
    /// (plus any pre-existing balance), then clamp uncountedInvestable so it
    /// can never exceed investableUsdt" was duplicated identically 3 times
    /// (_increaseLiquidityAndAccount, _rebalanceCore, reinjectIntoPosition).
    /// Factored out purely to keep bytecode down, no behavior change —
    /// `preExistingInvestable` is 0 at the 2 call sites that don't have one.
    function _foldCapitalAndClamp(uint256 preExistingInvestable, uint256 stableBal, uint256 foldedIn)
        internal
        returns (uint256 consumedUncounted)
    {
        consumedUncounted = foldedIn < uncountedInvestable ? foldedIn : uncountedInvestable;
        uncountedInvestable -= consumedUncounted;
        investableUsdt = preExistingInvestable + (stableBal - foldedIn);
        if (uncountedInvestable > investableUsdt) uncountedInvestable = investableUsdt;
    }

    /// plus whatever's left of stableBal after folding in used0/used1, then
    /// clamp uncountedInvestable" (the smaller variant, without touching
    /// uncountedInvestable's own subtraction — these 2 call sites never
    /// added to uncountedInvestable in the first place) was duplicated
    /// identically in increasePosition() and increasePositionWithToken().
    /// Factored out purely to keep bytecode down, no behavior change.
    function _setInvestableAndClamp(uint256 preExistingInvestable, uint256 stableBal, uint256 usedStable) internal {
        investableUsdt = preExistingInvestable + (stableBal - usedStable);
        if (uncountedInvestable > investableUsdt) uncountedInvestable = investableUsdt;
    }

    /// @dev Shared body of rebalance()/ownerRebalance() — everything past
    /// each function's own gate check (periodicDue/_isOutOfRange() for the
    /// former, none for the latter) is identical between them: the hard-
    /// ceiling/hard-floor check, decrease+collect, fee handling, the mint
    /// swap, optional reserve reinjection, the new mint, dust sweep, and
    /// ledger update. Factored out purely to keep this contract's deployed
    /// bytecode under EIP-170's 24576-byte limit (same discipline every
    /// prior version already established). No behavior change from inlining
    /// this into each caller — gas reimbursement (rebalance()-only) and
    /// rebalanceCount/lastRebalanceTimestamp bookkeeping in the triggered
    /// branch stay exactly where they were.
    function _rebalanceCore(
        int24 newTickLower,
        int24 newTickUpper,
        SwapInstruction calldata swapIx,
        SwapInstruction calldata feePayoutSwapIx,
        uint256 reinjectAmount,
        uint256 amount0Min,
        uint256 amount1Min
    ) internal returns (uint256 newTokenId) {
        (bool aboveCeiling, bool belowFloor) = _hardStopTriggered();
        bool shouldClose = aboveCeiling || belowFloor;
        if (!shouldClose) _checkRangeNearMarket(newTickLower, newTickUpper);

        uint128 liquidity = _currentLiquidity();
        (uint256 removed0, uint256 removed1, uint256 collected0, uint256 collected1) =
            _decreaseAndCollect(positionTokenId, liquidity, 0, 0);

        if (shouldClose) {
            // Deducts the platform's cut from the fee portion only (same as
            // always), everything else (principal + net fees) stays in the
            // vault's own balance and gets handled by _closePositionAndPause
            // below — nothing pays out to the owner here, this is a
            // rebalance outcome, not a withdrawal. The owner retrieves it
            // later via withdraw()/withdrawAll(), same as any idle
            // investable balance (or, for a no-swap floor exit, via the dust
            // bucket).
            _splitPerformanceFee(collected0 - removed0, collected1 - removed1);
            // Ceiling always converts 100% to stable; floor's conversion is
            // the owner's own choice (hardFloorConvertToStable).
            bool convertToStable = aboveCeiling || hardFloorConvertToStable;
            _closePositionAndPause(convertToStable, feePayoutSwapIx);
            rebalanceCount += 1;
            lastRebalanceTimestamp = block.timestamp;
            if (aboveCeiling) {
                emit HardCeilingTriggered(investableUsdt);
            } else {
                emit HardFloorTriggered(investableUsdt);
            }
            return 0;
        }

        uint256 lpFee0 = collected0 - removed0;
        uint256 lpFee1 = collected1 - removed1;
        (uint256 netFee0, uint256 netFee1) = _splitPerformanceFee(lpFee0, lpFee1);
        if (autoCompoundFees) {
            if (netFee0 > 0 || netFee1 > 0) {
                lastFeeClaimTimestamp = block.timestamp;
                emit FeesReinjected(netFee0, netFee1, 0, 0, _toStableUsd(netFee0, netFee1));
            }
        } else {
            if (payoutFeesInStableOnly) (netFee0, netFee1) = _convertPayoutToStable(netFee0, netFee1, feePayoutSwapIx);
            _payFeesToOwner(netFee0, netFee1);
        }

        _executeSwap(swapIx);

        if (reinjectAmount > 0) {
            if (reinjectAmount > reinjectionAmount) revert ReinjectionExceedsCap();
            if (reinjectAmount > reserveBalance) revert InsufficientReserve();
            reserveBalance -= reinjectAmount;

            // deposit time anymore (see deposit()/depositToken()); it
            // charges HERE instead, cut directly from the reinjected amount
            // itself (same "cut while passing through" pattern
            // _splitPerformanceFee already uses elsewhere in this contract),
            // not pulled as an extra transfer — there's no new inbound
            // transfer in this code path to pull from. The mint below
            // receives the net amount; reserveBalance was already debited
            // the GROSS amount above, matching how much left the reserve
            // the exact same call shape.
            uint256 reinjectFee = _creationFeeFor(reinjectAmount);
            _payCreationFee(reinjectFee);
            reinjectAmount -= reinjectFee;
        }

        (uint256 stableBal, uint256 volatileBal) = _measureAvailable(0, 0);
        (uint256 amount0, uint256 amount1) = _toToken01(stableBal, volatileBal);

        uint256 used0;
        uint256 used1;
        (newTokenId, used0, used1) = _mintPosition(newTickLower, newTickUpper, amount0, amount1, amount0Min, amount1Min);

        positionTokenId = newTokenId;

        (uint256 swept0, uint256 swept1) = _sweepDustIntoPosition(newTokenId, amount0 - used0, amount1 - used1);

        uint256 foldedInStable = _stableOf(used0, used1) + _stableOf(swept0, swept1);
        uint256 consumedUncounted = _foldCapitalAndClamp(0, stableBal, foldedInStable);

        rebalanceCount += 1;
        lastRebalanceTimestamp = block.timestamp;

        emit Rebalanced(newTokenId, newTickLower, newTickUpper, reinjectAmount, consumedUncounted);
    }

    function reinjectIntoPosition(
        SwapInstruction calldata swapIx,
        uint256 amount,
        uint256 amount0Min,
        uint256 amount1Min
    ) external onlyOperator whenNotPaused notClosed nonReentrant {
        uint256 gasStart = gasleft();

        if (positionTokenId == 0) revert NoPosition();
        if (amount == 0) return;
        if (amount > reinjectionAmount) revert ReinjectionExceedsCap();
        if (amount > reserveBalance) revert InsufficientReserve();

        reserveBalance -= amount;

        uint256 preExistingInvestable = investableUsdt;
        investableUsdt = 0;

        _executeSwap(swapIx);

        (uint256 stableBal, uint256 volatileBal) = _measureAvailable(preExistingInvestable, 0);
        if (stableBal > amount) stableBal = amount;
        (uint256 amount0, uint256 amount1) = _toToken01(stableBal, volatileBal);

        (uint256 used0, uint256 used1) = _increaseLiquidity(amount0, amount1, amount0Min, amount1Min);

        _setInvestableAndClamp(preExistingInvestable, stableBal, _stableOf(used0, used1));

        _reimburseKeeperGas(gasStart);

        emit ReinjectedIntoPosition(amount, used0, used1);
    }

    /// @notice Reclamo programado de comisiones — ver RangeVaultCompound.sol.
    /// Reembolsa gas al keeper igual que el resto de entrypoints operator-only
    /// que el keeper envía como su propia transacción. Sigue requiriendo
    /// autoCompoundFees == true (harvestFees() never pays out directly to the
    /// owner, so payoutFeesInStableOnly has no bearing here).
    function harvestFees(SwapInstruction calldata swapIx, uint256 amount0Min, uint256 amount1Min)
        external
        onlyOperator
        whenNotPaused
        notClosed
        nonReentrant
        returns (uint256 amount0, uint256 amount1)
    {
        uint256 gasStart = gasleft();

        if (positionTokenId == 0) revert NoPosition();
        if (!autoCompoundFees) revert AutoCompoundNotEnabled();

        (amount0, amount1) = _collectAllAndSplitFee();

        _reinjectFees(amount0, amount1, swapIx, amount0Min, amount1Min, 0, 0);

        _reimburseKeeperGas(gasStart);
    }

    function sweepIdleDust(SwapInstruction calldata swapIx, uint256 amount0Min, uint256 amount1Min)
        external
        onlyOperator
        whenNotPaused
        notClosed
        nonReentrant
    {
        uint256 gasStart = gasleft();

        if (positionTokenId == 0) revert NoPosition();

        _executeSwap(swapIx);

        (uint256 stableBal, uint256 volatileBal) = _measureAvailable(0, 0);
        (uint256 amount0, uint256 amount1) = _toToken01(stableBal, volatileBal);

        (uint256 used0, uint256 used1) = _increaseLiquidity(amount0, amount1, amount0Min, amount1Min);

        uint256 consumedUncounted = _foldCapitalAndClamp(0, stableBal, _stableOf(used0, used1));

        _reimburseKeeperGas(gasStart);

        emit IdleDustSwept(used0, used1, consumedUncounted);
    }

    // ---------------------------------------------------------------------
    // Owner: collect fees — trading fees only, principal untouched
    // ---------------------------------------------------------------------

    /// @notice `feePayoutSwapIx` — only consumed in the non-compounding
    /// branch when payoutFeesInStableOnly is enabled; a no-op (amountIn == 0)
    /// otherwise, same convention as every other SwapInstruction param in
    /// this contract.
    function collectFees(SwapInstruction calldata swapIx, SwapInstruction calldata feePayoutSwapIx, uint256 amount0Min, uint256 amount1Min)
        external
        onlyOwner
        nonReentrant
        returns (uint256 amount0, uint256 amount1)
    {
        if (positionTokenId == 0) revert NoPosition();

        (amount0, amount1) = _collectAllAndSplitFee();

        if (autoCompoundFees) {
            _reinjectFees(amount0, amount1, swapIx, amount0Min, amount1Min, 0, 0);
        } else {
            if (payoutFeesInStableOnly) (amount0, amount1) = _convertPayoutToStable(amount0, amount1, feePayoutSwapIx);
            _payOwner(amount0, amount1);
            lastFeeClaimTimestamp = block.timestamp;
            emit FeesCollected(amount0, amount1);
        }
    }

    // ---------------------------------------------------------------------
    // Owner: withdraw — the only path principal can ever leave the vault
    // ---------------------------------------------------------------------

    /// @notice The 4 ledger buckets are fully independent. Layered behavior:
    ///   - Partial exit (positionShareBps < 10_000) with autoCompoundFees on:
    ///     fees reinject into the REMAINING position via `feeSwapIx` — pure
    ///     principal (no fees mixed in) is what reaches amount0/amount1.
    ///   - Partial exit with autoCompoundFees off: fees pay out directly,
    ///     optionally converted to stable first if payoutFeesInStableOnly is
    ///     on (`feeSwapIx` sized for that), tracked in their own
    ///     LpFeesPaidToOwner event — never merged into amount0/amount1.
    ///   - Full close (positionShareBps == 10_000): no remaining position to
    ///     reinject into either way — fees pay out merged with principal,
    ///     still respecting payoutFeesInStableOnly (intent-based: from the
    ///     owner's perspective a full close is indistinguishable from any
    ///     other direct fee payout).
    ///   - `payoutSwapIx` always runs LAST, on whatever total0/total1 end up
    ///     being after the branch above resolves — works identically
    ///     regardless of autoCompoundFees's state, since it only ever sees
    ///     pure principal (when compounding is on) or principal+fees (when
    ///     off), never double-converts what feeSwapIx already touched.
    ///   - `dustAmount0`/`dustAmount1` optionally sweep raw token0/token1
    ///     balance sitting in the vault unaccounted for by any of the 4
    ///     ledgers (a swap that didn't fold in exactly) — see
    ///     _availableDust() below. Never counted toward B1 either way.
    function withdraw(
        uint256 positionShareBps,
        uint256 investableShareBps,
        uint256 reserveShareBps,
        uint256 gasReserveShareBps,
        uint256 dustAmount0,
        uint256 dustAmount1,
        SwapInstruction calldata feeSwapIx,
        SwapInstruction calldata payoutSwapIx,
        uint256 amount0Min,
        uint256 amount1Min
    ) external onlyOwner nonReentrant {
        if (
            positionShareBps > 10_000 || investableShareBps > 10_000 || reserveShareBps > 10_000
                || gasReserveShareBps > 10_000
        ) revert InvalidShareBps();
        // A dust-only withdrawal (all 4 shares at 0) is a valid request too,
        // so the "at least one thing requested" gate must also accept
        // dustAmount0/dustAmount1 alone.
        if (
            positionShareBps == 0 && investableShareBps == 0 && reserveShareBps == 0 && gasReserveShareBps == 0
                && dustAmount0 == 0 && dustAmount1 == 0
        ) revert InvalidShareBps();

        uint256 amount0;
        uint256 amount1;
        // Principal removed from the position — SEPARATE from amount0/amount1
        // above, which also fold in the owner's fee share in the full-close
        // case only (partial-exit-plus-compounding never merges them at
        // all). Fees never counted toward B1, so principalUsd below must be
        // computed from these, never from amount0/amount1 directly.
        uint256 removedPrincipal0;
        uint256 removedPrincipal1;

        if (positionShareBps > 0 && positionTokenId != 0) {
            (amount0, amount1, removedPrincipal0, removedPrincipal1) =
                _withdrawPositionShare(positionShareBps, feeSwapIx, amount0Min, amount1Min);
        }

        uint256 investableShare = (investableUsdt * investableShareBps) / 10_000;
        uint256 reserveShare = (reserveBalance * reserveShareBps) / 10_000;
        uint256 gasReserveShare = (gasReserveBalance * gasReserveShareBps) / 10_000;
        investableUsdt -= investableShare;
        reserveBalance -= reserveShare;
        gasReserveBalance -= gasReserveShare;

        // investableShare itself can be a mix of already-counted capital and
        // still-uncounted pending top-ups (see uncountedInvestable's own
        // docstring) — the slice proportional to investableShareBps shrinks
        // uncountedInvestable the same way the position/reserve/gas shares
        // above shrink their own ledgers, and principalUsd must exclude the
        // uncounted portion (can't subtract from B1 what was never added).
        uint256 uncountedShare = (uncountedInvestable * investableShareBps) / 10_000;
        uncountedInvestable -= uncountedShare;

        // Deliberately excludes fees (never in B1), reserveShare/
        // gasReserveShare (reserve only ever counts in B1 at the moment it's
        // REINJECTED — withdrawing it un-reinjected is withdrawing capital
        // that was never added to B1 in the first place, so it can't
        // subtract from it either), and uncountedShare (same reasoning,
        // applied to the investable leg).
        uint256 principalUsd = _toStableUsd(removedPrincipal0, removedPrincipal1) + (investableShare - uncountedShare);

        (uint256 ledger0, uint256 ledger1) = _toToken01(investableShare + reserveShare + gasReserveShare, 0);
        uint256 total0 = amount0 + ledger0;
        uint256 total1 = amount1 + ledger1;

        // Dust bucket, sized against what's genuinely unaccounted for AFTER
        // this call's own claims (total0/total1) and whatever ledger balance
        // remains for later withdrawals.
        (uint256 dust0, uint256 dust1) = _availableDust(total0, total1);
        if (dustAmount0 > dust0 || dustAmount1 > dust1) revert InvalidDustAmount();
        total0 += dustAmount0;
        total1 += dustAmount1;

        // Per-call "todo en stable", owner-sized, runs last, over whatever
        // this specific withdrawal ends up paying out.
        (total0, total1) = _convertPayoutToStable(total0, total1, payoutSwapIx);

        _payOwner(total0, total1);

        emit Withdrawn(total0, total1, principalUsd);
    }

    /// @notice How much of the vault's raw token0/token1 balance is
    /// genuinely unaccounted for: not part of `claimed0`/`claimed1` (this
    /// withdrawal's own position + ledger shares, already computed by the
    /// caller) and not part of whatever ledger balance REMAINS in the vault
    /// for future withdrawals (investableUsdt/reserveBalance/
    /// gasReserveBalance, read here AFTER withdraw() already decremented
    /// them by this call's shares). Whatever's left over is stray dust — a
    /// swap that didn't fold in exactly on a prior mint/increaseLiquidity(),
    /// or the natural leftover of a no-swap hard-floor exit.
    function _availableDust(uint256 claimed0, uint256 claimed1) internal view returns (uint256 dust0, uint256 dust1) {
        (uint256 remainingLedger0, uint256 remainingLedger1) =
            _toToken01(investableUsdt + reserveBalance + gasReserveBalance, 0);
        uint256 rawBal0 = IERC20(token0).balanceOf(address(this));
        uint256 rawBal1 = IERC20(token1).balanceOf(address(this));
        uint256 accounted0 = claimed0 + remainingLedger0;
        uint256 accounted1 = claimed1 + remainingLedger1;
        dust0 = rawBal0 > accounted0 ? rawBal0 - accounted0 : 0;
        dust1 = rawBal1 > accounted1 ? rawBal1 - accounted1 : 0;
    }

    /// @dev Extracted from withdraw() purely to keep local-variable count
    /// under control (stack-too-deep risk with 8 params + this much local
    /// state) — no behavior difference from having it inline. Returns
    /// amount0/amount1/removedPrincipal0/removedPrincipal1 — the caller MUST
    /// capture all four from the call site, Solidity doesn't mutate a
    /// value-type argument in place.
    function _withdrawPositionShare(
        uint256 positionShareBps,
        SwapInstruction calldata feeSwapIx,
        uint256 amount0Min,
        uint256 amount1Min
    ) internal returns (uint256 amount0, uint256 amount1, uint256 removedPrincipal0, uint256 removedPrincipal1) {
        uint128 partialLiquidity = uint128((uint256(_currentLiquidity()) * positionShareBps) / 10_000);
        (uint256 removed0, uint256 removed1, uint256 collected0, uint256 collected1) =
            _decreaseAndCollect(positionTokenId, partialLiquidity, 0, 0);
        (uint256 netFee0, uint256 netFee1) = _splitPerformanceFee(collected0 - removed0, collected1 - removed1);
        removedPrincipal0 = removed0;
        removedPrincipal1 = removed1;

        bool fullClose = positionShareBps == 10_000;
        // Shared by the full-close and non-compounding-partial branches below
        // (hoisted purely to keep bytecode down, same call either way) — NOT
        // applied in the autoCompoundFees-reinject branch, which never
        // converts anything.
        if ((fullClose || !autoCompoundFees) && payoutFeesInStableOnly) {
            (netFee0, netFee1) = _convertPayoutToStable(netFee0, netFee1, feeSwapIx);
        }

        if (fullClose) {
            positionTokenId = 0;
            // Full close — no remaining position to reinject into regardless
            // of autoCompoundFees; fees merge with principal, still
            // respecting payoutFeesInStableOnly (intent-based — see this
            // function's own docstring).
            amount0 = removed0 + netFee0;
            amount1 = removed1 + netFee1;
        } else if (autoCompoundFees) {
            // Fees reinject into the position that's staying open; the owner
            // receives pure principal only. removed0/removed1 must be
            // excluded from _reinjectFees()'s own balance measurement —
            // decreaseLiquidity() above already deposited them into the
            // vault's raw balance too, see _reinjectFees()'s own docstring.
            _reinjectFees(
                netFee0, netFee1, feeSwapIx, amount0Min, amount1Min, _stableOf(removed0, removed1),
                stableIsToken0 ? removed1 : removed0
            );
            amount0 = removed0;
            amount1 = removed1;
        } else {
            _payFeesToOwner(netFee0, netFee1);
            amount0 = removed0;
            amount1 = removed1;
        }
    }

    function withdrawAll(SwapInstruction calldata feeSwapIx, SwapInstruction calldata payoutSwapIx)
        external
        onlyOwner
        nonReentrant
    {
        (uint256 removed0, uint256 removed1, uint256 netFee0, uint256 netFee1) = _closePositionRaw();
        // Fees aren't tracked separately here (everything sweeps out
        // undifferentiated below) — if the preference is on, just convert
        // them in place; the stable proceeds land in the vault's own balance
        // and get swept out regardless of currency by the balanceOf reads
        // inside _sweepLedgersAndPrincipalUsd below.
        if (payoutFeesInStableOnly) _convertPayoutToStable(netFee0, netFee1, feeSwapIx);

        (uint256 principalUsd, uint256 amount0, uint256 amount1) = _sweepLedgersAndPrincipalUsd(removed0, removed1);

        // Owner-sized "todo en stable" over the full sweep.
        (amount0, amount1) = _convertPayoutToStable(amount0, amount1, payoutSwapIx);

        _payOwner(amount0, amount1);

        emit Withdrawn(amount0, amount1, principalUsd);
    }

    /// excludes any swap dependency entirely (no SwapInstruction param,
    /// ignores payoutFeesInStableOnly). This is the last-resort exit; its
    /// ENTIRE purpose is to work no matter what state the rest of the system
    /// is in. Adding a swap dependency here would reintroduce, in a worse
    /// form, exactly the category of risk this function exists to remove: an
    /// external call (swapRouter.exactInputSingle) that can revert for
    /// reasons entirely outside this vault's control — insufficient pool
    /// liquidity, an unmet amountOutMinimum, the router itself paused. An
    /// owner with payoutFeesInStableOnly enabled will get raw mixed-token
    /// funds specifically from this one call — a deliberate, documented
    /// inconsistency, not an oversight.
    function emergencyWithdrawPosition() external onlyOwner nonReentrant {
        paused = true;
        emit PausedSet(true);

        (uint256 removed0, uint256 removed1,,) = _closePositionRaw();
        (uint256 principalUsd, uint256 amount0, uint256 amount1) = _sweepLedgersAndPrincipalUsd(removed0, removed1);

        _payOwner(amount0, amount1);

        emit EmergencyWithdraw(amount0, amount1, principalUsd);
    }

    /// @dev Shared by withdrawAll()/emergencyWithdrawPosition() — fully
    /// closes whatever position exists (decreaseLiquidity 100% + collect +
    /// _splitPerformanceFee), returns the removed principal and net fee
    /// legs. Callers decide independently what to do with the fee (convert
    /// to stable, or just let it fall into the raw balanceOf sweep below).
    /// Returns all-zero, no-op if there's no open position. Deliberately
    /// keeps decreaseLiquidity()'s amount0Min/amount1Min hardcoded at 0,0 via
    /// _decreaseAndCollect() — same "no swap/slippage dependency, ever"
    /// principle as the rest of this last-resort path.
    function _closePositionRaw() internal returns (uint256 removed0, uint256 removed1, uint256 netFee0, uint256 netFee1) {
        if (positionTokenId == 0) return (0, 0, 0, 0);
        uint256 collected0;
        uint256 collected1;
        (removed0, removed1, collected0, collected1) = _decreaseAndCollect(positionTokenId, _currentLiquidity(), 0, 0);
        (netFee0, netFee1) = _splitPerformanceFee(collected0 - removed0, collected1 - removed1);
        positionTokenId = 0;
    }

    /// @dev Shared by withdrawAll()/emergencyWithdrawPosition() — saturating
    /// subtraction (this principalUsd figure only feeds the audit event, B1
    /// accounting off-chain, and must never be able to block the actual fund
    /// transfer), then zeroes all 4 ledgers and reads the vault's real raw
    /// balance to sweep. Factored out purely to keep bytecode down — no
    /// behavior change.
    function _sweepLedgersAndPrincipalUsd(uint256 removed0, uint256 removed1)
        internal
        returns (uint256 principalUsd, uint256 amount0, uint256 amount1)
    {
        uint256 investableCounted = investableUsdt > uncountedInvestable ? investableUsdt - uncountedInvestable : 0;
        principalUsd = _toStableUsd(removed0, removed1) + investableCounted;

        amount0 = IERC20(token0).balanceOf(address(this));
        amount1 = IERC20(token1).balanceOf(address(this));
        investableUsdt = 0;
        reserveBalance = 0;
        gasReserveBalance = 0;
        uncountedInvestable = 0;
    }

    function closeVault() external onlyOwner {
        if (closed) revert VaultClosed();
        if (
            positionTokenId != 0 || investableUsdt != 0 || reserveBalance != 0 || gasReserveBalance != 0
                || IERC20(token0).balanceOf(address(this)) != 0 || IERC20(token1).balanceOf(address(this)) != 0
        ) {
            revert VaultNotEmpty();
        }
        closed = true;
        emit Closed();
    }

    // ---------------------------------------------------------------------
    // Internal helpers
    // ---------------------------------------------------------------------

    uint256 constant GAS_REIMBURSEMENT_OVERHEAD = 40_000;
    /// 24h heartbeat for the Arbitrum ETH/USD feed, re-confirm against the
    /// real feed's heartbeat at deploy time (see deploy_v5.sh).
    uint256 constant MAX_GAS_ORACLE_STALENESS = 90_000;

    function _reimburseKeeperGas(uint256 gasStart) internal {
        uint256 effectiveGasPrice = tx.gasprice < block.basefee * 3 ? tx.gasprice : block.basefee * 3;
        uint256 gasUsed = gasStart - gasleft() + GAS_REIMBURSEMENT_OVERHEAD;
        // VAULT'S OWN POOL price to convert gas cost (always genuinely ETH
        // wei) into stable. Silently correct only when the vault's volatile
        // asset happens to BE the L2's native gas token (WETH) — wrong for
        // any other pair (confirmed live: a WBTC/USDT0 vault computed a
        // ~$8 BILLION "gas cost" this way, draining its entire gas-reserve
        // bucket in a single call). _ethUsdFromOracle uses a dedicated,
        // decoupled Chainlink ETH/USD feed instead — see gasPriceOracle's
        // own docstring.
        uint256 gasCostUsd = _ethUsdFromOracle(gasUsed * effectiveGasPrice);
        uint256 gasReimbursed = gasCostUsd < gasReserveBalance ? gasCostUsd : gasReserveBalance;
        if (gasReimbursed > 0) {
            gasReserveBalance -= gasReimbursed;
            IERC20(_stableAddr()).safeTransfer(operator, gasReimbursed);
            emit KeeperGasReimbursed(gasReimbursed, gasUsed, effectiveGasPrice);
        }
    }

    /// units via gasPriceOracle, a dedicated Chainlink-style ETH/USD feed —
    /// deliberately NOT this vault's own pool (see _reimburseKeeperGas's own
    /// docstring for why that was wrong). Degrades to 0 on ANY failure
    /// (stale, reverting call, non-positive answer) rather than reverting
    /// the real operation this is called from (initPosition/rebalance/
    /// reinjectIntoPosition/harvestFees/sweepIdleDust) — same principle
    /// already established in this codebase: "proteger el capital del owner
    /// gana siempre sobre cobrarle al operador" (see CLAUDE.md's "Visibilidad
    /// de gas agotado"). Worst case here is simply the keeper not getting
    /// reimbursed for this one call, never a stuck vault.
    ///
    /// Formula: wei[18d] × answer[8d] / 1e18[wei→ETH] × 1e6[USD→stable-6d] /
    /// 1e8[feed decimals] = /1e20 — only valid for a 6-decimal stable, which
    /// initialize() already enforces (see UnsupportedStableDecimals).
    function _ethUsdFromOracle(uint256 weiAmount) internal view returns (uint256) {
        try IAggregatorV3(gasPriceOracle).latestRoundData() returns (
            uint80, int256 answer, uint256, uint256 updatedAt, uint80
        ) {
            if (answer <= 0) return 0;
            if (block.timestamp - updatedAt > MAX_GAS_ORACLE_STALENESS) return 0;
            return (weiAmount * uint256(answer)) / 1e20;
        } catch {
            return 0;
        }
    }

    /// @dev Reinyecta fees ya cobradas (post-_splitPerformanceFee) al principal
    /// de la posición abierta — ver RangeVaultCompound.sol para el porqué del
    /// swap mixto (fees llegan en las dos piernas a la vez). Generalizado
    /// sobre _stableAddr()/_volatileAddr()/_toToken01()/_stableOf() como el
    /// resto de esta variante Arbitrum.
    /// @dev `excludeStableExtra`/`excludeVolatileExtra` — additional balance
    /// to treat as "not available for this reinject", beyond the usual
    /// preExistingInvestable/reserveBalance/gasReserveBalance ledgers. Zero
    /// for collectFees()/harvestFees() (the vault's balance at that point
    /// genuinely is only the fee, nothing else). Nonzero for
    /// _withdrawPositionShare()'s compounding-partial-exit branch: that call
    /// site runs AFTER decreaseLiquidity() has already deposited the
    /// REMOVED PRINCIPAL into the vault's raw token balance too — without
    /// this exclusion, this function's balance-delta measurement can't tell
    /// principal and fee apart, sweeps the principal into the reinject
    /// alongside the fee, and then reverts trying to pay the owner an amount
    /// that's already been spent.
    function _reinjectFees(
        uint256 netFee0,
        uint256 netFee1,
        SwapInstruction calldata swapIx,
        uint256 amount0Min,
        uint256 amount1Min,
        uint256 excludeStableExtra,
        uint256 excludeVolatileExtra
    ) internal {
        if (netFee0 == 0 && netFee1 == 0) return;

        // Valued from the fee amounts themselves, at the pool's price right
        // now — before _executeSwap below, which only trades one leg for the
        // other at that same price and creates no new value, so computing it
        // here vs. after is equivalent modulo swap slippage/fees (negligible
        // for this accounting figure, same tolerance the rest of the B1/A1
        // design already accepts).
        uint256 netFeeUsd = _toStableUsd(netFee0, netFee1);

        uint256 preExistingInvestable = investableUsdt;
        investableUsdt = 0;

        _executeSwap(swapIx);

        (uint256 stableBal, uint256 volatileBal) =
            _measureAvailable(preExistingInvestable + excludeStableExtra, excludeVolatileExtra);
        (uint256 amount0, uint256 amount1) = _toToken01(stableBal, volatileBal);

        (uint256 used0, uint256 used1) = _increaseLiquidity(amount0, amount1, amount0Min, amount1Min);

        _setInvestableAndClamp(preExistingInvestable, stableBal, _stableOf(used0, used1));

        lastFeeClaimTimestamp = block.timestamp;
        emit FeesReinjected(netFee0, netFee1, used0, used1, netFeeUsd);
    }

    function _splitPerformanceFee(uint256 fee0, uint256 fee1) internal returns (uint256 net0, uint256 net1) {
        uint256 bps = IPlatformConfig(platformConfig).performanceFeeBps();
        uint256 platform0 = (fee0 * bps) / 10_000;
        uint256 platform1 = (fee1 * bps) / 10_000;
        if (platform0 > 0) IERC20(token0).safeTransfer(operator, platform0);
        if (platform1 > 0) IERC20(token1).safeTransfer(operator, platform1);
        if (platform0 > 0 || platform1 > 0) emit PerformanceFeeCollected(platform0, platform1);
        net0 = fee0 - platform0;
        net1 = fee1 - platform1;
    }

    /// token0/token1 to the owner" was duplicated identically across
    /// withdraw(), withdrawAll(), and emergencyWithdrawPosition() (each
    /// emits its own distinct event right after, so only the transfer pair
    /// itself is shared here, not the event). Factored out purely to keep
    /// bytecode down, no behavior change.
    function _payOwner(uint256 amount0, uint256 amount1) internal {
        if (amount0 > 0) IERC20(token0).safeTransfer(owner, amount0);
        if (amount1 > 0) IERC20(token1).safeTransfer(owner, amount1);
    }

    /// then emit LpFeesPaidToOwner" tail was duplicated identically in
    /// _rebalanceCore()'s and _withdrawPositionShare()'s non-compounding
    /// branches. Factored out purely to keep bytecode down, no behavior
    /// change.
    function _payFeesToOwner(uint256 fee0, uint256 fee1) internal {
        _payOwner(fee0, fee1);
        if (fee0 > 0 || fee1 > 0) emit LpFeesPaidToOwner(fee0, fee1);
    }

    function _sweepDustIntoPosition(uint256 tokenId, uint256 leftover0, uint256 leftover1)
        internal
        returns (uint256 swept0, uint256 swept1)
    {
        if (leftover0 == 0 && leftover1 == 0) return (0, 0);
        try positionManager.increaseLiquidity(
            INonfungiblePositionManager.IncreaseLiquidityParams({
                tokenId: tokenId,
                amount0Desired: leftover0,
                amount1Desired: leftover1,
                amount0Min: 0,
                amount1Min: 0,
                deadline: block.timestamp
            })
        ) returns (uint128, uint256 used0, uint256 used1) {
            swept0 = used0;
            swept1 = used1;
        } catch {
            swept0 = 0;
            swept1 = 0;
        }
    }

    /// @notice Converts up to swapIx.amountIn of whatever volatile-token leg
    /// is present in (amount0, amount1) into the vault's stable token,
    /// returning the resulting (out0, out1) with the same total economic
    /// value, just re-split toward stable. Shared by both mechanisms: the
    /// persistent payoutFeesInStableOnly preference (collectFees/rebalance/
    /// ownerRebalance's fee-only amounts) and the per-call payoutSwapIx
    /// (withdraw/withdrawAll's principal+fee amounts), plus the hard-ceiling/
    /// hard-floor full close-out. Operates on NET amounts only (post-
    /// _splitPerformanceFee where relevant) — the platform's cut is always
    /// taken first, in the original token split, never touched by this.
    ///
    /// swapIx.amountIn == 0 is a complete no-op (returns the input
    /// unchanged) — same convention as _executeSwap itself, so a caller who
    /// doesn't want any conversion just passes the same inert default used
    /// everywhere else in this contract.
    ///
    /// Deliberately reverts (rather than silently clamping) if
    /// swapIx.amountIn exceeds the volatile amount actually present in THIS
    /// call's (amount0, amount1) — the one place in this contract where a
    /// caller-supplied SwapInstruction gets validated against a hard,
    /// known-in-advance bound, unlike a mint/reinject swap's target amount
    /// (a heuristic, not a fact). Closes off selling volatile balance that
    /// has nothing to do with this specific payout. Under-sizing (amountIn
    /// less than the full volatile leg) degrades gracefully instead —
    /// whatever isn't converted just pays out raw alongside the converted
    /// stable, no revert.
    function _convertPayoutToStable(uint256 amount0, uint256 amount1, SwapInstruction calldata swapIx)
        internal
        returns (uint256 out0, uint256 out1)
    {
        uint256 volatileAmount = stableIsToken0 ? amount1 : amount0;
        if (swapIx.amountIn > volatileAmount) revert InvalidSwapInstruction();
        if (swapIx.amountIn == 0) return (amount0, amount1);

        bool sellsVolatileForStable = _sellsVolatileForStable(swapIx);
        if (!sellsVolatileForStable) revert InvalidSwapInstruction();

        uint256 stableBefore = IERC20(_stableAddr()).balanceOf(address(this));
        _executeSwap(swapIx);
        uint256 stableReceived = IERC20(_stableAddr()).balanceOf(address(this)) - stableBefore;

        uint256 remainingVolatile = volatileAmount - swapIx.amountIn;
        uint256 stableAmount = stableIsToken0 ? amount0 : amount1;
        (out0, out1) = _toToken01(stableAmount + stableReceived, remainingVolatile);
    }

    /// @notice Hard ceiling / hard floor share this exit path — closes the
    /// position and auto-pauses, called from rebalance()/ownerRebalance()
    /// once either trigger has been confirmed and decrease+collect have
    /// already run (the caller passes control here right after).
    /// `convertToStable == false` (only possible via a no-swap floor exit)
    /// leaves any volatile leg as raw, untracked balance — never folded into
    /// investableUsdt (a stable-only ledger) — retrievable via the dust
    /// bucket in withdraw() or withdrawAll()/emergencyWithdrawPosition().
    /// Reuses `paused`/`whenNotPaused` (already blocks initPosition()/
    /// rebalance()) instead of a new flag — this is also what stops
    /// checkVault() (keeper, off-chain) from mistaking positionTokenId == 0
    /// for "brand new vault, needs its first position" and trying to
    /// auto-reopen: initPosition() itself reverts while paused, no
    /// keeper-side change needed. withdraw() has no whenNotPaused gate, so
    /// the owner can always retrieve the parked balance regardless.
    function _closePositionAndPause(bool convertToStable, SwapInstruction calldata exitSwapIx) internal {
        uint256 stableBal = IERC20(_stableAddr()).balanceOf(address(this)) - reserveBalance - gasReserveBalance;

        if (convertToStable) {
            uint256 volatileBal = IERC20(_volatileAddr()).balanceOf(address(this));
            (uint256 exitAmount0, uint256 exitAmount1) = _toToken01(stableBal, volatileBal);
            (exitAmount0, exitAmount1) = _convertPayoutToStable(exitAmount0, exitAmount1, exitSwapIx);
            stableBal = _stableOf(exitAmount0, exitAmount1);
        }

        // Stays inside the vault as investableUsdt — this is a rebalance
        // outcome, not a withdrawal. The owner still owns this capital,
        // retrievable via withdraw()/withdrawAll() same as any other idle
        // investable balance (plus the dust bucket for any raw volatile leg
        // left behind when convertToStable is false).
        investableUsdt = stableBal;
        if (uncountedInvestable > investableUsdt) uncountedInvestable = investableUsdt;

        positionTokenId = 0;
        paused = true;
        emit PausedSet(true);
    }

    /// duplicated 4 times (deposit/depositToken include gasReserveBalance in
    /// currentTotal, increasePosition/increasePositionWithToken don't, since
    /// there's no gas-reserve bucket involved in a top-up to an existing
    /// position). `includeGasReserve` picks the right variant. Factored out
    /// purely to keep bytecode down, no behavior change.
    function _enforceDepositCap(uint256 addedAmount, bool includeGasReserve) internal view {
        uint256 cap = IPlatformConfig(platformConfig).maxDepositUsd();
        uint256 currentTotal = reserveBalance + investableUsdt + (includeGasReserve ? gasReserveBalance : 0);
        if (cap != 0 && currentTotal + addedAmount > cap) revert DepositExceedsPlatformCap();
    }

    /// event was duplicated identically in deposit() and depositToken().
    /// Factored out purely to keep bytecode down, no behavior change.
    function _creditDepositLedgers(uint256 investableAmount, uint256 reserveAmount, uint256 gasReserveAmount) internal {
        reserveBalance += reserveAmount;
        investableUsdt += investableAmount;
        gasReserveBalance += gasReserveAmount;
        emit Deposited(investableAmount, reserveAmount, gasReserveAmount, false);
    }

    /// investableUsdt while stashing its pre-existing value was duplicated
    /// identically in increasePosition() and increasePositionWithToken().
    /// Factored out purely to keep bytecode down, no behavior change.
    function _beginIncreasePosition(uint256 usdtAmount) internal returns (uint256 preExistingInvestable) {
        _enforceDepositCap(usdtAmount, false);
        preExistingInvestable = investableUsdt;
        investableUsdt = 0;
    }

    /// plus its PositionIncreased emit was duplicated identically in
    /// increasePosition() and increasePositionWithToken(). Factored out
    /// purely to keep bytecode down, no behavior change.
    function _finishAndEmitIncrease(
        uint256 usdtAmount,
        uint256 realVolatileTopUp,
        uint256 preExistingInvestable,
        uint256 feeStable,
        SwapInstruction calldata swapIx,
        uint256 amount0Min,
        uint256 amount1Min
    ) internal {
        (uint256 used0, uint256 used1, uint256 consumedUncounted, uint256 volatileFoldedUsd) =
            _finishIncreasePosition(usdtAmount, realVolatileTopUp, preExistingInvestable, feeStable, swapIx, amount0Min, amount1Min);
        emit PositionIncreased(usdtAmount, used0, used1, consumedUncounted, volatileFoldedUsd);
    }

    /// tiered schedule — see this contract's own class docstring, item 1,
    /// for the full product rationale. `cumulativeFeeableUsd` is this
    /// vault's own running total of every fee-eligible dollar ever
    /// contributed (never decremented); `priorTotal`/`newTotal` bracket the
    /// delta THIS call contributes. The one-time flat fee only ever fires
    /// once, exactly when `priorTotal == 0` (this vault's very first
    /// fee-eligible call ever) — guarded by `baseAmount == 0` returning
    /// early so a deposit()/depositToken() call funding ONLY reserve/gas
    /// (investableAmount == 0) can never accidentally burn that one-time
    /// charge on zero real capital. `tier2` (the excess above the
    /// threshold) can never underflow: `newTotal >= priorTotal` always
    /// (baseAmount is added, never subtracted), so `excessAfter >=
    /// excessBefore` always holds too. Reads all 3 knobs (threshold, flat
    /// fee, bps) via ONE packed `creationFeeParams()` call — 2 extra
    /// external calls would each cost real bytecode this contract can't
    ///
    /// Called once per "leg" of a capital-increasing call (see
    /// increasePosition()/increasePositionWithToken() above, which now call
    /// this twice — once for the stable leg, once for the volatile leg) —
    /// since the counter is purely cumulative, two sequential calls give
    /// exactly the same combined total as one call on the summed amount
    /// would, decomposed cleanly per leg, regardless of call order.
    ///
    /// every one of its 5 call sites (deposit, depositToken,
    /// increasePosition, increasePositionWithToken ×2, and
    /// _rebalanceCore's reinject block) is already inside a state-mutating,
    /// non-view function.
    function _creationFeeFor(uint256 baseAmount) internal returns (uint256 fee) {
        if (baseAmount == 0) return 0;

        (uint256 thresholdUsd, uint256 flatUsd, uint256 bps) = IPlatformConfig(platformConfig).creationFeeParams();

        uint256 priorTotal = cumulativeFeeableUsd;

        if (priorTotal == 0 && flatUsd > 0) fee = flatUsd;

        // unchecked: cumulativeFeeableUsd only ever grows by real deposit
        // amounts (USD-cents scale, nowhere near 2^256), and every
        // subtraction below is guarded by the ternary/order it sits next to
        // (newTotal >= priorTotal always) — first use of `unchecked` in this
        // anything else; see this file's own class docstring for the
        // bytecode-budget history.
        uint256 newTotal;
        uint256 tier2;
        unchecked {
            newTotal = priorTotal + baseAmount;
            uint256 excessAfter = newTotal > thresholdUsd ? newTotal - thresholdUsd : 0;
            uint256 excessBefore = priorTotal > thresholdUsd ? priorTotal - thresholdUsd : 0;
            tier2 = excessAfter - excessBefore;
        }
        cumulativeFeeableUsd = newTotal;
        if (tier2 > 0 && bps > 0) fee += (tier2 * bps) / 10_000;
    }

    function _payCreationFee(uint256 fee) internal {
        if (fee > 0) {
            IERC20(_stableAddr()).safeTransfer(IPlatformConfig(platformConfig).treasury(), fee);
            emit CreationFeeCharged(fee);
        }
    }

    /// @notice Shared by depositToken()/increasePositionWithToken() — sells
    /// 100% of a non-stable, non-volatile third-party token into the vault's
    /// own stable token via the generic swapRouter. Factored out purely to
    /// keep bytecode down (identical block in both), no behavior change.
    function _swapThirdPartyToStable(
        address tokenIn,
        uint256 amountIn,
        uint24 fee,
        uint256 amountOutMinimum,
        address stableAddr
    ) internal {
        IERC20(tokenIn).forceApprove(address(swapRouter), amountIn);
        _doExactInputSingle(tokenIn, stableAddr, fee, amountIn, amountOutMinimum);
    }

    function _stableAddr() internal view returns (address) {
        return stableIsToken0 ? token0 : token1;
    }

    function _volatileAddr() internal view returns (address) {
        return stableIsToken0 ? token1 : token0;
    }

    function _toToken01(uint256 stableAmt, uint256 volatileAmt) internal view returns (uint256, uint256) {
        return stableIsToken0 ? (stableAmt, volatileAmt) : (volatileAmt, stableAmt);
    }

    function _stableOf(uint256 amount0, uint256 amount1) internal view returns (uint256) {
        return stableIsToken0 ? amount0 : amount1;
    }

    /// swapIx sell the volatile leg for the stable leg" was duplicated
    /// identically in depositToken() and _convertPayoutToStable(); a third,
    /// new use in _finishIncreasePosition() (this version's own fix) made
    /// extracting it worth it, same discipline as every other 1-line helper
    /// already in this file. No behavior change at either existing call site.
    function _sellsVolatileForStable(SwapInstruction calldata swapIx) internal view returns (bool) {
        return stableIsToken0 ? !swapIx.token0ToToken1 : swapIx.token0ToToken1;
    }

    /// is genuinely available right now" measurement that used to be
    /// duplicated, with minor variations, across 6 call sites (initPosition,
    /// _rebalanceCore, reinjectIntoPosition, sweepIdleDust, _reinjectFees,
    /// _increaseLiquidityAndAccount). Needed to claw back the bytecode room
    /// refactor, no behavior change: `extraStableExclude`/
    /// `extraVolatileExclude` are the same additional exclusions each
    /// original call site already subtracted inline (0 where there was none).
    function _measureAvailable(uint256 extraStableExclude, uint256 extraVolatileExclude)
        internal
        view
        returns (uint256 stableBal, uint256 volatileBal)
    {
        stableBal =
            IERC20(_stableAddr()).balanceOf(address(this)) - reserveBalance - gasReserveBalance - extraStableExclude;
        volatileBal = IERC20(_volatileAddr()).balanceOf(address(this)) - extraVolatileExclude;
    }

    function _nativeWeiToStableRaw(uint256 volatileWei) internal view returns (uint256) {
        (uint160 sqrtPriceX96,,,,,,) = pool.slot0();
        if (stableIsToken0) {
            uint256 step1 = (volatileWei << 96) / sqrtPriceX96;
            return (step1 << 96) / sqrtPriceX96;
        } else {
            uint256 step1 = (volatileWei * sqrtPriceX96) >> 96;
            return (step1 * sqrtPriceX96) >> 96;
        }
    }

    /// @dev Values a pair of real token0/token1 amounts entirely in the
    /// stable leg's raw units, at the pool's CURRENT spot price — the stable
    /// leg passes through unchanged, the volatile leg goes through
    /// _nativeWeiToStableRaw. Shared by every B1 accounting event this
    /// contract emits (FeesReinjected.netFeeUsd, Withdrawn/
    /// EmergencyWithdraw.principalUsd) so both directions — capital entering
    /// the position (reinjection) and capital leaving it (withdrawal) — are
    /// valued the exact same way, at the exact moment each happens.
    function _toStableUsd(uint256 amount0, uint256 amount1) internal view returns (uint256) {
        uint256 stableRaw = _stableOf(amount0, amount1);
        uint256 volatileRaw = stableIsToken0 ? amount1 : amount0;
        return stableRaw + _nativeWeiToStableRaw(volatileRaw);
    }

    function _executeSwap(SwapInstruction calldata swapIx) internal {
        if (swapIx.amountIn == 0) return;
        if (swapIx.fee == 0) revert InvalidSwapInstruction();
        address tokenIn = swapIx.token0ToToken1 ? token0 : token1;
        address tokenOut = swapIx.token0ToToken1 ? token1 : token0;
        _doExactInputSingle(tokenIn, tokenOut, swapIx.fee, swapIx.amountIn, swapIx.amountOutMinimum);
    }

    /// (sqrtPriceLimitX96 always 0, recipient always this vault) was
    /// duplicated identically in _swapThirdPartyToStable() and
    /// _executeSwap() — factored out purely to keep bytecode down.
    /// Deliberately does NOT also own the forceApprove step, which differs
    /// genuinely between the two callers (see this contract's own class
    /// docstring, item 2, on why mixing the exact-approval and
    /// persistent-approval paths is a real bug class, not just a style
    /// choice) — no behavior change at either call site.
    function _doExactInputSingle(address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint256 amountOutMinimum)
        internal
    {
        swapRouter.exactInputSingle(
            ISwapRouter02.ExactInputSingleParams({
                tokenIn: tokenIn,
                tokenOut: tokenOut,
                fee: fee,
                recipient: address(this),
                amountIn: amountIn,
                amountOutMinimum: amountOutMinimum,
                sqrtPriceLimitX96: 0
            })
        );
    }

    function _checkRangeNearMarket(int24 tickLower, int24 tickUpper) internal view {
        (, int24 currentTick,,,,,) = pool.slot0();
        int256 slack = int256(maxRangeDeviationBps);
        int256 lowerBound = int256(tickLower) - slack;
        int256 upperBound = int256(tickUpper) + slack;
        int256 current = int256(currentTick);
        if (current < lowerBound || current > upperBound) revert RangeTooFarFromMarket();
    }

    function _isOutOfRange() internal view returns (bool) {
        (,,,,, int24 posTickLower, int24 posTickUpper, uint128 liquidity,,,,) =
            positionManager.positions(positionTokenId);
        if (liquidity == 0) return true;
        (, int24 currentTick,,,,,) = pool.slot0();
        return currentTick < posTickLower || currentTick > posTickUpper;
    }

    /// @notice Hard ceiling + hard floor, merged into one slot0() read (kept
    /// as 2 separate functions would cost more bytecode) — factored together
    /// purely to keep bytecode down, same discipline as the other shared
    /// helpers in this file. Direction-aware: a higher tick means a HIGHER
    /// price when stableIsToken0 is false (Arbitrum: token0=volatile,
    /// token1=stable — raw price token1/token0 rises with tick, and that raw
    /// price IS the stable-per-volatile price). A higher tick means a LOWER
    /// price when stableIsToken0 is true (Celo: token0=stable — the
    /// stable-per-volatile price is the INVERSE of the raw token1/token0
    /// price, so it falls as tick rises). Same direction logic this
    /// codebase's own off-chain keeper already uses for `floorTick` (see
    /// rebalancer.ts) — mirrored here on-chain rather than trusted from any
    /// caller, since this gate exists specifically so a misbehaving/
    /// compromised operator can't rebalance past the owner's configured
    /// ceiling/floor regardless of what it claims off-chain. The floor's
    /// comparison is the OPPOSITE of the ceiling's — do not copy operators
    /// unchanged between the two. Ceiling takes priority if both somehow
    /// read true in the same block (should be impossible in practice, and
    /// now additionally guarded at config time by _hardStopOrderValid()).
    function _hardStopTriggered() internal view returns (bool aboveCeiling, bool belowFloor) {
        if (!hardCeilingEnabled && !hardFloorEnabled) return (false, false);
        (, int24 currentTick,,,,,) = pool.slot0();
        aboveCeiling =
            hardCeilingEnabled && (stableIsToken0 ? currentTick <= hardCeilingTick : currentTick >= hardCeilingTick);
        belowFloor = !aboveCeiling && hardFloorEnabled
            && (stableIsToken0 ? currentTick >= hardFloorTick : currentTick <= hardFloorTick);
    }

    // ---------------------------------------------------------------------
    // ---------------------------------------------------------------------

    function onERC721Received(address, address, uint256, bytes calldata) external view returns (bytes4) {
        if (msg.sender != address(positionManager)) revert NotPositionManager();
        return this.onERC721Received.selector;
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuardUpgradeable is Initializable {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
    struct ReentrancyGuardStorage {
        uint256 _status;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
        assembly {
            $.slot := ReentrancyGuardStorageLocation
        }
    }

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        $._status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if ($._status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        $._status = ENTERED;
    }

    function _nonReentrantAfter() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        $._status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        return $._status == ENTERED;
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @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);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.20;

/**
 * @title ERC-721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC-721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

lib/openzeppelin-contracts/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Errors.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

lib/v3-core/contracts/interfaces/IUniswapV3Pool.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';

/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
    IUniswapV3PoolImmutables,
    IUniswapV3PoolState,
    IUniswapV3PoolDerivedState,
    IUniswapV3PoolActions,
    IUniswapV3PoolOwnerActions,
    IUniswapV3PoolEvents
{

}

lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolActions.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;

    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
    /// on tickLower, tickUpper, the amount of liquidity, and the current price.
    /// @param recipient The address for which the liquidity will be created
    /// @param tickLower The lower tick of the position in which to add liquidity
    /// @param tickUpper The upper tick of the position in which to add liquidity
    /// @param amount The amount of liquidity to mint
    /// @param data Any data that should be passed through to the callback
    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
    function mint(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Collects tokens owed to a position
    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
    /// @param recipient The address which should receive the fees collected
    /// @param tickLower The lower tick of the position for which to collect fees
    /// @param tickUpper The upper tick of the position for which to collect fees
    /// @param amount0Requested How much token0 should be withdrawn from the fees owed
    /// @param amount1Requested How much token1 should be withdrawn from the fees owed
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
    /// @dev Fees must be collected separately via a call to #collect
    /// @param tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
    /// with 0 amount{0,1} and sending the donation amount(s) from the callback
    /// @param recipient The address which will receive the token0 and token1 amounts
    /// @param amount0 The amount of token0 to send
    /// @param amount1 The amount of token1 to send
    /// @param data Any data to be passed through to the callback
    function flash(
        address recipient,
        uint256 amount0,
        uint256 amount1,
        bytes calldata data
    ) external;

    /// @notice Increase the maximum number of price and liquidity observations that this pool will store
    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
    /// the input observationCardinalityNext.
    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}

lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
    /// you must call it with secondsAgos = [3600, 0].
    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
    /// timestamp
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
    /// snapshot is taken and the second snapshot is taken.
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
        external
        view
        returns (
            int56 tickCumulativeInside,
            uint160 secondsPerLiquidityInsideX128,
            uint32 secondsInside
        );
}

lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolEvents.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
    event Initialize(uint160 sqrtPriceX96, int24 tick);

    /// @notice Emitted when liquidity is minted for a given position
    /// @param sender The address that minted the liquidity
    /// @param owner The owner of the position and recipient of any minted liquidity
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity minted to the position range
    /// @param amount0 How much token0 was required for the minted liquidity
    /// @param amount1 How much token1 was required for the minted liquidity
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted when fees are collected by the owner of a position
    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
    /// @param owner The owner of the position for which fees are collected
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount0 The amount of token0 fees collected
    /// @param amount1 The amount of token1 fees collected
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );

    /// @notice Emitted when a position's liquidity is removed
    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
    /// @param owner The owner of the position for which liquidity is removed
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity to remove
    /// @param amount0 The amount of token0 withdrawn
    /// @param amount1 The amount of token1 withdrawn
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted by the pool for any swaps between token0 and token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the output of the swap
    /// @param amount0 The delta of the token0 balance of the pool
    /// @param amount1 The delta of the token1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of price of the pool after the swap
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick
    );

    /// @notice Emitted by the pool for any flashes of token0/token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the tokens from flash
    /// @param amount0 The amount of token0 that was flashed
    /// @param amount1 The amount of token1 that was flashed
    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );

    /// @notice Emitted by the pool for increases to the number of observations that can be stored
    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
    /// just before a mint/swap/burn.
    /// @param observationCardinalityNextOld The previous value of the next observation cardinality
    /// @param observationCardinalityNextNew The updated value of the next observation cardinality
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld,
        uint16 observationCardinalityNextNew
    );

    /// @notice Emitted when the protocol fee is changed by the pool
    /// @param feeProtocol0Old The previous value of the token0 protocol fee
    /// @param feeProtocol1Old The previous value of the token1 protocol fee
    /// @param feeProtocol0New The updated value of the token0 protocol fee
    /// @param feeProtocol1New The updated value of the token1 protocol fee
    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);

    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
    /// @param sender The address that collects the protocol fees
    /// @param recipient The address that receives the collected protocol fees
    /// @param amount0 The amount of token0 protocol fees that is withdrawn
    /// @param amount0 The amount of token1 protocol fees that is withdrawn
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}

lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolImmutables.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token1() external view returns (address);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The pool tick spacing
    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
    /// This value is an int24 to avoid casting even though it is always positive.
    /// @return The tick spacing
    function tickSpacing() external view returns (int24);

    /// @notice The maximum amount of position liquidity that can use any tick in the range
    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
    /// @return The max amount of liquidity per tick
    function maxLiquidityPerTick() external view returns (uint128);
}

lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    /// @param feeProtocol0 new protocol fee for token0 of the pool
    /// @param feeProtocol1 new protocol fee for token1 of the pool
    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;

    /// @notice Collect the protocol fee accrued to the pool
    /// @param recipient The address to which collected protocol fees should be sent
    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
    /// @return amount0 The protocol fee collected in token0
    /// @return amount1 The protocol fee collected in token1
    function collectProtocol(
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);
}

lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolState.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
    /// when accessed externally.
    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
    /// tick The current tick of the pool, i.e. according to the last tick transition that was run.
    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
    /// boundary.
    /// observationIndex The index of the last oracle observation that was written,
    /// observationCardinality The current maximum number of observations stored in the pool,
    /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
    /// feeProtocol The protocol fee for both tokens of the pool.
    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
    /// unlocked Whether the pool is currently locked to reentrancy
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal0X128() external view returns (uint256);

    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal1X128() external view returns (uint256);

    /// @notice The amounts of token0 and token1 that are owed to the protocol
    /// @dev Protocol fees will never exceed uint128 max in either token
    function protocolFees() external view returns (uint128 token0, uint128 token1);

    /// @notice The currently in range liquidity available to the pool
    /// @dev This value has no relationship to the total liquidity across all ticks
    function liquidity() external view returns (uint128);

    /// @notice Look up information about a specific tick in the pool
    /// @param tick The tick to look up
    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
    /// tick upper,
    /// liquidityNet how much liquidity changes when the pool price crosses the tick,
    /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
    /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
    /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
    /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
    /// secondsOutside the seconds spent on the other side of the tick from the current tick,
    /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
    /// a specific position.
    function ticks(int24 tick)
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
    function tickBitmap(int16 wordPosition) external view returns (uint256);

    /// @notice Returns the information about a position by the position's key
    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
    /// @return _liquidity The amount of liquidity in the position,
    /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
    /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
    /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
    /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
    function positions(bytes32 key)
        external
        view
        returns (
            uint128 _liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    /// @notice Returns data about a specific observation index
    /// @param index The element of the observations array to fetch
    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
    /// ago, rather than at a specific index in the array.
    /// @return blockTimestamp The timestamp of the observation,
    /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
    /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
    /// Returns initialized whether the observation has been initialized and the values are safe to use
    function observations(uint256 index)
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );
}

src/interfaces/IAggregatorV3.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

/// @notice Minimal local copy of Chainlink's AggregatorV3Interface — only
/// the two functions RangeVaultArbCompoundV5 needs, same "write it locally
/// instead of pulling in a whole external package" discipline as
/// INonfungiblePositionManager.sol/ISwapRouter02.sol in this same directory.
interface IAggregatorV3 {
    function decimals() external view returns (uint8);

    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

src/interfaces/INonfungiblePositionManager.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.24;

/// @notice Minimal local copy of Uniswap V3's NonfungiblePositionManager interface —
/// only the functions this project needs. Written locally instead of importing the
/// Uniswap v3-periphery package, because that package's version of this interface
/// imports OpenZeppelin v3.x-era ERC721 interfaces (IERC721Metadata/IERC721Enumerable
/// at a path that no longer exists in OZ v5), which conflicts with the OZ version
/// this project uses elsewhere. The ABI below matches the real deployed contract.
interface INonfungiblePositionManager {
    struct MintParams {
        address token0;
        address token1;
        uint24 fee;
        int24 tickLower;
        int24 tickUpper;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        address recipient;
        uint256 deadline;
    }

    function mint(MintParams calldata params)
        external
        payable
        returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);

    struct DecreaseLiquidityParams {
        uint256 tokenId;
        uint128 liquidity;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    function decreaseLiquidity(DecreaseLiquidityParams calldata params)
        external
        payable
        returns (uint256 amount0, uint256 amount1);

    struct IncreaseLiquidityParams {
        uint256 tokenId;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    function increaseLiquidity(IncreaseLiquidityParams calldata params)
        external
        payable
        returns (uint128 liquidity, uint256 amount0, uint256 amount1);

    struct CollectParams {
        uint256 tokenId;
        address recipient;
        uint128 amount0Max;
        uint128 amount1Max;
    }

    function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);

    function positions(uint256 tokenId)
        external
        view
        returns (
            uint96 nonce,
            address operator,
            address token0,
            address token1,
            uint24 fee,
            int24 tickLower,
            int24 tickUpper,
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    function burn(uint256 tokenId) external payable;

    /// @notice Added for RangeVaultArbCompoundV5's rescuePosition() — the
    /// real deployed contract has this via ERC721 inheritance, but this
    /// local minimal copy never declared it before nothing here needed to
    /// move the NFT itself, only mint/decrease/increase/collect against it.
    /// rescuePosition() deliberately uses the RAW transferFrom below, not
    /// this one — see that function's own docstring (found during the
    /// pre-deploy audit: safeTransferFrom can revert if `owner` is a
    /// contract without onERC721Received, e.g. an EIP-7702-delegated
    /// address, confirmed live against a real such address on an Arbitrum
    /// fork — the last-resort rescue must never be blockable that way).
    /// Kept declared regardless in case a future caller genuinely wants the
    /// receiver-checked variant.
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /// @notice Raw ERC721 transfer, no onERC721Received check on `to`. See
    /// safeTransferFrom's own docstring for why rescuePosition() uses this
    /// one specifically.
    function transferFrom(address from, address to, uint256 tokenId) external;
}

src/interfaces/IPlatformConfig.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

/// @notice Read-only view a RangeVault needs from PlatformConfig. Kept as a narrow
/// interface (instead of importing the concrete contract) so RangeVault only depends
/// on the three values it actually reads live on every rebalance.
interface IPlatformConfig {
    function feeToken() external view returns (address);
    function defaultOperator() external view returns (address);
    function maxDepositUsd() external view returns (uint256);
    function performanceFeeBps() external view returns (uint256);
    function creationFeeUsdt() external view returns (uint256);
    /// @notice V4 only — the already-deployed shared PlatformConfig (V1-V3)
    /// predates this field and doesn't have it; V4 vaults point at their own
    /// PlatformConfig instance instead. See RangeVaultArbCompoundV4.sol's
    /// own docstring for why.
    function creationFeeBps() external view returns (uint256);
    function treasury() external view returns (address);
    /// @notice V6 only — same reasoning as creationFeeBps above: the
    /// already-deployed shared PlatformConfig (V1-V5) predates this field;
    /// V6 vaults point at their own fresh PlatformConfig instance instead.
    /// See RangeVaultArbCompoundV6.sol's operatorForceRebalance().
    function forceRebalanceCooldownSeconds() external view returns (uint256);
    /// @notice V7 only — packs the 3 reads RangeVaultArbCompoundV7's
    /// _creationFeeFor() needs (tier threshold, one-time flat fee, bracket-2
    /// bps) into a single external call, for bytecode/gas reasons (V7
    /// needed real structural trimming to fit under EIP-170). Only
    /// PlatformConfigV7 (and later) implements this — same "own fresh
    /// instance" reasoning as creationFeeBps/forceRebalanceCooldownSeconds
    /// above.
    function creationFeeParams() external view returns (uint256 thresholdUsd, uint256 flatUsd, uint256 bps);
    /// @notice V9 only — the platform's own pool of backup operator wallets,
    /// seeded into every new vault's isOperator mapping at creation time
    /// (see RangeVaultArbCompoundV9.sol's initialize()). Only
    /// PlatformConfigV9 (and later) implements this — same "own fresh
    /// instance" reasoning as every other version-gated field above.
    function operatorPool() external view returns (address[] memory);
}

src/interfaces/ISwapRouter02.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.24;

/// @notice Minimal local interface for Uniswap's SwapRouter02 (the router actually
/// deployed on Celo at 0x5615CDAb..., per Celopedia's verified contract list).
/// SwapRouter02 dropped the `deadline` field that the original v1 SwapRouter had —
/// this struct matches the real SwapRouter02 ABI, not the older v3-periphery one.
interface ISwapRouter02 {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "v3-core/=lib/v3-core/",
    "v3-periphery/=lib/v3-periphery/contracts/",
    "@uniswap/v3-core/=lib/v3-core/",
    "@uniswap/v3-periphery/=lib/v3-periphery/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.