Skip to content
Verified contractExactMIT

EkuboV3Connector

Address0xad28c23bfd39c49a6b906ab8375e3512480b0fd5
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.19

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.19+commit.7dd6d404
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,400,514
Creation transaction
0xfc492c6eb6…2050bbf7b4

contracts/connectors/ekubo/EkuboV3Connector.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

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

import {
    EkuboPoolKey,
    IEkuboPositions
} from "contracts/interfaces/external/ekubo/IEkuboPositions.sol";
import { EkuboLib } from "contracts/connectors/ekubo/EkuboLib.sol";
import {
    EkuboPosition,
    EkuboPositionRegistry
} from "contracts/connectors/ekubo/EkuboPositionRegistry.sol";
import { INftFarmConnector } from "contracts/interfaces/INftFarmConnector.sol";
import {
    INftLiquidityConnector,
    NftPoolInfo,
    NftPoolKey,
    NftPositionInfo
} from "contracts/interfaces/INftLiquidityConnector.sol";
import {
    NftAddLiquidity,
    NftRemoveLiquidity
} from "contracts/structs/NftLiquidityStructs.sol";
import { NftPosition } from "contracts/structs/NftFarmStrategyStructs.sol";

/// @notice `NftAddLiquidity.extraData` for a mint (`tokenId == 0`). The pool
/// key is (pool.token0, pool.token1, config) and must hash to `poolId`.
/// Increases ignore extraData: they reuse the recorded key and range.
struct EkuboAddLiquidityExtraData {
    bytes32 poolId;
    bytes32 config;
}

/// @title EkuboV3Connector
/// @notice NFT liquidity and farm connector for Ekubo v3 concentrated
/// liquidity positions (Core 0x00000000000014aA86C5d3c41765bb24e11bd701,
/// Positions 0x02D9876A21AF7545f8632C3af76eC90b5ad4b66D).
///
/// Tick units. Ekubo ticks are int32 powers of 1.000001 (±88,722,835), wider
/// than the int24 tick fields in the Sickle structs, settings and
/// automation. At this boundary every tick is expressed in TICK-SPACING
/// UNITS: ekuboTick = sickleTick * tickSpacing. `poolInfo` reports
/// tickSpacing = 1 and tick = floor(ekuboTick / tickSpacing); position ticks
/// are divided by the spacing and NftAddLiquidity ticks multiplied by it.
/// Range membership and spacing arithmetic, the only tick operations
/// ShiftMath and NftSettingsRegistry perform, are preserved exactly.
/// Uniswap tick-to-price math does not apply to these ticks: do not wire
/// Ekubo positions into consumers of it (NftLiquidityAmountsResolver /
/// NftFarmVault).
///
/// Position metadata. Ekubo NFTs store neither pool nor range, so mints
/// record them in EkuboPositionRegistry and every later action reads them
/// from there, never from caller-supplied data. `totalSupply` is the
/// registry's mint counter and `getTokenId` the caller's last recorded mint.
///
/// Farm role. Positions is its own staking contract: `depositExistingNft`
/// and `withdrawNft` are no-ops and `claim` collects swap fees.
///
/// Execution context. Mutators run under DELEGATECALL from a Sickle:
/// address(this) is the Sickle, which pays, owns the NFT and receives every
/// withdrawal. Only immutables are read; the registry is called normally.
contract EkuboV3Connector is INftLiquidityConnector, INftFarmConnector {
    error InvalidNftManager(address nft);
    error InvalidDesiredAmount();
    error InvalidParameters();
    error InvalidTokenOwner();
    error PoolIdMismatch(bytes32 expected, bytes32 actual);
    error PoolNotInitialized(bytes32 poolId);
    error PoolTokensMismatch(
        address token0, address token1, address expected0, address expected1
    );
    error PositionRangeMismatch(
        int32 tickLower,
        int32 tickUpper,
        int32 recordedLower,
        int32 recordedUpper
    );
    error LiquidityExceedsPosition(uint128 requested, uint128 current);
    error AmountBelowMinimum(uint256 index, uint256 amount, uint256 minimum);

    EkuboPositionRegistry public immutable registry;
    IEkuboPositions public immutable positions;
    address public immutable core;

    constructor(
        EkuboPositionRegistry registry_
    ) {
        registry = registry_;
        positions = registry_.positions();
        core = registry_.core();
    }

    /* INftLiquidityConnector mutators (delegatecalled by a Sickle) */

    function addLiquidity(
        NftAddLiquidity memory params
    ) external override {
        _requirePositions(address(params.nft));
        if (
            params.amount0Desired > type(uint128).max
                || params.amount1Desired > type(uint128).max
        ) {
            revert InvalidDesiredAmount();
        }

        EkuboPoolKey memory key;
        int32 tickLower;
        int32 tickUpper;
        if (params.tokenId == 0) {
            (key, tickLower, tickUpper) = _mintTarget(params);
        } else {
            (key, tickLower, tickUpper) = _increaseTarget(params);
        }

        bool native = key.token0 == address(0);
        uint256 before0 = _balance(key.token0);
        uint256 before1 = _balance(key.token1);

        bytes[] memory calls = new bytes[](native ? 2 : 1);
        bytes32 salt;
        if (params.tokenId == 0) {
            salt = registry.nextSalt();
            calls[0] = abi.encodeCall(
                IEkuboPositions.mintAndDepositWithSalt,
                (
                    salt,
                    key,
                    tickLower,
                    tickUpper,
                    uint128(params.amount0Desired),
                    uint128(params.amount1Desired),
                    0
                )
            );
        } else {
            calls[0] = abi.encodeCall(
                IEkuboPositions.deposit,
                (
                    params.tokenId,
                    key,
                    tickLower,
                    tickUpper,
                    uint128(params.amount0Desired),
                    uint128(params.amount1Desired),
                    0
                )
            );
        }
        if (native) {
            // Positions pays native token0 from its own balance and returns
            // what the deposit left unused in the same call.
            calls[1] = abi.encodeCall(IEkuboPositions.refundNativeToken, ());
        }
        positions.multicall{ value: native ? params.amount0Desired : 0 }(calls);

        _requireMinimum(0, _spent(key.token0, before0), params.amount0Min);
        _requireMinimum(1, _spent(key.token1, before1), params.amount1Min);

        if (params.tokenId == 0) {
            registry.record(
                positions.saltToId(address(this), salt),
                key,
                tickLower,
                tickUpper
            );
        }
    }

    /// @dev Ekubo's withdraw takes no minimum amounts, so they are enforced
    /// here on the balances the Sickle actually received. Fees are always
    /// collected with the liquidity (withFees), as a Uniswap v4 decrease
    /// does; the minimums apply to the total. Removing all liquidity burns
    /// the NFT.
    function removeLiquidity(
        NftRemoveLiquidity memory params
    ) external override {
        _requirePositions(address(params.nft));
        EkuboPosition memory p = registry.getPosition(params.tokenId);
        (uint128 current,,,,) = positions.getPositionFeesAndLiquidity(
            params.tokenId, p.poolKey, p.tickLower, p.tickUpper
        );
        uint128 liquidity =
            params.liquidity == type(uint128).max ? current : params.liquidity;
        if (liquidity == 0) {
            revert InvalidParameters();
        }
        if (liquidity > current) {
            revert LiquidityExceedsPosition(liquidity, current);
        }

        uint256 before0 = _balance(p.poolKey.token0);
        uint256 before1 = _balance(p.poolKey.token1);

        bool burn = liquidity == current;
        bytes[] memory calls = new bytes[](burn ? 2 : 1);
        calls[0] = abi.encodeCall(
            IEkuboPositions.withdraw,
            (
                params.tokenId,
                p.poolKey,
                p.tickLower,
                p.tickUpper,
                liquidity,
                address(this),
                true
            )
        );
        if (burn) {
            calls[1] = abi.encodeCall(IEkuboPositions.burn, (params.tokenId));
        }
        positions.multicall(calls);

        _requireMinimum(
            0, _received(p.poolKey.token0, before0), params.amount0Min
        );
        _requireMinimum(
            1, _received(p.poolKey.token1, before1), params.amount1Min
        );
    }

    /* INftFarmConnector (delegatecalled by a Sickle) */

    function depositExistingNft(
        NftPosition calldata, // position
        bytes calldata // extraData
    ) external override { }

    function withdrawNft(
        NftPosition calldata, // position
        bytes calldata // extraData
    ) external override { }

    /// @dev Collects the position's swap fees to the Sickle. Positions keeps
    /// SWAP_PROTOCOL_FEE_X64 of them.
    function claim(
        NftPosition calldata position,
        address[] memory, // rewardTokens
        uint128, // amount0Max
        uint128, // amount1Max
        bytes calldata // extraData
    ) external override {
        _requirePositions(address(position.nft));
        EkuboPosition memory p = registry.getPosition(position.tokenId);
        positions.collectFees(
            position.tokenId, p.poolKey, p.tickLower, p.tickUpper, address(this)
        );
    }

    function isStaked(
        address, // user
        NftPosition calldata // position
    ) external pure override returns (bool) {
        return false;
    }

    /// @dev Ekubo pays no incentive tokens through Positions.
    function earned(
        address, // user
        NftPosition calldata, // position
        address[] memory rewardTokens
    ) external pure override returns (uint256[] memory) {
        return new uint256[](rewardTokens.length);
    }

    /* Views */

    function fee(
        address, // pool
        uint256 tokenId
    ) external view override returns (uint24) {
        return EkuboLib.feeToUniswapUnits(
            registry.getPosition(tokenId).poolKey.config
        );
    }

    /// @dev `pool` is unused: Core is the only Ekubo pool contract.
    function poolInfo(
        address, // pool
        bytes32 poolId
    ) external view override returns (NftPoolInfo memory info) {
        EkuboPoolKey memory key = registry.getPoolKey(poolId);
        uint32 spacing = EkuboLib.supportedTickSpacing(key.config);
        (uint96 sqrtRatio, int32 tick, uint128 liquidity) =
            EkuboLib.poolState(core, poolId);
        (uint256 fees0, uint256 fees1) = EkuboLib.feesPerLiquidity(core, poolId);
        info = NftPoolInfo({
            token0: key.token0,
            token1: key.token1,
            fee: EkuboLib.feeToUniswapUnits(key.config),
            tickSpacing: 1,
            sqrtPriceX96: EkuboLib.sqrtRatioToX96(sqrtRatio),
            tick: EkuboLib.toSickleTick(tick, spacing),
            liquidity: liquidity,
            feeGrowthGlobal0X128: fees0,
            feeGrowthGlobal1X128: fees1
        });
    }

    function positionLiquidity(
        address, // nftManager
        uint256 tokenId
    )
        public
        view
        override
        returns (int24 tickLower, int24 tickUpper, uint128 liquidity)
    {
        EkuboPosition memory p = registry.getPosition(tokenId);
        uint32 spacing = EkuboLib.supportedTickSpacing(p.poolKey.config);
        (liquidity,,,,) = positions.getPositionFeesAndLiquidity(
            tokenId, p.poolKey, p.tickLower, p.tickUpper
        );
        tickLower = EkuboLib.toSickleTick(p.tickLower, spacing);
        tickUpper = EkuboLib.toSickleTick(p.tickUpper, spacing);
    }

    function positionInfo(
        address nftManager,
        uint256 tokenId
    ) external view override returns (NftPositionInfo memory) {
        (int24 tickLower, int24 tickUpper, uint128 liquidity) =
            positionLiquidity(nftManager, tokenId);
        return NftPositionInfo({
            liquidity: liquidity, tickLower: tickLower, tickUpper: tickUpper
        });
    }

    function positionPoolKey(
        address, // poolFactory
        address, // nftManager
        uint256 tokenId
    ) external view override returns (NftPoolKey memory) {
        return NftPoolKey({
            poolAddress: core,
            poolId: EkuboLib.poolId(registry.getPosition(tokenId).poolKey)
        });
    }

    /// @dev Swap fees owed to the position, net of the share Positions keeps
    /// at collection. Excludes fees an extension holds pending and has not
    /// yet donated to the pool: SignedExclusiveSwap donates a timestamp's
    /// fees on the pool's first touch at a later timestamp.
    function earnedFees(
        address, // nftManager
        address, // pool
        uint256 tokenId
    ) external view override returns (uint256 fees0, uint256 fees1) {
        EkuboPosition memory p = registry.getPosition(tokenId);
        (,,, uint128 owed0, uint128 owed1) = positions.getPositionFeesAndLiquidity(
            tokenId, p.poolKey, p.tickLower, p.tickUpper
        );
        uint64 protocolFee = positions.SWAP_PROTOCOL_FEE_X64();
        fees0 = owed0 - EkuboLib.computeFee(owed0, protocolFee);
        fees1 = owed1 - EkuboLib.computeFee(owed1, protocolFee);
    }

    function getTokenId(
        address, // nftManager
        address owner
    ) external view override returns (uint256 tokenId) {
        tokenId = registry.lastTokenId(owner);
        if (tokenId == 0 || positions.ownerOf(tokenId) != owner) {
            revert InvalidTokenOwner();
        }
    }

    /// @dev The registry's mint counter: it rises by one per connector mint
    /// and never falls, like Uniswap v4's nextTokenId() - 1, so deposit's
    /// supply-increase and increase/decrease/compound's supply-unchanged
    /// checks keep their meaning.
    function totalSupply(
        address // nftManager
    ) external view override returns (uint256) {
        return registry.mintCount();
    }

    /* Internal */

    function _mintTarget(
        NftAddLiquidity memory params
    )
        private
        view
        returns (EkuboPoolKey memory key, int32 tickLower, int32 tickUpper)
    {
        EkuboAddLiquidityExtraData memory
            extra = abi.decode(params.extraData, (EkuboAddLiquidityExtraData));
        key = EkuboPoolKey({
            token0: params.pool.token0,
            token1: params.pool.token1,
            config: extra.config
        });
        bytes32 id = EkuboLib.poolId(key);
        if (id != extra.poolId) {
            revert PoolIdMismatch(extra.poolId, id);
        }
        uint32 spacing = EkuboLib.supportedTickSpacing(key.config);
        if (!EkuboLib.isInitialized(core, id)) {
            revert PoolNotInitialized(id);
        }
        tickLower = EkuboLib.toEkuboTick(params.tickLower, spacing);
        tickUpper = EkuboLib.toEkuboTick(params.tickUpper, spacing);
    }

    function _increaseTarget(
        NftAddLiquidity memory params
    )
        private
        view
        returns (EkuboPoolKey memory key, int32 tickLower, int32 tickUpper)
    {
        EkuboPosition memory p = registry.getPosition(params.tokenId);
        key = p.poolKey;
        if (
            params.pool.token0 != key.token0 || params.pool.token1 != key.token1
        ) {
            revert PoolTokensMismatch(
                params.pool.token0, params.pool.token1, key.token0, key.token1
            );
        }
        uint32 spacing = EkuboLib.supportedTickSpacing(key.config);
        tickLower = EkuboLib.toEkuboTick(params.tickLower, spacing);
        tickUpper = EkuboLib.toEkuboTick(params.tickUpper, spacing);
        if (tickLower != p.tickLower || tickUpper != p.tickUpper) {
            revert PositionRangeMismatch(
                tickLower, tickUpper, p.tickLower, p.tickUpper
            );
        }
    }

    function _requirePositions(
        address nft
    ) private view {
        if (nft != address(positions)) {
            revert InvalidNftManager(nft);
        }
    }

    function _balance(
        address token
    ) private view returns (uint256) {
        return token == address(0)
            ? address(this).balance
            : IERC20(token).balanceOf(address(this));
    }

    function _spent(
        address token,
        uint256 before
    ) private view returns (uint256) {
        uint256 current = _balance(token);
        return before > current ? before - current : 0;
    }

    function _received(
        address token,
        uint256 before
    ) private view returns (uint256) {
        uint256 current = _balance(token);
        return current > before ? current - before : 0;
    }

    function _requireMinimum(
        uint256 index,
        uint256 amount,
        uint256 minimum
    ) private pure {
        if (amount < minimum) {
            revert AmountBelowMinimum(index, amount, minimum);
        }
    }
}

contracts/connectors/ekubo/EkuboLib.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import {
    EkuboPoolKey
} from "contracts/interfaces/external/ekubo/IEkuboPositions.sol";

/// @notice Ekubo v3 encodings shared by EkuboPositionRegistry and
/// EkuboV3Connector. Each helper restates one definition from
/// EkuboProtocol/evm-contracts (pinned at acf5e95, the source verified for
/// the deployed Core and Positions); the file cited is the authority.
library EkuboLib {
    /// @dev `math/constants.sol` MIN_TICK / MAX_TICK. Ticks are powers of
    /// 1.000001, unlike Uniswap's 1.0001.
    int256 internal constant MIN_TICK = -88_722_835;
    int256 internal constant MAX_TICK = 88_722_835;

    /// @dev The smallest concentrated tick spacing whose scaled ticks fit the
    /// Sickle structs' int24 fields: MAX_TICK / 11 = 8_065_712 <= 2^23 - 1,
    /// while MAX_TICK / 10 = 8_872_283 does not fit.
    uint32 internal constant MIN_SUPPORTED_TICK_SPACING = 11;

    /// @dev `IExposedStorage.sload()`: Core reads raw 32-byte slots appended
    /// to the selector and returns them unencoded (`base/ExposedStorage.sol`).
    bytes4 internal constant SLOAD_SELECTOR = 0x380eb4e0;

    /// @dev `libraries/CoreStorageLayout.sol` FPL_OFFSET: the pool's global
    /// fees per liquidity live at poolId + FPL_OFFSET and the next slot.
    uint256 internal constant FPL_OFFSET =
        0xb09b03866d96933565a9435bfb511c8ac5b2be454285ca331201452704799f72;

    /// @dev `types/sqrtRatio.sol` BIT_MASK: the two exponent bits of the
    /// 96-bit float.
    uint256 internal constant SQRT_RATIO_BIT_MASK = 0xc00000000000000000000000;

    error CoreReadFailed();
    error StableswapPoolNotSupported(bytes32 config);
    error TickSpacingNotSupported(uint32 tickSpacing);
    error TickOutOfRange(int256 tick);
    error SqrtPriceX96Overflow(uint256 sqrtRatioFixed);

    /// @dev `types/poolKey.sol` toPoolId: keccak256 of the 96-byte key.
    function poolId(
        EkuboPoolKey memory key
    ) internal pure returns (bytes32) {
        return keccak256(abi.encode(key.token0, key.token1, key.config));
    }

    /// @dev `types/poolConfig.sol` fee(): bits 32-95, a fraction of 2^64.
    function fee(
        bytes32 config
    ) internal pure returns (uint64) {
        return uint64(uint256(config) >> 32);
    }

    /// @dev Converts the 2^64-based pool fee to the Uniswap uint24 convention
    /// (1e6 = 100%) that `INftLiquidityConnector.fee` reports. Rounds down.
    function feeToUniswapUnits(
        bytes32 config
    ) internal pure returns (uint24) {
        return uint24((uint256(fee(config)) * 1e6) >> 64);
    }

    /// @dev `types/poolConfig.sol`: bit 31 set marks a concentrated pool and
    /// bits 0-30 hold its tick spacing. Rejects stableswap/full-range configs
    /// and spacings whose scaled ticks would overflow int24.
    function supportedTickSpacing(
        bytes32 config
    ) internal pure returns (uint32 spacing) {
        if (uint256(config) & 0x80000000 == 0) {
            revert StableswapPoolNotSupported(config);
        }
        spacing = uint32(uint256(config) & 0x7fffffff);
        if (spacing < MIN_SUPPORTED_TICK_SPACING) {
            revert TickSpacingNotSupported(spacing);
        }
    }

    /// @dev A Sickle tick is an Ekubo tick in tick-spacing units:
    /// ekuboTick = sickleTick * spacing. Ekubo validates alignment itself;
    /// this checks the protocol bounds so int32 cannot wrap.
    function toEkuboTick(
        int24 sickleTick,
        uint32 spacing
    ) internal pure returns (int32) {
        int256 tick = int256(sickleTick) * int256(uint256(spacing));
        if (tick < MIN_TICK || tick > MAX_TICK) {
            revert TickOutOfRange(tick);
        }
        return int32(tick);
    }

    /// @dev floor(ekuboTick / spacing). For a position bound (always a
    /// multiple of the spacing) this is exact. For the pool tick it keeps
    /// range membership: with aligned bounds a * s <= t < b * s holds exactly
    /// when a <= floor(t / s) < b. Fits int24 for every supported spacing.
    function toSickleTick(
        int32 ekuboTick,
        uint32 spacing
    ) internal pure returns (int24) {
        int256 s = int256(uint256(spacing));
        int256 q = int256(ekuboTick) / s;
        if (ekuboTick < 0 && int256(ekuboTick) % s != 0) {
            q -= 1;
        }
        return int24(q);
    }

    /// @dev `types/sqrtRatio.sol` toFixed: the 96-bit float as a 64.128
    /// fixed point number, i.e. sqrt(token1 / token0) * 2^128.
    function sqrtRatioToFixed(
        uint96 sqrtRatio
    ) internal pure returns (uint256) {
        uint256 raw = uint256(sqrtRatio);
        uint256 shift = 2 + ((raw & SQRT_RATIO_BIT_MASK) >> 89);
        return (raw & ~SQRT_RATIO_BIT_MASK) << shift;
    }

    /// @dev Uniswap's sqrtPriceX96 is the 64.128 value shifted down by 32.
    /// Near Ekubo's MAX_SQRT_RATIO it needs more than 160 bits; revert rather
    /// than truncate a price bound into a wrong one.
    function sqrtRatioToX96(
        uint96 sqrtRatio
    ) internal pure returns (uint160) {
        uint256 fixed128 = sqrtRatioToFixed(sqrtRatio);
        uint256 x96 = fixed128 >> 32;
        if (x96 > type(uint160).max) {
            revert SqrtPriceX96Overflow(fixed128);
        }
        return uint160(x96);
    }

    /// @dev `math/fee.sol` computeFee: amount * fee / 2^64, rounded up. This
    /// is how Positions takes SWAP_PROTOCOL_FEE_X64 from collected fees.
    function computeFee(
        uint128 amount,
        uint64 feeX64
    ) internal pure returns (uint128) {
        return uint128(
            (uint256(amount) * uint256(feeX64) + 0xffffffffffffffff) >> 64
        );
    }

    function sload(
        address core,
        uint256 slot
    ) internal view returns (bytes32 value) {
        (bool ok, bytes memory data) =
            core.staticcall(abi.encodePacked(SLOAD_SELECTOR, slot));
        if (!ok || data.length != 32) revert CoreReadFailed();
        value = bytes32(data);
    }

    /// @dev `types/poolState.sol`: sqrtRatio (96 bits) | tick (int32) |
    /// liquidity (128 bits), stored at slot = poolId. Zero means the pool
    /// was never initialized.
    function poolState(
        address core,
        bytes32 id
    ) internal view returns (uint96 sqrtRatio, int32 tick, uint128 liquidity) {
        uint256 state = uint256(sload(core, uint256(id)));
        sqrtRatio = uint96(state >> 160);
        tick = int32(uint32(state >> 128));
        liquidity = uint128(state);
    }

    function isInitialized(
        address core,
        bytes32 id
    ) internal view returns (bool) {
        return sload(core, uint256(id)) != bytes32(0);
    }

    /// @dev `libraries/CoreLib.sol` getPoolFeesPerLiquidity: Q128 fees per
    /// unit of liquidity, Uniswap's feeGrowthGlobalX128 equivalent.
    function feesPerLiquidity(
        address core,
        bytes32 id
    ) internal view returns (uint256 value0, uint256 value1) {
        uint256 slot;
        unchecked {
            slot = uint256(id) + FPL_OFFSET;
            value0 = uint256(sload(core, slot));
            value1 = uint256(sload(core, slot + 1));
        }
    }
}

contracts/connectors/ekubo/EkuboPositionRegistry.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import {
    EkuboPoolKey,
    IEkuboPositions
} from "contracts/interfaces/external/ekubo/IEkuboPositions.sol";
import { EkuboLib } from "contracts/connectors/ekubo/EkuboLib.sol";

/// @notice The Ekubo v3 range a Positions NFT holds: one (poolKey, ticks)
/// pair, in Ekubo's own int32 tick units.
struct EkuboPosition {
    EkuboPoolKey poolKey;
    int32 tickLower;
    int32 tickUpper;
}

/// @title EkuboPositionRegistry
/// @notice Position metadata that Ekubo v3 Positions NFTs do not store.
/// @dev An Ekubo NFT carries no pool or range: a position is (id, poolKey,
/// tickLower, tickUpper), and one id may hold several of them. Its ids are
/// salt hashes, and the NFT is neither enumerable nor counted. The Sickle
/// interfaces, however, address a position by NFT id alone and detect mints
/// through a supply counter.
///
/// This registry fills that gap. It is called normally, never
/// delegatecalled: EkuboV3Connector, running inside a Sickle, calls
/// `record` right after minting, so `msg.sender` is the Sickle that owns
/// the NFT. Every record is checked against the protocol, not taken on the
/// caller's word: the caller must own the NFT, and Core must hold nonzero
/// liquidity for exactly that (id, poolKey, range).
///
/// Records are write-once, so an id never moves to another range. Keeping
/// them outside the connector lets a connector redeploy reuse them.
///
/// Only NFTs minted through the connector are recorded. An Ekubo NFT minted
/// elsewhere has no record, and the connector's views revert for it.
contract EkuboPositionRegistry {
    error PositionAlreadyRecorded(uint256 tokenId);
    error PositionNotRecorded(uint256 tokenId);
    error PoolNotRegistered(bytes32 poolId);
    error PoolNotInitialized(bytes32 poolId);
    error NotPositionOwner(uint256 tokenId, address owner, address caller);
    error PositionHasNoLiquidity(uint256 tokenId);

    /// @notice A pool key became resolvable from its id.
    event PoolRegistered(
        bytes32 indexed poolId, address token0, address token1, bytes32 config
    );

    /// @notice An NFT was bound to its pool and range. `mintIndex` is the
    /// value of `mintCount` after this record.
    event PositionRecorded(
        uint256 indexed tokenId,
        address indexed owner,
        bytes32 indexed poolId,
        int32 tickLower,
        int32 tickUpper,
        uint256 mintIndex
    );

    IEkuboPositions public immutable positions;
    address public immutable core;

    /// @notice Number of positions recorded. Never decreases; the Sickle
    /// strategies read it as the NFT supply.
    uint256 public mintCount;

    /// @notice The last NFT each owner recorded.
    mapping(address => uint256) public lastTokenId;

    /// @dev Presence is token1 != 0: Ekubo requires token0 < token1, so a
    /// real key never has a zero token1, whereas config 0 is a valid
    /// (full-range, fee-free, extensionless) pool.
    mapping(uint256 => EkuboPosition) private _positions;
    mapping(bytes32 => EkuboPoolKey) private _poolKeys;

    constructor(
        IEkuboPositions positions_,
        address core_
    ) {
        positions = positions_;
        core = core_;
    }

    /// @notice Salt for the next connector mint. Each salt is used by at most
    /// one recorded mint, so with Positions' id = keccak(minter, salt,
    /// chainId, Positions) the id is unique and known before the mint.
    function nextSalt() external view returns (bytes32) {
        return bytes32(mintCount + 1);
    }

    /// @notice Bind `tokenId`, owned by the caller, to its pool and range.
    function record(
        uint256 tokenId,
        EkuboPoolKey calldata poolKey,
        int32 tickLower,
        int32 tickUpper
    ) external returns (uint256 mintIndex) {
        if (_positions[tokenId].poolKey.token1 != address(0)) {
            revert PositionAlreadyRecorded(tokenId);
        }
        address owner = positions.ownerOf(tokenId);
        if (owner != msg.sender) {
            revert NotPositionOwner(tokenId, owner, msg.sender);
        }
        (uint128 liquidity,,,,) = positions.getPositionFeesAndLiquidity(
            tokenId, poolKey, tickLower, tickUpper
        );
        if (liquidity == 0) {
            revert PositionHasNoLiquidity(tokenId);
        }
        bytes32 id = _registerPool(poolKey);

        _positions[tokenId] = EkuboPosition({
            poolKey: poolKey, tickLower: tickLower, tickUpper: tickUpper
        });
        mintIndex = ++mintCount;
        lastTokenId[msg.sender] = tokenId;

        emit PositionRecorded(
            tokenId, msg.sender, id, tickLower, tickUpper, mintIndex
        );
    }

    /// @notice Make an initialized pool resolvable from its id. The id is the
    /// key's hash, so anyone may register any initialized pool.
    function registerPool(
        EkuboPoolKey calldata poolKey
    ) external returns (bytes32) {
        return _registerPool(poolKey);
    }

    function getPosition(
        uint256 tokenId
    ) external view returns (EkuboPosition memory position) {
        position = _positions[tokenId];
        if (position.poolKey.token1 == address(0)) {
            revert PositionNotRecorded(tokenId);
        }
    }

    function isRecorded(
        uint256 tokenId
    ) external view returns (bool) {
        return _positions[tokenId].poolKey.token1 != address(0);
    }

    function getPoolKey(
        bytes32 poolId
    ) external view returns (EkuboPoolKey memory poolKey) {
        poolKey = _poolKeys[poolId];
        if (poolKey.token1 == address(0)) {
            revert PoolNotRegistered(poolId);
        }
    }

    function _registerPool(
        EkuboPoolKey memory poolKey
    ) private returns (bytes32 id) {
        id = EkuboLib.poolId(poolKey);
        if (_poolKeys[id].token1 != address(0)) {
            return id;
        }
        if (!EkuboLib.isInitialized(core, id)) {
            revert PoolNotInitialized(id);
        }
        _poolKeys[id] = poolKey;
        emit PoolRegistered(id, poolKey.token0, poolKey.token1, poolKey.config);
    }
}

contracts/interfaces/INftFarmConnector.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { NftPosition } from "contracts/structs/NftFarmStrategyStructs.sol";

interface INftFarmConnector {
    function depositExistingNft(
        NftPosition calldata position,
        bytes calldata extraData
    ) external;

    function withdrawNft(
        NftPosition calldata position,
        bytes calldata extraData
    ) external;

    function claim(
        NftPosition calldata position,
        address[] memory rewardTokens,
        uint128 maxAmount0, // For collecting
        uint128 maxAmount1,
        bytes calldata extraData
    ) external;

    function earned(
        address user,
        NftPosition calldata position,
        address[] memory rewardTokens
    ) external view returns (uint256[] memory);

    function isStaked(
        address user,
        NftPosition calldata position
    ) external view returns (bool);
}

contracts/interfaces/INftLiquidityConnector.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {
    NftAddLiquidity,
    NftRemoveLiquidity,
    NftPoolKey,
    NftPoolInfo,
    NftPositionInfo
} from "contracts/structs/NftLiquidityStructs.sol";

interface INftLiquidityConnector {
    function addLiquidity(
        NftAddLiquidity memory addLiquidityParams
    ) external;

    function removeLiquidity(
        NftRemoveLiquidity memory removeLiquidityParams
    ) external;

    function fee(
        address pool,
        uint256 tokenId // Used by UniswapV4
    ) external view returns (uint24);

    function totalSupply(
        address nftManager
    ) external view returns (uint256);

    function getTokenId(
        address nftManager,
        address owner
    ) external view returns (uint256);

    function earnedFees(
        address nftManager,
        address pool,
        uint256 tokenId
    ) external view returns (uint256 fees0, uint256 fees1);

    function positionLiquidity(
        address nftManager,
        uint256 tokenId
    )
        external
        view
        returns (int24 tickLower, int24 tickUpper, uint128 liquidity);

    function positionPoolKey(
        address poolFactory,
        address nftManager,
        uint256 tokenId
    ) external view returns (NftPoolKey memory);

    function poolInfo(
        address pool,
        bytes32 poolId
    ) external view returns (NftPoolInfo memory);

    // Maintained for backwards compatibility with NftSettingsRegistry
    function positionInfo(
        address nftManager,
        uint256 tokenId
    ) external view returns (NftPositionInfo memory);
}

contracts/interfaces/external/ekubo/IEkuboPositions.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @notice Ekubo v3 pool key, as `src/types/poolKey.sol` defines it.
/// `config` packs extension (bits 96-255), fee (u64, bits 32-95) and the pool
/// type (bits 0-31: bit 31 set = concentrated, bits 0-30 = tick spacing).
/// Ekubo encodes native ETH as token0 = address(0).
struct EkuboPoolKey {
    address token0;
    address token1;
    bytes32 config;
}

/// @notice The subset of Ekubo v3 `Positions` (`src/Positions.sol`,
/// `src/base/BasePositions.sol`, `src/base/BaseNonfungibleToken.sol`,
/// `src/base/PayableMulticallable.sol`) that the Sickle integration uses. The
/// signatures match the Etherscan-verified source of
/// 0x02D9876A21AF7545f8632C3af76eC90b5ad4b66D, which is the same address on
/// every Ekubo chain.
interface IEkuboPositions {
    function mintAndDepositWithSalt(
        bytes32 salt,
        EkuboPoolKey memory poolKey,
        int32 tickLower,
        int32 tickUpper,
        uint128 maxAmount0,
        uint128 maxAmount1,
        uint128 minLiquidity
    )
        external
        payable
        returns (
            uint256 id,
            uint128 liquidity,
            uint128 amount0,
            uint128 amount1
        );

    function deposit(
        uint256 id,
        EkuboPoolKey memory poolKey,
        int32 tickLower,
        int32 tickUpper,
        uint128 maxAmount0,
        uint128 maxAmount1,
        uint128 minLiquidity
    )
        external
        payable
        returns (uint128 liquidity, uint128 amount0, uint128 amount1);

    function withdraw(
        uint256 id,
        EkuboPoolKey memory poolKey,
        int32 tickLower,
        int32 tickUpper,
        uint128 liquidity,
        address recipient,
        bool withFees
    ) external payable returns (uint128 amount0, uint128 amount1);

    function collectFees(
        uint256 id,
        EkuboPoolKey memory poolKey,
        int32 tickLower,
        int32 tickUpper,
        address recipient
    ) external payable returns (uint128 amount0, uint128 amount1);

    function getPositionFeesAndLiquidity(
        uint256 id,
        EkuboPoolKey memory poolKey,
        int32 tickLower,
        int32 tickUpper
    )
        external
        view
        returns (
            uint128 liquidity,
            uint128 principal0,
            uint128 principal1,
            uint128 fees0,
            uint128 fees1
        );

    function burn(
        uint256 id
    ) external payable;

    function saltToId(
        address minter,
        bytes32 salt
    ) external view returns (uint256 id);

    function ownerOf(
        uint256 id
    ) external view returns (address owner);

    function multicall(
        bytes[] calldata data
    ) external payable returns (bytes[] memory results);

    function refundNativeToken() external payable;

    /// @notice Share of collected swap fees Positions keeps, as a fraction of
    /// 2^64 (immutable).
    function SWAP_PROTOCOL_FEE_X64() external view returns (uint64);
}

contracts/interfaces/external/uniswap/INonfungiblePositionManager.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { IERC721Enumerable } from
    "openzeppelin-contracts/contracts/interfaces/IERC721Enumerable.sol";

interface INonfungiblePositionManager is IERC721Enumerable {
    struct IncreaseLiquidityParams {
        uint256 tokenId;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    struct MintParams {
        address token0;
        address token1;
        uint24 fee;
        int24 tickLower;
        int24 tickUpper;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        address recipient;
        uint256 deadline;
    }

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

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

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

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

    function mint(
        MintParams memory params
    )
        external
        payable
        returns (uint256 tokenId, uint256 amount0, uint256 amount1);

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

    function burn(
        uint256 tokenId
    ) external payable;

    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 factory() external view returns (address);
}

contracts/interfaces/external/uniswap/IUniswapV3Pool.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);
}

/// @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
    /// @return 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.
    /// @return observationIndex The index of the last oracle observation that
    /// was written,
    /// @return observationCardinality The current maximum number of
    /// observations stored in the pool,
    /// @return observationCardinalityNext The next maximum number of
    /// observations, to be updated when the observation.
    /// @return 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
    /// @return The liquidity at the current price of the pool
    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
    /// @return liquidityNet how much liquidity changes when the pool price
    /// crosses the tick,
    /// @return feeGrowthOutside0X128 the fee growth on the other side of the
    /// tick from the current tick in token0,
    /// @return feeGrowthOutside1X128 the fee growth on the other side of the
    /// tick from the current tick in token1,
    /// @return tickCumulativeOutside the cumulative tick value on the other
    /// side of the tick from the current tick
    /// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity
    /// on the other side of the tick from the current tick,
    /// @return secondsOutside the seconds spent on the other side of the tick
    /// from the current tick,
    /// @return 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,
    /// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick
    /// range as of the last mint/burn/poke,
    /// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick
    /// range as of the last mint/burn/poke,
    /// @return tokensOwed0 the computed amount of token0 owed to the position
    /// as of the last mint/burn/poke,
    /// @return 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,
    /// @return tickCumulative the tick multiplied by seconds elapsed for the
    /// life of the pool as of the observation timestamp,
    /// @return secondsPerLiquidityCumulativeX128 the seconds per in range
    /// liquidity for the life of the pool as of the observation timestamp,
    /// @return 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
        );

    function observe(
        uint32[] calldata secondsAgos
    )
        external
        view
        returns (
            int56[] memory tickCumulatives,
            uint160[] memory secondsPerLiquidityCumulativeX128s
        );
}

interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState {
    function flash(
        address recipient,
        uint256 amount0,
        uint256 amount1,
        bytes calldata data
    ) external;

    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);
}

contracts/structs/FarmStrategyStructs.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import { ZapIn, ZapOut } from "contracts/structs/ZapStructs.sol";
import { SwapParams } from "contracts/structs/SwapStructs.sol";

struct Farm {
    address stakingContract;
    uint256 poolIndex;
}

struct DepositParams {
    Farm farm;
    address[] tokensIn;
    uint256[] amountsIn;
    ZapIn zap;
    bytes extraData;
}

struct WithdrawParams {
    bytes extraData;
    ZapOut zap;
    address[] tokensOut;
}

struct HarvestParams {
    SwapParams[] swaps;
    bytes extraData;
    address[] tokensOut;
}

struct CompoundParams {
    Farm claimFarm;
    bytes claimExtraData;
    address[] rewardTokens;
    ZapIn zap;
    Farm depositFarm;
    bytes depositExtraData;
}

struct SimpleDepositParams {
    Farm farm;
    address lpToken;
    uint256 amountIn;
    bytes extraData;
}

struct SimpleHarvestParams {
    address[] rewardTokens;
    bytes extraData;
}

struct SimpleWithdrawParams {
    address lpToken;
    uint256 amountOut;
    bytes extraData;
}

contracts/structs/LiquidityStructs.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

struct AddLiquidityParams {
    address router;
    address lpToken;
    address[] tokens;
    uint256[] desiredAmounts;
    uint256[] minAmounts;
    bytes extraData;
}

struct RemoveLiquidityParams {
    address router;
    address lpToken;
    address[] tokens;
    uint256 lpAmountIn;
    uint256[] minAmountsOut;
    bytes extraData;
}

contracts/structs/NftFarmStrategyStructs.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import { IUniswapV3Pool } from
    "contracts/interfaces/external/uniswap/IUniswapV3Pool.sol";
import { INonfungiblePositionManager } from
    "contracts/interfaces/external/uniswap/INonfungiblePositionManager.sol";
import { NftZapIn, NftZapOut } from "contracts/structs/NftZapStructs.sol";
import { SwapParams } from "contracts/structs/SwapStructs.sol";
import { Farm } from "contracts/structs/FarmStrategyStructs.sol";

struct NftPosition {
    Farm farm;
    INonfungiblePositionManager nft;
    uint256 tokenId;
}

struct NftIncrease {
    address[] tokensIn;
    uint256[] amountsIn;
    NftZapIn zap;
    bytes extraData;
}

struct NftDeposit {
    Farm farm;
    INonfungiblePositionManager nft;
    NftIncrease increase;
}

struct NftWithdraw {
    NftZapOut zap;
    address[] tokensOut;
    bytes extraData;
}

struct SimpleNftHarvest {
    address[] rewardTokens;
    uint128 amount0Max;
    uint128 amount1Max;
    bytes extraData;
}

struct NftHarvest {
    SimpleNftHarvest harvest;
    SwapParams[] swaps;
    address[] outputTokens;
    address[] sweepTokens;
}

struct NftCompound {
    SimpleNftHarvest harvest;
    NftZapIn zap;
}

struct NftRebalance {
    IUniswapV3Pool pool;
    NftPosition position;
    NftHarvest harvest;
    NftWithdraw withdraw;
    NftIncrease increase;
}

/// @notice The pool price a keeper-built rebalance is valid for: the
/// inclusive sqrtPriceX96 window in which the add step's `amount0Min` /
/// `amount1Min` can still be met. `boundedRebalanceFor` reverts before
/// the harvest/withdraw/swap when the pool is outside it. Both fields zero
/// declares no window. See ShiftMath._checkRebalancePriceGuardInner.
struct RebalancePriceBounds {
    uint160 minSqrtPriceX96;
    uint160 maxSqrtPriceX96;
}

struct NftMove {
    IUniswapV3Pool pool;
    NftPosition position;
    NftHarvest harvest;
    NftWithdraw withdraw;
    NftDeposit deposit;
}

contracts/structs/NftLiquidityStructs.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { INonfungiblePositionManager } from
    "contracts/interfaces/external/uniswap/INonfungiblePositionManager.sol";

struct Pool {
    address token0;
    address token1;
    uint24 fee;
}

struct NftPoolKey {
    address poolAddress;
    bytes32 poolId;
}

struct NftPoolInfo {
    address token0;
    address token1;
    uint24 fee;
    uint24 tickSpacing;
    uint160 sqrtPriceX96;
    int24 tick;
    uint128 liquidity;
    uint256 feeGrowthGlobal0X128;
    uint256 feeGrowthGlobal1X128;
}

// Maintained for backwards compatibility with NftSettingsRegistry
struct NftPositionInfo {
    uint128 liquidity;
    int24 tickLower;
    int24 tickUpper;
}

struct NftAddLiquidity {
    INonfungiblePositionManager nft;
    uint256 tokenId;
    Pool pool;
    int24 tickLower;
    int24 tickUpper;
    uint256 amount0Desired;
    uint256 amount1Desired;
    uint256 amount0Min;
    uint256 amount1Min;
    bytes extraData;
}

struct NftRemoveLiquidity {
    INonfungiblePositionManager nft;
    uint256 tokenId;
    uint128 liquidity;
    uint256 amount0Min; // For decreasing
    uint256 amount1Min;
    uint128 amount0Max; // For collecting
    uint128 amount1Max;
    bytes extraData;
}

contracts/structs/NftZapStructs.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import { SwapParams } from "contracts/structs/SwapStructs.sol";
import {
    NftAddLiquidity,
    NftRemoveLiquidity
} from "contracts/structs/NftLiquidityStructs.sol";

struct NftZapIn {
    SwapParams[] swaps;
    NftAddLiquidity addLiquidityParams;
}

struct NftZapOut {
    NftRemoveLiquidity removeLiquidityParams;
    SwapParams[] swaps;
}

contracts/structs/SwapStructs.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

struct SwapParams {
    address tokenApproval;
    address router;
    uint256 amountIn;
    uint256 desiredAmountOut;
    uint256 minAmountOut;
    address tokenIn;
    address tokenOut;
    bytes extraData;
}

contracts/structs/ZapStructs.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { SwapParams } from "contracts/structs/SwapStructs.sol";

import {
    AddLiquidityParams,
    RemoveLiquidityParams
} from "contracts/structs/LiquidityStructs.sol";

struct ZapIn {
    SwapParams[] swaps;
    AddLiquidityParams addLiquidityParams;
}

struct ZapOut {
    RemoveLiquidityParams removeLiquidityParams;
    SwapParams[] swaps;
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Enumerable.sol)

pragma solidity ^0.8.0;

import "../token/ERC721/extensions/IERC721Enumerable.sol";

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

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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
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 amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

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

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Enumerable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * 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[EIP 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);
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris",
  "remappings": [
    "solmate/=lib/solmate/src/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "@morpho-blue/=lib/morpho-blue/src/",
    "ds-test/=lib/solmate/lib/ds-test/src/",
    "forge-std/=lib/forge-std/src/",
    "morpho-blue/=lib/morpho-blue/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.