Skip to content
Verified contractExactMIT

MetricMoveLib

Address0xbdbee75845bd1f9a431b446deb7cfb7cf9c71d4f
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,498,299
Creation transaction
0xd79d605888…8aaf601b3b

contracts/libraries/MetricMoveLib.sol

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

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeTransferLib } from "solmate/utils/SafeTransferLib.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { Sickle } from "contracts/Sickle.sol";
import { DelegateModule } from "contracts/modules/DelegateModule.sol";
import { MetricSettingsRegistry } from "contracts/MetricSettingsRegistry.sol";
import { ISwapLib } from "contracts/interfaces/libraries/ISwapLib.sol";
import { IFeesLib } from "contracts/interfaces/libraries/IFeesLib.sol";
import { IBridgeLib } from "contracts/interfaces/libraries/IBridgeLib.sol";
import { IWETH9 } from "contracts/interfaces/external/IWETH.sol";
import {
    IMetricLiquidityConnector
} from "contracts/interfaces/IMetricLiquidityConnector.sol";
import {
    MetricPoolImmutables
} from "contracts/interfaces/external/metric/IMetricOmm.sol";
import {
    MetricAddLiquidity,
    MetricAutomatedExit,
    MetricBridgeDeposit,
    MetricBridgeWithdrawal,
    MetricMove,
    MetricPosition,
    MetricRemoveLiquidity
} from "contracts/structs/MetricStrategyStructs.sol";
import { SwapParams } from "contracts/structs/SwapStructs.sol";
import { MetricSettings } from "contracts/structs/MetricSettingsStructs.sol";

/// @notice Reinvests Metric removal proceeds without spending existing
/// balances. @dev Delegated from Sickle. All dependencies are immutable. No
/// storage writes.
contract MetricMoveLib is DelegateModule {
    error InvalidSwapAsset(address token);
    error ExistingBalanceConsumed(address token);
    error InsufficientSwapBudget(address token);
    error InsufficientOutput(address token, uint256 received, uint256 minimum);
    error FullWithdrawalRequired();
    error InsufficientDeliveredBalance(address token, uint256 amount);

    struct AssetBalance {
        address token;
        uint256 startingBalance;
    }

    uint256 private constant SOURCE_TOKEN0 = 0;
    uint256 private constant SOURCE_TOKEN1 = 1;
    uint256 private constant DESTINATION_TOKEN0 = 2;
    uint256 private constant DESTINATION_TOKEN1 = 3;
    bytes4 private constant WITHDRAW_FEE = bytes4(keccak256("FarmWithdrawFee"));
    bytes4 private constant REBALANCE_FEE =
        bytes4(keccak256("RebalanceLowFee"));
    bytes4 private constant BRIDGE_DEPOSIT_FEE =
        bytes4(keccak256("BridgeDepositFee"));
    bytes4 private constant BRIDGE_WITHDRAW_FEE =
        bytes4(keccak256("BridgeWithdrawFee"));
    address private constant NATIVE =
        0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    ISwapLib public immutable swapLib;
    IFeesLib public immutable feesLib;
    IBridgeLib public immutable bridgeLib;
    IWETH9 public immutable wrappedNative;
    MetricSettingsRegistry public immutable settingsRegistry;

    constructor(
        ISwapLib swapLib_,
        IFeesLib feesLib_,
        IBridgeLib bridgeLib_,
        IWETH9 wrappedNative_,
        MetricSettingsRegistry settingsRegistry_
    ) {
        swapLib = swapLib_;
        feesLib = feesLib_;
        bridgeLib = bridgeLib_;
        wrappedNative = wrappedNative_;
        settingsRegistry = settingsRegistry_;
    }

    function executeMove(
        MetricMove calldata params,
        address feeStrategy
    ) external {
        IMetricLiquidityConnector connector = settingsRegistry.connector();
        MetricPoolImmutables memory source =
            connector.poolInfo(params.removal.position.pool);
        MetricPoolImmutables memory destination =
            connector.poolInfo(params.addition.position.pool);
        AssetBalance[4] memory balances = [
            _snapshot(source.token0),
            _snapshot(source.token1),
            _snapshot(destination.token0),
            _snapshot(destination.token1)
        ];

        _removeAll(connector, params.removal);
        _charge(feeStrategy, balances[SOURCE_TOKEN0], REBALANCE_FEE);
        _charge(feeStrategy, balances[SOURCE_TOKEN1], REBALANCE_FEE);
        for (uint256 i; i < params.swaps.length; ++i) {
            _swap(balances, params.swaps[i]);
        }

        _add(connector, params.addition, balances);

        _transferProceeds(balances[SOURCE_TOKEN0]);
        _transferProceeds(balances[SOURCE_TOKEN1]);
        _transferProceeds(balances[DESTINATION_TOKEN0]);
        _transferProceeds(balances[DESTINATION_TOKEN1]);
    }

    function syncRebalance(
        MetricPosition calldata position,
        int256[] calldata bins
    ) external {
        settingsRegistry.syncAfterRebalance(position, bins);
    }

    function syncOwnerPosition(
        MetricPosition calldata position,
        int256[] calldata additions
    ) external {
        settingsRegistry.syncAfterOwnerLiquidityChange(position, additions);
    }

    function setSettings(
        MetricPosition calldata position,
        MetricSettings calldata settings,
        int256[] calldata bins
    ) external {
        settingsRegistry.setSettings(
            Sickle(payable(address(this))), position, settings, bins
        );
    }

    function executeExit(
        MetricAutomatedExit calldata params,
        address tokenOut,
        address feeStrategy
    ) external {
        IMetricLiquidityConnector connector = settingsRegistry.connector();
        MetricPoolImmutables memory source =
            connector.poolInfo(params.removal.position.pool);
        AssetBalance memory source0 = _snapshot(source.token0);
        AssetBalance memory source1 = _snapshot(source.token1);
        AssetBalance memory output;
        if (tokenOut != address(0)) {
            output = _snapshot(
                tokenOut == NATIVE ? address(wrappedNative) : tokenOut
            );
        }
        _removeAll(connector, params.removal);
        _charge(feeStrategy, source0, WITHDRAW_FEE);
        _charge(feeStrategy, source1, WITHDRAW_FEE);
        if (tokenOut == address(0)) {
            if (params.swaps.length != 0 || params.minimumOutput != 0) {
                revert InvalidSwapAsset(tokenOut);
            }
        } else {
            _swapInto(params.swaps, source0, source1, output);
            uint256 amount = _proceeds(output);
            if (amount < params.minimumOutput || amount == 0) {
                revert InsufficientOutput(
                    tokenOut, amount, params.minimumOutput
                );
            }
            if (tokenOut == NATIVE) {
                wrappedNative.withdraw(amount);
                SafeTransferLib.safeTransferETH(
                    Sickle(payable(address(this))).owner(), amount
                );
            } else {
                _transferToken(output.token, amount);
            }
        }
        settingsRegistry.clearAfterExit(params.removal.position);
        _transferProceeds(source0);
        _transferProceeds(source1);
    }

    function executeBridgeDeposit(
        address token,
        uint256 amount,
        MetricBridgeDeposit calldata params,
        address feeStrategy
    ) external {
        IMetricLiquidityConnector connector = settingsRegistry.connector();
        MetricPoolImmutables memory destination =
            connector.poolInfo(params.addition.position.pool);
        AssetBalance memory funded;
        if (token == address(0)) {
            if (amount == 0 || address(this).balance < amount) {
                revert InsufficientDeliveredBalance(token, amount);
            }
            funded = _snapshot(address(wrappedNative));
            wrappedNative.deposit{ value: amount }();
        } else {
            funded = _snapshot(token);
            if (amount == 0 || amount > funded.startingBalance) {
                revert InsufficientDeliveredBalance(token, amount);
            }
            funded.startingBalance -= amount;
        }
        AssetBalance[4] memory balances = [
            funded,
            funded,
            _snapshot(destination.token0),
            _snapshot(destination.token1)
        ];
        if (destination.token0 == funded.token) {
            balances[DESTINATION_TOKEN0] = funded;
        }
        if (destination.token1 == funded.token) {
            balances[DESTINATION_TOKEN1] = funded;
        }
        _charge(feeStrategy, funded, BRIDGE_DEPOSIT_FEE);
        for (uint256 i; i < params.swaps.length; ++i) {
            _swap(balances, params.swaps[i]);
        }
        _add(connector, params.addition, balances);
        settingsRegistry.syncAfterOwnerLiquidityChange(
            params.addition.position, params.addition.weights.binIdxs
        );
        _transferProceeds(funded);
        _transferProceeds(balances[DESTINATION_TOKEN0]);
        _transferProceeds(balances[DESTINATION_TOKEN1]);
    }

    function executeBridgeWithdrawal(
        MetricBridgeWithdrawal calldata params,
        address feeStrategy
    ) external payable {
        IMetricLiquidityConnector connector = settingsRegistry.connector();
        MetricPoolImmutables memory source =
            connector.poolInfo(params.removal.position.pool);
        AssetBalance memory source0 = _snapshot(source.token0);
        AssetBalance memory source1 = _snapshot(source.token1);
        AssetBalance memory output = _snapshot(
            params.bridgeToken == address(0)
                ? address(wrappedNative)
                : params.bridgeToken
        );
        _remove(connector, params.removal);
        _swapInto(params.swaps, source0, source1, output);
        _charge(feeStrategy, output, BRIDGE_WITHDRAW_FEE);
        uint256 available = _proceeds(output);
        if (params.bridgeAmount == 0 || params.bridgeAmount > available) {
            revert InsufficientSwapBudget(output.token);
        }
        _delegateToConnector(
            address(bridgeLib),
            abi.encodeCall(
                IBridgeLib.bridge,
                (
                    params.bridge,
                    params.bridgeCalldata,
                    params.bridgeToken,
                    params.bridgeAmount
                )
            )
        );
        settingsRegistry.syncAfterOwnerLiquidityChange(
            params.removal.position, new int256[](0)
        );
        _transferProceeds(output);
        _transferProceeds(source0);
        _transferProceeds(source1);
    }

    function _add(
        IMetricLiquidityConnector connector,
        MetricAddLiquidity memory addition,
        AssetBalance[4] memory balances
    ) private {
        addition.amount0Max = Math.min(
            addition.amount0Max, _proceeds(balances[DESTINATION_TOKEN0])
        );
        addition.amount1Max = Math.min(
            addition.amount1Max, _proceeds(balances[DESTINATION_TOKEN1])
        );
        _delegateToConnector(
            address(connector),
            abi.encodeCall(IMetricLiquidityConnector.addLiquidity, addition)
        );
    }

    function _removeAll(
        IMetricLiquidityConnector connector,
        MetricRemoveLiquidity calldata removal
    ) private {
        for (uint256 i; i < removal.deltas.shares.length; ++i) {
            if (removal.deltas.shares[i] != type(uint256).max) {
                revert FullWithdrawalRequired();
            }
        }
        _remove(connector, removal);
    }

    function _remove(
        IMetricLiquidityConnector connector,
        MetricRemoveLiquidity calldata removal
    ) private {
        _delegateToConnector(
            address(connector),
            abi.encodeCall(IMetricLiquidityConnector.removeLiquidity, removal)
        );
    }

    function _charge(
        address feeStrategy,
        AssetBalance memory asset,
        bytes4 fee
    ) private {
        uint256 amount = _proceeds(asset);
        if (amount == 0) return;
        _delegateToConnector(
            address(feesLib),
            abi.encodeCall(
                IFeesLib.chargeFee, (feeStrategy, fee, asset.token, amount)
            )
        );
    }

    function _swapInto(
        SwapParams[] calldata swaps,
        AssetBalance memory source0,
        AssetBalance memory source1,
        AssetBalance memory output
    ) private {
        AssetBalance[4] memory balances = [source0, source1, output, output];
        for (uint256 i; i < swaps.length; ++i) {
            if (swaps[i].tokenOut != output.token) {
                revert InvalidSwapAsset(swaps[i].tokenOut);
            }
            _swap(balances, swaps[i]);
        }
    }

    function _swap(
        AssetBalance[4] memory balances,
        SwapParams calldata swap
    ) private {
        if (swap.tokenIn == swap.tokenOut) {
            revert InvalidSwapAsset(swap.tokenIn);
        }
        uint256 amount = _proceeds(_findAsset(balances, swap.tokenIn));
        AssetBalance memory output = _findAsset(balances, swap.tokenOut);
        SwapParams memory step = swap;
        if (step.amountIn == 0) step.amountIn = amount;
        if (step.amountIn == 0 || step.amountIn > amount) {
            revert InsufficientSwapBudget(step.tokenIn);
        }

        uint256 outputBefore = _proceeds(output);
        _delegateToConnector(
            address(swapLib), abi.encodeCall(ISwapLib.swap, step)
        );
        if (_proceeds(output) < outputBefore + step.minAmountOut) {
            revert InsufficientSwapBudget(step.tokenOut);
        }
    }

    function _findAsset(
        AssetBalance[4] memory balances,
        address token
    ) private pure returns (AssetBalance memory) {
        for (uint256 i; i < balances.length; ++i) {
            if (balances[i].token == token) return balances[i];
        }
        revert InvalidSwapAsset(token);
    }

    function _snapshot(
        address token
    ) private view returns (AssetBalance memory) {
        return AssetBalance(token, IERC20(token).balanceOf(address(this)));
    }

    function _proceeds(
        AssetBalance memory asset
    ) private view returns (uint256) {
        uint256 current = IERC20(asset.token).balanceOf(address(this));
        if (current < asset.startingBalance) {
            revert ExistingBalanceConsumed(asset.token);
        }
        return current - asset.startingBalance;
    }

    function _transferProceeds(
        AssetBalance memory asset
    ) private {
        uint256 amount = _proceeds(asset);
        if (amount != 0) _transferToken(asset.token, amount);
    }

    function _transferToken(
        address token,
        uint256 amount
    ) private {
        SafeTransferLib.safeTransfer(
            token, Sickle(payable(address(this))).owner(), amount
        );
    }
}

contracts/ConnectorRegistry.sol

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

import { Admin } from "contracts/base/Admin.sol";
import { TimelockAdmin } from "contracts/base/TimelockAdmin.sol";

error ConnectorNotRegistered(address target);
error CustomRegistryAlreadyRegistered();

interface ICustomConnectorRegistry {
    function connectorOf(
        address target
    ) external view returns (address);
}

contract ConnectorRegistry is Admin, TimelockAdmin {
    event ConnectorChanged(address target, address connector);
    event CustomRegistryAdded(address registry);
    event CustomRegistryRemoved(address registry);

    error ConnectorAlreadySet(address target);
    error ConnectorNotSet(address target);
    error ArrayLengthMismatch();

    ICustomConnectorRegistry[] public customRegistries;

    mapping(address target => address connector) private connectors_;

    constructor(
        address admin_,
        address timelockAdmin_
    ) Admin(admin_) TimelockAdmin(timelockAdmin_) { }

    /// Admin functions

    /// @notice Update connector addresses for a batch of targets.
    /// @dev Controls which connector contracts are used for the specified
    /// targets.
    /// @custom:access Restricted to protocol admin.
    function setConnectors(
        address[] calldata targets,
        address[] calldata connectors
    ) external onlyAdmin {
        if (targets.length != connectors.length) {
            revert ArrayLengthMismatch();
        }
        for (uint256 i; i != targets.length;) {
            if (connectors_[targets[i]] != address(0)) {
                revert ConnectorAlreadySet(targets[i]);
            }
            connectors_[targets[i]] = connectors[i];
            emit ConnectorChanged(targets[i], connectors[i]);

            unchecked {
                ++i;
            }
        }
    }

    function updateConnectors(
        address[] calldata targets,
        address[] calldata connectors
    ) external onlyTimelockAdmin {
        if (targets.length != connectors.length) {
            revert ArrayLengthMismatch();
        }
        for (uint256 i; i != targets.length;) {
            if (connectors_[targets[i]] == address(0)) {
                revert ConnectorNotSet(targets[i]);
            }
            connectors_[targets[i]] = connectors[i];
            emit ConnectorChanged(targets[i], connectors[i]);

            unchecked {
                ++i;
            }
        }
    }

    /// @notice Append an address to the custom registries list.
    /// @custom:access Restricted to protocol admin.
    function addCustomRegistry(
        ICustomConnectorRegistry registry
    ) external onlyAdmin {
        if (isCustomRegistry(registry)) {
            revert CustomRegistryAlreadyRegistered();
        }

        customRegistries.push(registry);
        emit CustomRegistryAdded(address(registry));
    }

    /// @notice Replace an address in the custom registries list.
    /// @custom:access Restricted to protocol admin.
    function updateCustomRegistry(
        uint256 index,
        ICustomConnectorRegistry newRegistry
    ) external onlyTimelockAdmin {
        ICustomConnectorRegistry oldRegistry = customRegistries[index];
        emit CustomRegistryRemoved(address(oldRegistry));
        customRegistries[index] = newRegistry;
        if (address(newRegistry) != address(0)) {
            emit CustomRegistryAdded(address(newRegistry));
        }
    }

    /// Public functions

    function connectorOf(
        address target
    ) external view returns (address) {
        address connector = _getConnector(target);

        if (connector != address(0)) {
            return connector;
        }

        revert ConnectorNotRegistered(target);
    }

    function hasConnector(
        address target
    ) external view returns (bool) {
        return _getConnector(target) != address(0);
    }

    function isCustomRegistry(
        ICustomConnectorRegistry registry
    ) public view returns (bool) {
        for (uint256 i; i != customRegistries.length;) {
            if (address(customRegistries[i]) == address(registry)) {
                return true;
            }
            unchecked {
                ++i;
            }
        }
        return false;
    }

    /// Internal functions

    function _getConnector(
        address target
    ) internal view returns (address) {
        address connector = connectors_[target];
        if (connector != address(0)) {
            return connector;
        }
        uint256 length = customRegistries.length;
        for (uint256 i; i != length;) {
            if (address(customRegistries[i]) != address(0)) {
                (bool success, bytes memory data) = address(customRegistries[i])
                    .staticcall(
                    abi.encodeWithSelector(
                        ICustomConnectorRegistry.connectorOf.selector, target
                    )
                );
                if (success && data.length == 32) {
                    address _connector = abi.decode(data, (address));
                    if (_connector != address(0)) {
                        return _connector;
                    }
                }
            }

            unchecked {
                ++i;
            }
        }

        return address(0);
    }
}

contracts/MetricSettingsRegistry.sol

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

import { Sickle } from "contracts/Sickle.sol";
import { SickleFactory } from "contracts/SickleFactory.sol";
import { ConnectorRegistry } from "contracts/ConnectorRegistry.sol";
import {
    MetricLiquidityConnector
} from "contracts/connectors/metric/MetricLiquidityConnector.sol";
import {
    IMetricLiquidityConnector
} from "contracts/interfaces/IMetricLiquidityConnector.sol";
import {
    IMetricOmmDataProvider,
    IMetricOmmFactory,
    IMetricOmmPool,
    MetricPoolImmutables
} from "contracts/interfaces/external/metric/IMetricOmm.sol";
import {
    MetricPosition,
    MetricMove,
    MetricRemoveLiquidity
} from "contracts/structs/MetricStrategyStructs.sol";
import {
    MetricSettings,
    MetricRebalanceConfig,
    MetricExitConfig
} from "contracts/structs/MetricSettingsStructs.sol";

contract MetricSettingsRegistry {
    error UnauthorizedSettingsWriter();
    error InvalidSettings();
    error InvalidTrackedBins();
    error RebalanceNotEnabled();
    error ExitNotEnabled();
    error RebalanceNotTriggered();
    error ExitNotTriggered();
    error InvalidDestinationBins();
    error InvalidMetricPrice();
    error InvalidBridgeIntent();
    error InvalidConnector();

    event MetricSettingsSet(
        Sickle indexed sickle,
        address indexed pool,
        uint80 indexed salt,
        MetricSettings settings,
        int256[] bins
    );
    event MetricSettingsCleared(
        Sickle indexed sickle, address indexed pool, uint80 indexed salt
    );

    struct SavedPosition {
        MetricSettings settings;
        int256[] bins;
    }

    SickleFactory public immutable factory;
    ConnectorRegistry public immutable connectorRegistry;
    IMetricOmmFactory public immutable metricFactory;
    MetricSettingsRegistry public immutable previousRegistry;
    mapping(
        Sickle => mapping(address => mapping(uint80 => SavedPosition))
    ) private positions;
    mapping(Sickle => mapping(address => mapping(uint80 => bool))) private
        initialized;
    mapping(address => mapping(address => mapping(bytes32 => bool))) private
        consumedBridgeIntents;

    constructor(
        SickleFactory factory_,
        ConnectorRegistry connectorRegistry_,
        IMetricOmmFactory metricFactory_,
        MetricSettingsRegistry previousRegistry_
    ) {
        if (
            address(factory_).code.length == 0
                || address(connectorRegistry_).code.length == 0
                || address(metricFactory_).code.length == 0
        ) revert InvalidSettings();
        factory = factory_;
        connectorRegistry = connectorRegistry_;
        metricFactory = metricFactory_;
        if (
            address(previousRegistry_) != address(0)
                && (previousRegistry_.factory() != factory_
                    || previousRegistry_.metricFactory() != metricFactory_)
        ) revert InvalidSettings();
        previousRegistry = previousRegistry_;
    }

    function connector()
        public
        view
        returns (IMetricLiquidityConnector active)
    {
        active =
            IMetricLiquidityConnector(
                connectorRegistry.connectorOf(address(metricFactory))
            );
        if (active.metricFactory() != metricFactory) revert InvalidConnector();
    }

    function dataProvider() public view returns (IMetricOmmDataProvider) {
        return _dataProvider(connector());
    }

    function getSettings(
        Sickle sickle,
        MetricPosition calldata position
    )
        external
        view
        returns (MetricSettings memory settings, int256[] memory bins)
    {
        if (
            !initialized[sickle][position.pool][position.salt]
                && address(previousRegistry) != address(0)
        ) {
            return previousRegistry.getSettings(sickle, position);
        }
        SavedPosition storage saved =
            positions[sickle][position.pool][position.salt];
        return (saved.settings, saved.bins);
    }

    /// @notice Consumes an intent in the calling strategy's namespace.
    function consumeBridgeIntent(
        address owner,
        bytes32 intentId
    ) external {
        if (usedBridgeIntents(msg.sender, owner, intentId)) {
            revert InvalidBridgeIntent();
        }
        consumedBridgeIntents[msg.sender][owner][intentId] = true;
    }

    function usedBridgeIntents(
        address strategy,
        address owner,
        bytes32 intentId
    ) public view returns (bool) {
        return consumedBridgeIntents[strategy][owner][intentId]
            || (address(previousRegistry) != address(0)
                && previousRegistry.usedBridgeIntents(
                strategy, owner, intentId
            ));
    }

    function setSettings(
        Sickle sickle,
        MetricPosition calldata position,
        MetricSettings calldata config,
        int256[] calldata bins
    ) external {
        _requireOwner(sickle);
        if (!config.autoRebalance && !config.autoExit) {
            _clear(sickle, position);
            return;
        }
        IMetricLiquidityConnector active = connector();
        MetricPoolImmutables memory info = active.poolInfo(position.pool);
        _validateSettings(config);
        _validateTrackedBins(
            _dataProvider(active), sickle, position, info, bins
        );
        if (
            config.autoRebalance
                && int256(uint256(config.rebalanceConfig.targetBinsBelow))
                    > bins[bins.length - 1] - bins[0]
        ) {
            revert InvalidSettings();
        }
        SavedPosition storage saved =
            positions[sickle][position.pool][position.salt];
        initialized[sickle][position.pool][position.salt] = true;
        saved.settings = config;
        saved.bins = bins;
        emit MetricSettingsSet(
            sickle, position.pool, position.salt, config, bins
        );
    }

    function clearSettings(
        Sickle sickle,
        MetricPosition calldata position
    ) external {
        _requireOwner(sickle);
        _clear(sickle, position);
    }

    /// @notice Replaces the tracked bins after the checked Sickle rebalance.
    function syncAfterRebalance(
        MetricPosition calldata position,
        int256[] calldata bins
    ) external {
        Sickle sickle = _callerSickle();
        SavedPosition storage saved = _materialize(sickle, position);
        if (!saved.settings.autoRebalance) revert RebalanceNotEnabled();
        saved.bins = bins;
        emit MetricSettingsSet(
            sickle, position.pool, position.salt, saved.settings, bins
        );
    }

    /// @notice Clears the keeper opt-in after the Sickle closes its tracked
    /// bins.
    function clearAfterExit(
        MetricPosition calldata position
    ) external {
        _clear(_callerSickle(), position);
    }

    /// @notice Preserves consent across owner edits to a live salt and clears
    /// it when the tracked position closes.
    function syncAfterOwnerLiquidityChange(
        MetricPosition calldata position,
        int256[] calldata additions
    ) external {
        Sickle sickle = _callerSickle();
        SavedPosition storage saved = _materialize(sickle, position);
        if (saved.bins.length == 0) return;

        IMetricOmmDataProvider provider = dataProvider();
        int256[] memory merged =
            new int256[](saved.bins.length + additions.length);
        uint256 count;
        uint256 i;
        uint256 j;
        while (i < saved.bins.length || j < additions.length) {
            int256 bin;
            if (
                j == additions.length
                    || (i < saved.bins.length && saved.bins[i] < additions[j])
            ) {
                bin = saved.bins[i++];
            } else if (i == saved.bins.length || additions[j] < saved.bins[i]) {
                bin = additions[j++];
            } else {
                bin = saved.bins[i++];
                ++j;
            }
            if (_shares(provider, sickle, position, bin) != 0) {
                merged[count++] = bin;
            }
        }
        if (count == 0) {
            _clear(sickle, position);
            return;
        }
        if (count == saved.bins.length) {
            bool same = true;
            for (uint256 k; k < count; ++k) {
                if (merged[k] != saved.bins[k]) {
                    same = false;
                    break;
                }
            }
            if (same) return;
        }
        int256[] memory updated = new int256[](count);
        for (uint256 k; k < count; ++k) {
            updated[k] = merged[k];
        }
        saved.bins = updated;
        emit MetricSettingsSet(
            sickle, position.pool, position.salt, saved.settings, updated
        );
    }

    function validateRebalance(
        Sickle sickle,
        MetricMove calldata move
    ) external {
        MetricPosition calldata position = move.removal.position;
        SavedPosition storage saved = _materialize(sickle, position);
        if (!saved.settings.autoRebalance) revert RebalanceNotEnabled();
        IMetricLiquidityConnector active = connector();
        MetricPoolImmutables memory info = active.poolInfo(position.pool);
        IMetricOmmDataProvider provider = _dataProvider(active);
        uint256[] memory held =
            _validateHeldBins(provider, sickle, move.removal, saved.bins);
        MetricRebalanceConfig memory config = saved.settings.rebalanceConfig;
        (, int16 currentBin,,,,,) = provider.slot0(position.pool);
        int256 first = move.removal.deltas.binIdxs[0];
        int256 last = move.removal.deltas.binIdxs[held.length - 1];
        if (
            currentBin >= first - int256(uint256(config.bufferBinsBelow))
                && currentBin <= last + int256(uint256(config.bufferBinsAbove))
        ) {
            revert RebalanceNotTriggered();
        }
        if (config.minPriceX64 != 0 || config.maxPriceX64 != 0) {
            uint256 price = _poolPrice(position.pool);
            if (
                (config.minPriceX64 != 0 && price < config.minPriceX64)
                    || (config.maxPriceX64 != 0 && price > config.maxPriceX64)
            ) {
                revert RebalanceNotTriggered();
            }
        }
        _validateDestination(
            move,
            info,
            held,
            int256(currentBin) - int256(uint256(config.targetBinsBelow)) - first
        );
    }

    function validateExit(
        Sickle sickle,
        MetricRemoveLiquidity calldata removal
    ) external returns (address outputToken) {
        MetricPosition calldata position = removal.position;
        SavedPosition storage saved = _materialize(sickle, position);
        if (!saved.settings.autoExit) revert ExitNotEnabled();
        IMetricLiquidityConnector active = connector();
        active.poolInfo(position.pool);
        _validateHeldBins(_dataProvider(active), sickle, removal, saved.bins);
        MetricExitConfig memory config = saved.settings.exitConfig;
        uint256 price = _poolPrice(position.pool);
        if (config.priceLowX64 != 0 && price <= config.priceLowX64) {
            return config.tokenOutLow;
        }
        if (config.priceHighX64 != 0 && price >= config.priceHighX64) {
            return config.tokenOutHigh;
        }
        revert ExitNotTriggered();
    }

    function currentPriceX64(
        address pool
    ) external returns (uint256) {
        connector().poolInfo(pool);
        return _poolPrice(pool);
    }

    function _validateSettings(
        MetricSettings calldata config
    ) private pure {
        if (config.autoRebalance) {
            MetricRebalanceConfig calldata rebalance = config.rebalanceConfig;
            if (
                rebalance.slippageBps > 10_000
                    || rebalance.priceImpactBps > 10_000
                    || (rebalance.minPriceX64 != 0
                        && rebalance.maxPriceX64 != 0
                        && rebalance.minPriceX64 >= rebalance.maxPriceX64)
            ) revert InvalidSettings();
        }
        if (config.autoExit) {
            MetricExitConfig calldata exit = config.exitConfig;
            if (
                exit.slippageBps > 10_000 || exit.priceImpactBps > 10_000
                    || (exit.priceLowX64 == 0 && exit.priceHighX64 == 0)
                    || (exit.priceLowX64 != 0
                        && exit.priceHighX64 != 0
                        && exit.priceLowX64 >= exit.priceHighX64)
            ) revert InvalidSettings();
        }
    }

    function _validateTrackedBins(
        IMetricOmmDataProvider provider,
        Sickle sickle,
        MetricPosition calldata position,
        MetricPoolImmutables memory info,
        int256[] calldata bins
    ) private view {
        if (
            bins.length == 0 || bins[0] < info.lowestBin
                || bins[bins.length - 1] > info.highestBin
        ) revert InvalidTrackedBins();
        for (uint256 i; i < bins.length; ++i) {
            if (
                (i != 0 && bins[i] <= bins[i - 1])
                    || _shares(provider, sickle, position, bins[i]) == 0
            ) revert InvalidTrackedBins();
        }
    }

    function _validateHeldBins(
        IMetricOmmDataProvider provider,
        Sickle sickle,
        MetricRemoveLiquidity calldata removal,
        int256[] storage tracked
    ) private view returns (uint256[] memory held) {
        uint256 count = removal.deltas.binIdxs.length;
        if (count == 0 || count != removal.deltas.shares.length) {
            revert InvalidTrackedBins();
        }
        held = new uint256[](count);
        uint256 index;
        for (uint256 i; i < tracked.length; ++i) {
            int256 bin = tracked[i];
            uint256 shares = _shares(provider, sickle, removal.position, bin);
            if (shares == 0) continue;
            if (
                index == count || removal.deltas.binIdxs[index] != bin
                    || removal.deltas.shares[index] != type(uint256).max
            ) revert InvalidTrackedBins();
            held[index] = shares;
            ++index;
        }
        if (index != count) revert InvalidTrackedBins();
    }

    function _validateDestination(
        MetricMove calldata move,
        MetricPoolImmutables memory info,
        uint256[] memory held,
        int256 shift
    ) private pure {
        if (
            shift == 0 || move.addition.weights.binIdxs.length != held.length
                || move.addition.weights.shares.length != held.length
        ) {
            revert InvalidDestinationBins();
        }
        for (uint256 i; i < held.length; ++i) {
            int256 targetBin = move.removal.deltas.binIdxs[i] + shift;
            if (
                targetBin < info.lowestBin || targetBin > info.highestBin
                    || targetBin != move.addition.weights.binIdxs[i]
                    || held[i] != move.addition.weights.shares[i]
            ) {
                revert InvalidDestinationBins();
            }
        }
    }

    function _poolPrice(
        address pool
    ) private returns (uint256) {
        (uint128 sell, uint128 buy) = IMetricOmmPool(pool).getSellAndBuyPrices();
        if (sell == 0 || buy < sell) revert InvalidMetricPrice();
        return (uint256(sell) + buy) / 2;
    }

    function _shares(
        IMetricOmmDataProvider provider,
        Sickle sickle,
        MetricPosition calldata position,
        int256 bin
    ) private view returns (uint256) {
        if (bin < type(int16).min || bin > type(int16).max) {
            revert InvalidTrackedBins();
        }
        return provider.positionBinShares(
            position.pool, address(sickle), position.salt, int16(bin)
        );
    }

    function _requireOwner(
        Sickle sickle
    ) private view {
        address owner = factory.admins(address(sickle));
        if (
            owner == address(0)
                || (msg.sender != owner && msg.sender != address(sickle))
        ) {
            revert UnauthorizedSettingsWriter();
        }
    }

    function _dataProvider(
        IMetricLiquidityConnector active
    ) private view returns (IMetricOmmDataProvider) {
        return MetricLiquidityConnector(address(active)).dataProvider();
    }

    function _callerSickle() private view returns (Sickle) {
        if (factory.admins(msg.sender) == address(0)) {
            revert UnauthorizedSettingsWriter();
        }
        return Sickle(payable(msg.sender));
    }

    function _clear(
        Sickle sickle,
        MetricPosition calldata position
    ) private {
        initialized[sickle][position.pool][position.salt] = true;
        delete positions[sickle][position.pool][position.salt];
        emit MetricSettingsCleared(sickle, position.pool, position.salt);
    }

    function _materialize(
        Sickle sickle,
        MetricPosition calldata position
    ) private returns (SavedPosition storage saved) {
        saved = positions[sickle][position.pool][position.salt];
        if (!initialized[sickle][position.pool][position.salt]) {
            initialized[sickle][position.pool][position.salt] = true;
            if (address(previousRegistry) != address(0)) {
                (saved.settings, saved.bins) =
                    previousRegistry.getSettings(sickle, position);
            }
        }
    }
}

contracts/Sickle.sol

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

import { SickleStorage } from "contracts/base/SickleStorage.sol";
import { Multicall } from "contracts/base/Multicall.sol";
import { SickleRegistry } from "contracts/SickleRegistry.sol";

/// @title Sickle contract
/// @author vfat.tools
/// @notice Sickle facilitates farming and interactions with Masterchef
/// contracts
/// @dev Base contract inheriting from all the other "manager" contracts
contract Sickle is SickleStorage, Multicall {
    /// @notice Function to receive ETH
    receive() external payable { }

    /// @param sickleRegistry_ Address of the SickleRegistry contract
    constructor(
        SickleRegistry sickleRegistry_
    ) Multicall(sickleRegistry_) {
        _disableInitializers();
    }

    /// @param sickleOwner_ Address of the Sickle owner
    function initialize(
        address sickleOwner_,
        address approved_
    ) external initializer {
        SickleStorage._initializeSickleStorage(sickleOwner_, approved_);
    }

    /// INTERNALS ///

    function onERC721Received(
        address, // operator
        address, // from
        uint256, // tokenId
        bytes calldata // data
    ) external pure returns (bytes4) {
        return this.onERC721Received.selector;
    }

    function onERC1155Received(
        address, // operator
        address, // from
        uint256, // id
        uint256, // value
        bytes calldata // data
    ) external pure returns (bytes4) {
        return this.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address, // operator
        address, // from
        uint256[] calldata, // ids
        uint256[] calldata, // values
        bytes calldata // data
    ) external pure returns (bytes4) {
        return this.onERC1155BatchReceived.selector;
    }
}

contracts/SickleFactory.sol

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

import { Clones } from "@openzeppelin/contracts/proxy/Clones.sol";

import { Sickle } from "contracts/Sickle.sol";
import { SickleRegistry } from "contracts/SickleRegistry.sol";
import { Admin } from "contracts/base/Admin.sol";

/// @title SickleFactory contract
/// @author vfat.tools
/// @notice Factory deploying new Sickle contracts
contract SickleFactory is Admin {
    /// EVENTS ///

    /// @notice Emitted when a new Sickle contract is deployed
    /// @param admin Address receiving the admin rights of the Sickle contract
    /// @param sickle Address of the newly deployed Sickle contract
    event Deploy(address indexed admin, address sickle);

    /// @notice Thrown when the caller is not whitelisted
    /// @param caller Address of the non-whitelisted caller
    error CallerNotWhitelisted(address caller); // 0x252c8273

    /// @notice Thrown when the factory is not active and a deploy is attempted
    error NotActive(); // 0x80cb55e2

    /// @notice Thrown when a Sickle contract is already deployed for a user
    error SickleAlreadyDeployed(); //0xf6782ef1

    /// STORAGE ///

    mapping(address => address) private _sickles;
    mapping(address => address) private _admins;
    mapping(address => bytes32) public _referralCodes;

    /// @notice Address of the SickleRegistry contract
    SickleRegistry public immutable registry;

    /// @notice Address of the Sickle implementation contract
    address public immutable implementation;

    /// @notice Address of the previous SickleFactory contract (if applicable)
    SickleFactory public immutable previousFactory;

    /// @notice Whether the factory is active (can deploy new Sickle contracts)
    bool public isActive = true;

    /// WRITE FUNCTIONS ///

    /// @param admin_ Address of the admin
    /// @param sickleRegistry_ Address of the SickleRegistry contract
    /// @param sickleImplementation_ Address of the Sickle implementation
    /// contract
    /// @param previousFactory_ Address of the previous SickleFactory contract
    /// if applicable
    constructor(
        address admin_,
        address sickleRegistry_,
        address sickleImplementation_,
        address previousFactory_
    ) Admin(admin_) {
        registry = SickleRegistry(sickleRegistry_);
        implementation = sickleImplementation_;
        previousFactory = SickleFactory(previousFactory_);
    }

    function setActive(
        bool active
    ) external onlyAdmin {
        isActive = active;
    }

    function _deploy(
        address admin,
        address approved,
        bytes32 referralCode
    ) internal returns (address sickle) {
        sickle = Clones.cloneDeterministic(
            implementation, keccak256(abi.encode(admin))
        );
        Sickle(payable(sickle)).initialize(admin, approved);
        _sickles[admin] = sickle;
        _admins[sickle] = admin;
        if (referralCode != bytes32(0)) {
            _referralCodes[sickle] = referralCode;
        }
        emit Deploy(admin, sickle);
    }

    function _getSickle(
        address admin
    ) internal returns (address sickle) {
        sickle = _sickles[admin];
        if (sickle != address(0)) {
            return sickle;
        }
        if (address(previousFactory) != address(0)) {
            sickle = previousFactory.sickles(admin);
            if (sickle != address(0)) {
                _sickles[admin] = sickle;
                _admins[sickle] = admin;
                _referralCodes[sickle] = previousFactory.referralCodes(sickle);
                return sickle;
            }
        }
    }

    /// @notice Predict the address of a Sickle contract for a specific user
    /// @param admin Address receiving the admin rights of the Sickle contract
    /// @return sickle Address of the predicted Sickle contract
    function predict(
        address admin
    ) external view returns (address) {
        bytes32 salt = keccak256(abi.encode(admin));
        return Clones.predictDeterministicAddress(implementation, salt);
    }

    /// @notice Returns the Sickle contract for a specific user
    /// @param admin Address that owns the Sickle contract
    /// @return sickle Address of the Sickle contract
    function sickles(
        address admin
    ) external view returns (address sickle) {
        sickle = _sickles[admin];
        if (sickle == address(0) && address(previousFactory) != address(0)) {
            sickle = previousFactory.sickles(admin);
        }
    }

    /// @notice Returns the admin for a specific Sickle contract
    /// @param sickle Address of the Sickle contract
    /// @return admin Address that owns the Sickle contract
    function admins(
        address sickle
    ) external view returns (address admin) {
        admin = _admins[sickle];
        if (admin == address(0) && address(previousFactory) != address(0)) {
            admin = previousFactory.admins(sickle);
        }
    }

    /// @notice Returns the referral code for a specific Sickle contract
    /// @param sickle Address of the Sickle contract
    /// @return referralCode Referral code for the user
    function referralCodes(
        address sickle
    ) external view returns (bytes32 referralCode) {
        referralCode = _referralCodes[sickle];
        if (
            referralCode == bytes32(0) && address(previousFactory) != address(0)
        ) {
            referralCode = previousFactory.referralCodes(sickle);
        }
    }

    /// @notice Deploys a new Sickle contract for a specific user, or returns
    /// the existing one if it exists
    /// @param admin Address receiving the admin rights of the Sickle contract
    /// @param approved Address approved to manage automation
    /// @param referralCode Referral code for the user
    /// @return sickle Address of the deployed Sickle contract
    function getOrDeploy(
        address admin,
        address approved,
        bytes32 referralCode
    ) external returns (address sickle) {
        if (!isActive) {
            revert NotActive();
        }
        if (!registry.isWhitelistedCaller(msg.sender)) {
            revert CallerNotWhitelisted(msg.sender);
        }
        if ((sickle = _getSickle(admin)) != address(0)) {
            return sickle;
        }
        return _deploy(admin, approved, referralCode);
    }

    /// @notice Deploys a new Sickle contract for a specific user
    /// @dev Sickle contracts are deployed with create2, the address of the
    /// admin is used as a salt, so all the Sickle addresses can be pre-computed
    /// and only 1 Sickle will exist per address
    /// @param approved Address approved to manage automation
    /// @param referralCode Referral code for the user
    /// @return sickle Address of the deployed Sickle contract
    function deploy(
        address approved,
        bytes32 referralCode
    ) external returns (address sickle) {
        if (!isActive) {
            revert NotActive();
        }
        if (_getSickle(msg.sender) != address(0)) {
            revert SickleAlreadyDeployed();
        }
        return _deploy(msg.sender, approved, referralCode);
    }
}

contracts/SickleRegistry.sol

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

import { Admin } from "contracts/base/Admin.sol";

library SickleRegistryEvents {
    event CollectorChanged(address newCollector);
    event FeesUpdated(bytes32[] feeHashes, uint256[] feesInBP);
    event ReferralCodeCreated(bytes32 indexed code, address indexed referrer);

    // Multicall caller and target whitelist status changes
    event CallerStatusChanged(address caller, bool isWhitelisted);
    event TargetStatusChanged(address target, bool isWhitelisted);
}

/// @title SickleRegistry contract
/// @author vfat.tools
/// @notice Manages the whitelisted contracts and the collector address
contract SickleRegistry is Admin {
    /// CONSTANTS ///

    uint256 constant MAX_FEE = 500; // 5%

    /// ERRORS ///

    error ArrayLengthMismatch(); // 0xa24a13a6
    error FeeAboveMaxLimit(); // 0xd6cf7b5e
    error InvalidReferralCode(); // 0xe55b4629

    /// STORAGE ///

    /// @notice Address of the fee collector
    address public collector;

    /// @notice Tracks the contracts that can be called through Sickle multicall
    /// @return True if the contract is a whitelisted target
    mapping(address => bool) public isWhitelistedTarget;

    /// @notice Tracks the contracts that can call Sickle multicall
    /// @return True if the contract is a whitelisted caller
    mapping(address => bool) public isWhitelistedCaller;

    /// @notice Keeps track of the referrers and their associated code
    mapping(bytes32 => address) public referralCodes;

    /// @notice Mapping for fee hashes (hash of the strategy contract addresses
    /// and the function selectors) and their associated fees
    /// @return The fee in basis points to apply to the transaction amount
    mapping(bytes32 => uint256) public feeRegistry;

    /// WRITE FUNCTIONS ///

    /// @param admin_ Address of the admin
    /// @param collector_ Address of the collector
    constructor(address admin_, address collector_) Admin(admin_) {
        collector = collector_;
    }

    /// @notice Updates the whitelist status for multiple multicall targets
    /// @param targets Addresses of the contracts to update
    /// @param isApproved New status for the contracts
    /// @custom:access Restricted to protocol admin.
    function setWhitelistedTargets(
        address[] calldata targets,
        bool isApproved
    ) external onlyAdmin {
        for (uint256 i; i < targets.length;) {
            isWhitelistedTarget[targets[i]] = isApproved;
            emit SickleRegistryEvents.TargetStatusChanged(
                targets[i], isApproved
            );

            unchecked {
                ++i;
            }
        }
    }

    /// @notice Updates the fee collector address
    /// @param newCollector Address of the new fee collector
    /// @custom:access Restricted to protocol admin.
    function updateCollector(
        address newCollector
    ) external onlyAdmin {
        collector = newCollector;
        emit SickleRegistryEvents.CollectorChanged(newCollector);
    }

    /// @notice Update the whitelist status for multiple multicall callers
    /// @param callers Addresses of the callers
    /// @param isApproved New status for the caller
    /// @custom:access Restricted to protocol admin.
    function setWhitelistedCallers(
        address[] calldata callers,
        bool isApproved
    ) external onlyAdmin {
        for (uint256 i; i < callers.length;) {
            isWhitelistedCaller[callers[i]] = isApproved;
            emit SickleRegistryEvents.CallerStatusChanged(
                callers[i], isApproved
            );

            unchecked {
                ++i;
            }
        }
    }

    /// @notice Associates a referral code to the address of the caller
    function setReferralCode(
        bytes32 referralCode
    ) external {
        if (referralCodes[referralCode] != address(0)) {
            revert InvalidReferralCode();
        }

        referralCodes[referralCode] = msg.sender;
        emit SickleRegistryEvents.ReferralCodeCreated(referralCode, msg.sender);
    }

    /// @notice Update the fees for multiple strategy functions
    /// @param feeHashes Array of fee hashes
    /// @param feesArray Array of fees to apply (in basis points)
    /// @custom:access Restricted to protocol admin.
    function setFees(
        bytes32[] calldata feeHashes,
        uint256[] calldata feesArray
    ) external onlyAdmin {
        if (feeHashes.length != feesArray.length) {
            revert ArrayLengthMismatch();
        }

        for (uint256 i = 0; i < feeHashes.length;) {
            if (feesArray[i] <= MAX_FEE) {
                feeRegistry[feeHashes[i]] = feesArray[i];
            } else {
                revert FeeAboveMaxLimit();
            }
            unchecked {
                ++i;
            }
        }

        emit SickleRegistryEvents.FeesUpdated(feeHashes, feesArray);
    }
}

contracts/base/Admin.sol

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

/// @title Admin contract
/// @author vfat.tools
/// @notice Provides an administration mechanism allowing restricted functions
abstract contract Admin {
    /// ERRORS ///

    /// @notice Thrown when the caller is not the admin
    error NotAdminError(); //0xb5c42b3b

    /// EVENTS ///

    /// @notice Emitted when a new admin is set
    /// @param oldAdmin Address of the old admin
    /// @param newAdmin Address of the new admin
    event AdminSet(address oldAdmin, address newAdmin);

    /// STORAGE ///

    /// @notice Address of the current admin
    address public admin;

    /// MODIFIERS ///

    /// @dev Restricts a function to the admin
    modifier onlyAdmin() {
        if (msg.sender != admin) revert NotAdminError();
        _;
    }

    /// WRITE FUNCTIONS ///

    /// @param admin_ Address of the admin
    constructor(
        address admin_
    ) {
        emit AdminSet(address(0), admin_);
        admin = admin_;
    }

    /// @notice Sets a new admin
    /// @param newAdmin Address of the new admin
    /// @custom:access Restricted to protocol admin.
    function setAdmin(
        address newAdmin
    ) external onlyAdmin {
        emit AdminSet(admin, newAdmin);
        admin = newAdmin;
    }
}

contracts/base/Multicall.sol

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

import { SickleRegistry } from "contracts/SickleRegistry.sol";

/// @title Multicall contract
/// @author vfat.tools
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall {
    /// ERRORS ///

    error MulticallParamsMismatchError(); // 0xc1e637c9

    /// @notice Thrown when the target contract is not whitelisted
    /// @param target Address of the non-whitelisted target
    error TargetNotWhitelisted(address target); // 0x47ccabe7

    /// @notice Thrown when the caller is not whitelisted
    /// @param caller Address of the non-whitelisted caller
    error CallerNotWhitelisted(address caller); // 0x252c8273

    /// STORAGE ///

    /// @notice Address of the SickleRegistry contract
    /// @dev Needs to be immutable so that it's accessible for Sickle proxies
    SickleRegistry public immutable registry;

    /// INITIALIZATION ///

    /// @param registry_ Address of the SickleRegistry contract
    constructor(
        SickleRegistry registry_
    ) {
        registry = registry_;
    }

    /// WRITE FUNCTIONS ///

    /// @notice Batch multiple calls together (calls or delegatecalls)
    /// @param targets Array of targets to call
    /// @param data Array of data to pass with the calls
    function multicall(
        address[] calldata targets,
        bytes[] calldata data
    ) external payable {
        if (targets.length != data.length) {
            revert MulticallParamsMismatchError();
        }

        if (!registry.isWhitelistedCaller(msg.sender)) {
            revert CallerNotWhitelisted(msg.sender);
        }

        for (uint256 i = 0; i != data.length;) {
            if (targets[i] == address(0)) {
                unchecked {
                    ++i;
                }
                continue; // No-op
            }

            if (targets[i] != address(this)) {
                if (!registry.isWhitelistedTarget(targets[i])) {
                    revert TargetNotWhitelisted(targets[i]);
                }
            }

            (bool success, bytes memory result) =
                targets[i].delegatecall(data[i]);

            if (!success) {
                if (result.length == 0) revert();
                assembly {
                    revert(add(32, result), mload(result))
                }
            }
            unchecked {
                ++i;
            }
        }
    }
}

contracts/base/SickleStorage.sol

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

import { Initializable } from
    "@openzeppelin/contracts/proxy/utils/Initializable.sol";

library SickleStorageEvents {
    event ApprovedAddressChanged(address newApproved);
}

/// @title SickleStorage contract
/// @author vfat.tools
/// @notice Base storage of the Sickle contract
/// @dev This contract needs to be inherited by stub contracts meant to be used
/// with `delegatecall`
abstract contract SickleStorage is Initializable {
    /// ERRORS ///

    /// @notice Thrown when the caller is not the owner of the Sickle contract
    error NotOwnerError(); // 0x74a21527

    /// @notice Thrown when the caller is not a strategy contract or the
    /// Flashloan Stub
    error NotStrategyError(); // 0x4581ba62

    /// STORAGE ///

    /// @notice Address of the owner
    address public owner;

    /// @notice An address that can be set by the owner of the Sickle contract
    /// in order to trigger specific functions.
    address public approved;

    /// MODIFIERS ///

    /// @dev Restricts a function call to the owner of the Sickle contract
    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwnerError();
        _;
    }

    /// INITIALIZATION ///

    /// @param owner_ Address of the owner of this Sickle contract
    function _initializeSickleStorage(
        address owner_,
        address approved_
    ) internal onlyInitializing {
        owner = owner_;
        approved = approved_;
    }

    /// WRITE FUNCTIONS ///

    /// @notice Sets the approved address of this Sickle
    /// @param newApproved Address meant to be approved by the owner
    function setApproved(
        address newApproved
    ) external onlyOwner {
        approved = newApproved;
        emit SickleStorageEvents.ApprovedAddressChanged(newApproved);
    }

    /// @notice Checks if `caller` is either the owner of the Sickle contract
    /// or was approved by them
    /// @param caller Address to check
    /// @return True if `caller` is either the owner of the Sickle contract
    function isOwnerOrApproved(
        address caller
    ) public view returns (bool) {
        return caller == owner || caller == approved;
    }
}

contracts/base/TimelockAdmin.sol

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

/// @title TimelockAdmin contract
/// @author vfat.tools
/// @notice Provides an timelockAdministration mechanism allowing restricted
/// functions
abstract contract TimelockAdmin {
    /// ERRORS ///

    /// @notice Thrown when the caller is not the timelockAdmin
    error NotTimelockAdminError();

    /// EVENTS ///

    /// @notice Emitted when a new timelockAdmin is set
    /// @param oldTimelockAdmin Address of the old timelockAdmin
    /// @param newTimelockAdmin Address of the new timelockAdmin
    event TimelockAdminSet(address oldTimelockAdmin, address newTimelockAdmin);

    /// STORAGE ///

    /// @notice Address of the current timelockAdmin
    address public timelockAdmin;

    /// MODIFIERS ///

    /// @dev Restricts a function to the timelockAdmin
    modifier onlyTimelockAdmin() {
        if (msg.sender != timelockAdmin) revert NotTimelockAdminError();
        _;
    }

    /// WRITE FUNCTIONS ///

    /// @param timelockAdmin_ Address of the timelockAdmin
    constructor(
        address timelockAdmin_
    ) {
        emit TimelockAdminSet(timelockAdmin, timelockAdmin_);
        timelockAdmin = timelockAdmin_;
    }

    /// @notice Sets a new timelockAdmin
    /// @dev Can only be called by the current timelockAdmin
    /// @param newTimelockAdmin Address of the new timelockAdmin
    function setTimelockAdmin(
        address newTimelockAdmin
    ) external onlyTimelockAdmin {
        emit TimelockAdminSet(timelockAdmin, newTimelockAdmin);
        timelockAdmin = newTimelockAdmin;
    }
}

contracts/connectors/metric/MetricLiquidityConnector.sol

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

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { SafeTransferLib } from "solmate/utils/SafeTransferLib.sol";
import {
    IMetricOmmFactory,
    IMetricOmmPool,
    IMetricOmmLiquidityAdder,
    IMetricOmmDataProvider,
    MetricPoolImmutables,
    MetricLiquidityDelta
} from "contracts/interfaces/external/metric/IMetricOmm.sol";
import {
    IMetricLiquidityConnector
} from "contracts/interfaces/IMetricLiquidityConnector.sol";
import {
    MetricAddLiquidity,
    MetricRemoveLiquidity,
    MetricPosition
} from "contracts/structs/MetricStrategyStructs.sol";

/// @notice Metric liquidity operations for Sickle-owned positions.
/// @dev Delegatecalled; Metric's adder handles deposit callbacks.
contract MetricLiquidityConnector is IMetricLiquidityConnector {
    struct AddState {
        uint256 balance0;
        uint256 balance1;
        uint256 cap0;
        uint256 cap1;
        uint256[] beforeShares;
    }
    error InvalidDependency();
    error OnlyDelegateCall();
    error InvalidPool(address pool);
    error InvalidBins();
    error InvalidAmounts();
    error InsufficientShares(int256 bin, uint256 actual, uint256 minimum);
    error InsufficientOutput(uint256 amount0, uint256 amount1);

    event MetricLiquidityAdded(
        address indexed sickle,
        address indexed pool,
        uint80 indexed salt,
        int256[] bins,
        uint256[] shares,
        uint256 amount0,
        uint256 amount1
    );
    event MetricLiquidityRemoved(
        address indexed sickle,
        address indexed pool,
        uint80 indexed salt,
        int256[] bins,
        uint256[] shares,
        uint256 amount0,
        uint256 amount1
    );

    IMetricOmmFactory public immutable override metricFactory;
    IMetricOmmLiquidityAdder public immutable liquidityAdder;
    IMetricOmmDataProvider public immutable dataProvider;
    address private immutable self;

    constructor(
        IMetricOmmFactory factory_,
        IMetricOmmLiquidityAdder adder_,
        IMetricOmmDataProvider provider_
    ) {
        if (
            address(factory_).code.length == 0
                || address(adder_).code.length == 0
                || address(provider_).code.length == 0
        ) revert InvalidDependency();
        metricFactory = factory_;
        liquidityAdder = adder_;
        dataProvider = provider_;
        self = address(this);
    }

    modifier delegated() {
        if (address(this) == self) revert OnlyDelegateCall();
        _;
    }

    function poolInfo(
        address pool
    ) public view override returns (MetricPoolImmutables memory info) {
        if (!metricFactory.isPool(pool)) revert InvalidPool(pool);
        info = IMetricOmmPool(pool).getImmutables();
        if (
            info.factory != address(metricFactory) || info.token0 == address(0)
                || info.token1 == address(0) || info.token0 == info.token1
                || info.token0ScaleMultiplier == 0
                || info.token1ScaleMultiplier == 0
        ) revert InvalidPool(pool);
    }

    function positionShares(
        MetricPosition calldata position,
        address owner,
        int256[] calldata bins
    ) external view override returns (uint256[] memory) {
        MetricPoolImmutables memory info = poolInfo(position.pool);
        _checkBins(info, bins);
        return _shares(position, owner, bins);
    }

    function underlyingAmounts(
        MetricPosition calldata position,
        address owner,
        int256[] calldata bins
    ) external view override returns (uint256 amount0, uint256 amount1) {
        MetricPoolImmutables memory info = poolInfo(position.pool);
        _checkBins(info, bins);
        for (uint256 i; i < bins.length; ++i) {
            int16 bin = int16(bins[i]);
            uint256 shares = dataProvider.positionBinShares(
                position.pool, owner, position.salt, bin
            );
            if (shares == 0) continue;
            uint256 total = dataProvider.binTotalShares(position.pool, bin);
            (uint104 reserve0, uint104 reserve1,,,) =
                dataProvider.binState(position.pool, bin);
            amount0 += Math.mulDiv(shares, reserve0, total);
            amount1 += Math.mulDiv(shares, reserve1, total);
        }
        // Match core's per-bin floor followed by one native-unit conversion.
        amount0 /= info.token0ScaleMultiplier;
        amount1 /= info.token1ScaleMultiplier;
    }

    function addLiquidity(
        MetricAddLiquidity calldata params
    ) external payable override delegated {
        MetricPoolImmutables memory info = poolInfo(params.position.pool);
        _checkBins(info, params.weights.binIdxs);
        uint256 n = params.weights.binIdxs.length;
        if (params.weights.shares.length != n || params.minShares.length != n) {
            revert InvalidAmounts();
        }
        for (uint256 i; i < n; ++i) {
            if (params.weights.shares[i] == 0) revert InvalidAmounts();
        }
        AddState memory state;
        state.balance0 = IERC20(info.token0).balanceOf(address(this));
        state.balance1 = IERC20(info.token1).balanceOf(address(this));
        state.cap0 = Math.min(params.amount0Max, state.balance0);
        state.cap1 = Math.min(params.amount1Max, state.balance1);
        if (state.cap0 == 0 && state.cap1 == 0) revert InvalidAmounts();
        state.beforeShares =
            _shares(params.position, address(this), params.weights.binIdxs);
        _approve(info.token0, state.cap0);
        _approve(info.token1, state.cap1);
        _add(params, state.cap0, state.cap1);
        _approve(info.token0, 0);
        _approve(info.token1, 0);
        uint256 spent0 =
            state.balance0 - IERC20(info.token0).balanceOf(address(this));
        uint256 spent1 =
            state.balance1 - IERC20(info.token1).balanceOf(address(this));
        if (spent0 > state.cap0 || spent1 > state.cap1) {
            revert InvalidAmounts();
        }
        uint256[] memory minted =
            _shares(params.position, address(this), params.weights.binIdxs);
        for (uint256 i; i < n; ++i) {
            minted[i] -= state.beforeShares[i];
            if (minted[i] == 0 || minted[i] < params.minShares[i]) {
                revert InsufficientShares(
                    params.weights.binIdxs[i], minted[i], params.minShares[i]
                );
            }
        }
        emit MetricLiquidityAdded(
            address(this),
            params.position.pool,
            params.position.salt,
            params.weights.binIdxs,
            minted,
            spent0,
            spent1
        );
    }

    function _add(
        MetricAddLiquidity calldata params,
        uint256 cap0,
        uint256 cap1
    ) private {
        liquidityAdder.addLiquidityWeighted(
            params.position.pool,
            address(this),
            params.position.salt,
            params.weights,
            cap0,
            cap1,
            params.bounds,
            params.extensionData
        );
    }

    function removeLiquidity(
        MetricRemoveLiquidity calldata params
    ) external payable override delegated {
        MetricPoolImmutables memory info = poolInfo(params.position.pool);
        _checkBins(info, params.deltas.binIdxs);
        uint256 n = params.deltas.binIdxs.length;
        if (params.deltas.shares.length != n) revert InvalidAmounts();
        uint256[] memory held =
            _shares(params.position, address(this), params.deltas.binIdxs);
        uint256[] memory burns = new uint256[](n);
        for (uint256 i; i < n; ++i) {
            uint256 requested = params.deltas.shares[i];
            burns[i] = requested == type(uint256).max ? held[i] : requested;
            if (burns[i] == 0 || burns[i] > held[i]) revert InvalidAmounts();
        }
        uint256 before0 = IERC20(info.token0).balanceOf(address(this));
        uint256 before1 = IERC20(info.token1).balanceOf(address(this));
        IMetricOmmPool(params.position.pool)
            .removeLiquidity(
                address(this),
                params.position.salt,
                MetricLiquidityDelta(params.deltas.binIdxs, burns),
                params.extensionData
            );
        uint256 amount0 = IERC20(info.token0).balanceOf(address(this)) - before0;
        uint256 amount1 = IERC20(info.token1).balanceOf(address(this)) - before1;
        if (amount0 < params.amount0Min || amount1 < params.amount1Min) {
            revert InsufficientOutput(amount0, amount1);
        }
        uint256[] memory remaining =
            _shares(params.position, address(this), params.deltas.binIdxs);
        for (uint256 i; i < n; ++i) {
            if (held[i] - remaining[i] != burns[i]) revert InvalidAmounts();
        }
        emit MetricLiquidityRemoved(
            address(this),
            params.position.pool,
            params.position.salt,
            params.deltas.binIdxs,
            burns,
            amount0,
            amount1
        );
    }

    function _shares(
        MetricPosition calldata position,
        address owner,
        int256[] calldata bins
    ) private view returns (uint256[] memory shares) {
        shares = new uint256[](bins.length);
        for (uint256 i; i < bins.length; ++i) {
            shares[i] = dataProvider.positionBinShares(
                position.pool, owner, position.salt, int16(bins[i])
            );
        }
    }

    function _checkBins(
        MetricPoolImmutables memory info,
        int256[] calldata bins
    ) private pure {
        if (bins.length == 0) revert InvalidBins();
        for (uint256 i; i < bins.length; ++i) {
            if (
                bins[i] < info.lowestBin || bins[i] > info.highestBin
                    || bins[i] < type(int16).min || bins[i] > type(int16).max
                    || (i > 0 && bins[i] <= bins[i - 1])
            ) revert InvalidBins();
        }
    }

    function _approve(
        address token,
        uint256 amount
    ) private {
        SafeTransferLib.safeApprove(token, address(liquidityAdder), 0);
        if (amount != 0) {
            SafeTransferLib.safeApprove(token, address(liquidityAdder), amount);
        }
    }
}

contracts/interfaces/IMetricLiquidityConnector.sol

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

import {
    IMetricOmmFactory,
    MetricPoolImmutables
} from "contracts/interfaces/external/metric/IMetricOmm.sol";
import {
    MetricAddLiquidity,
    MetricRemoveLiquidity,
    MetricPosition
} from "contracts/structs/MetricStrategyStructs.sol";

interface IMetricLiquidityConnector {
    function metricFactory() external view returns (IMetricOmmFactory);
    function poolInfo(
        address pool
    ) external view returns (MetricPoolImmutables memory);
    function positionShares(
        MetricPosition calldata position,
        address owner,
        int256[] calldata bins
    ) external view returns (uint256[] memory);
    function underlyingAmounts(
        MetricPosition calldata position,
        address owner,
        int256[] calldata bins
    ) external view returns (uint256, uint256);
    function addLiquidity(
        MetricAddLiquidity calldata params
    ) external payable;
    function removeLiquidity(
        MetricRemoveLiquidity calldata params
    ) external payable;
}

contracts/interfaces/external/IWETH.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.8.9;

interface IWETH9 {
    function deposit() external payable;

    function withdraw(
        uint256 wad
    ) external;

    function approve(address guy, uint256 wad) external returns (bool);

    function balanceOf(
        address account
    ) external view returns (uint256);

    function allowance(
        address account,
        address spender
    ) external view returns (uint256);
}

contracts/interfaces/external/metric/IMetricOmm.sol

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

// Metric ABI subset. Source revisions: docs/Metric.md.
struct MetricPoolImmutables {
    address factory;
    address token0;
    address token1;
    uint256 token0ScaleMultiplier;
    uint256 token1ScaleMultiplier;
    uint256 initialScaledToken0PerShareE18;
    uint256 initialScaledToken1PerShareE18;
    uint256 minimalOperationalLiquidity;
    address immutablePriceProvider;
    int256 lowestBin;
    int256 highestBin;
    address extension1;
    address extension2;
    address extension3;
    address extension4;
    address extension5;
    address extension6;
    address extension7;
    uint256 beforeAddLiquidityOrder;
    uint256 afterAddLiquidityOrder;
    uint256 beforeRemoveLiquidityOrder;
    uint256 afterRemoveLiquidityOrder;
    uint256 beforeSwapOrder;
    uint256 afterSwapOrder;
}

struct MetricLiquidityDelta {
    int256[] binIdxs;
    uint256[] shares;
}

struct MetricBinPositionBounds {
    int16 minimalCurBin;
    uint104 minimalPosition;
    int16 maximalCurBin;
    uint104 maximalPosition;
}

interface IMetricOmmFactory {
    function isPool(
        address pool
    ) external view returns (bool);
}

interface IMetricOmmPool {
    function getImmutables() external view returns (MetricPoolImmutables memory);

    function getSellAndBuyPrices()
        external
        returns (uint128 sellPriceX64, uint128 buyPriceX64);

    function removeLiquidity(
        address owner,
        uint80 salt,
        MetricLiquidityDelta calldata deltas,
        bytes calldata extensionData
    ) external returns (uint256 amount0Removed, uint256 amount1Removed);
}

interface IMetricOmmLiquidityAdder {
    function addLiquidityWeighted(
        address pool,
        address owner,
        uint80 salt,
        MetricLiquidityDelta calldata weightDeltas,
        uint256 maxAmountToken0,
        uint256 maxAmountToken1,
        MetricBinPositionBounds calldata binPositionBounds,
        bytes calldata extensionData
    ) external payable returns (uint256 amount0Added, uint256 amount1Added);
}

interface IMetricOmmDataProvider {
    function slot0(
        address pool
    )
        external
        view
        returns (
            uint8 pauseLevel,
            int16 currentBin,
            uint104 positionInBin,
            int24 lowerDistanceE6,
            uint24 spreadFeeE6,
            uint24 notionalFeeE8,
            uint16 bidAskReferenceAsymmetryX8
        );

    function positionBinShares(
        address pool,
        address owner,
        uint80 salt,
        int16 bin
    ) external view returns (uint256);

    function binTotalShares(
        address pool,
        int16 bin
    ) external view returns (uint256);

    function binState(
        address pool,
        int16 bin
    )
        external
        view
        returns (
            uint104 token0BalanceScaled,
            uint104 token1BalanceScaled,
            uint16 lengthE6,
            uint16 addFeeBuyE6,
            uint16 addFeeSellE6
        );
}

contracts/interfaces/libraries/IBridgeLib.sol

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

interface IBridgeLib {
    error ZeroBridgeAmount();
    error NotDelegatecall();
    error BridgeFailed(bytes reason);
    error BridgeDidNotConsumeTokens();

    function bridge(
        address bridgeContract,
        bytes calldata bridgeCalldata,
        address token,
        uint256 amount
    ) external payable;
}

contracts/interfaces/libraries/IFeesLib.sol

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

import { Sickle } from "contracts/Sickle.sol";

interface IFeesLib {
    event FeeCharged(
        address strategy, bytes4 feeDescriptor, uint256 amount, address token
    );
    event TransactionCostCharged(address recipient, uint256 amount);

    function chargeFee(
        address strategy,
        bytes4 feeDescriptor,
        address feeToken,
        uint256 feeBasis
    ) external payable returns (uint256 remainder);

    function chargeFees(
        address strategy,
        bytes4 feeDescriptor,
        address[] memory feeTokens
    ) external payable;

    function getBalance(
        Sickle sickle,
        address token
    ) external view returns (uint256);
}

contracts/interfaces/libraries/ISwapLib.sol

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

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

interface ISwapLib {
    function swap(
        SwapParams memory swap
    ) external payable;

    function swapMultiple(
        SwapParams[] memory swaps
    ) external payable;
}

contracts/modules/DelegateModule.sol

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

import { SickleRegistry } from "contracts/SickleRegistry.sol";

/// @dev The executing Sickle, seen from inside a `delegatecall`. `Multicall`
/// declares `registry` as an immutable public getter, so `address(this)`
/// answers it whenever this code runs in a Sickle's context.
interface IRegistryHolder {
    function registry() external view returns (SickleRegistry);
}

contract DelegateModule {
    /// @notice Thrown when a connector is not a whitelisted Sickle target.
    /// @dev Shares a signature, and therefore the selector 0x47ccabe7, with
    /// `Multicall.TargetNotWhitelisted`, so both refusals decode identically.
    error TargetNotWhitelisted(address target);

    function _delegateTo(
        address to,
        bytes memory data
    ) internal returns (bytes memory) {
        (bool success, bytes memory result) = to.delegatecall(data);

        if (!success) {
            if (result.length == 0) revert();
            assembly {
                revert(add(32, result), mload(result))
            }
        }

        return result;
    }

    /// @notice Delegatecall a connector resolved through `ConnectorRegistry`.
    /// @dev `connectorOf()` answers from a registry whose admin is a separate
    /// role from the one that curates `SickleRegistry`, so a connector reached
    /// this way would otherwise run in the Sickle's storage and balance context
    /// without ever passing the whitelist `Multicall` enforces on every other
    /// delegatecall target. Two registrations disagreeing is not hypothetical:
    /// retired aggregator connectors have been removed from the target
    /// whitelist while their `connectorOf` mapping stayed live, leaving the
    /// retirement with no effect on this path.
    ///
    /// The registry is read from the executing Sickle rather than held as an
    /// immutable, so the check always resolves to the same allowlist that
    /// authorised the enclosing `multicall`, and a redeployed library cannot
    /// drift from it. Outside a Sickle there is no `registry()` to answer and
    /// the call reverts, which is the safe direction.
    function _delegateToConnector(
        address connector,
        bytes memory data
    ) internal returns (bytes memory) {
        SickleRegistry registry = IRegistryHolder(address(this)).registry();

        if (!registry.isWhitelistedTarget(connector)) {
            revert TargetNotWhitelisted(connector);
        }

        return _delegateTo(connector, data);
    }
}

contracts/structs/MetricSettingsStructs.sol

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

/// @notice Keeper policy for one Sickle/pool/salt position.
/// @dev Prices are the pool's native Q64.64 ratio. A zero price disables the
/// corresponding bound. Slippage, price impact and delay use the standard
/// keeper settings and are consumed during off-chain preparation.
struct MetricRebalanceConfig {
    uint16 bufferBinsBelow;
    uint16 bufferBinsAbove;
    uint16 targetBinsBelow;
    uint128 minPriceX64;
    uint128 maxPriceX64;
    uint16 slippageBps;
    uint16 priceImpactBps;
    uint8 delayMin;
}

struct MetricExitConfig {
    uint128 priceLowX64;
    uint128 priceHighX64;
    address tokenOutLow;
    address tokenOutHigh;
    uint16 slippageBps;
    uint16 priceImpactBps;
}

struct MetricSettings {
    bool autoRebalance;
    MetricRebalanceConfig rebalanceConfig;
    bool autoExit;
    MetricExitConfig exitConfig;
}

contracts/structs/MetricStrategyStructs.sol

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

import {
    MetricLiquidityDelta,
    MetricBinPositionBounds
} from "contracts/interfaces/external/metric/IMetricOmm.sol";
import { SwapParams } from "contracts/structs/SwapStructs.sol";

struct MetricPosition {
    address pool;
    uint80 salt;
}

struct MetricAddLiquidity {
    MetricPosition position;
    /// @dev Relative share weights scaled by the adder to fit the token caps.
    /// Bin indices must be strictly increasing.
    MetricLiquidityDelta weights;
    /// @dev Post-swap spending caps; MAX uses the available balance.
    uint256 amount0Max;
    uint256 amount1Max;
    uint256[] minShares;
    MetricBinPositionBounds bounds;
    bytes extensionData;
}

struct MetricRemoveLiquidity {
    MetricPosition position;
    /// @dev MAX burns all shares in that bin for this Sickle and salt.
    MetricLiquidityDelta deltas;
    /// @dev Minimum underlying proceeds before fees and swaps.
    uint256 amount0Min;
    uint256 amount1Min;
    bytes extensionData;
}

struct MetricIncrease {
    address[] tokensIn;
    uint256[] amountsIn;
    SwapParams[] swaps;
    MetricAddLiquidity liquidity;
    address[] sweepTokens;
}

struct MetricOutput {
    /// @dev ERC20 or a TransferLib native sentinel. Native/wrapped aliases
    /// count as one output asset.
    address token;
    /// @dev Minimum net proceeds, excluding pre-existing balances.
    /// Native output includes both native and wrapped-native proceeds.
    uint256 minAmount;
}

struct MetricWithdraw {
    MetricRemoveLiquidity liquidity;
    SwapParams[] swaps;
    MetricOutput[] outputs;
    address[] sweepTokens;
}

struct MetricMove {
    MetricRemoveLiquidity removal;
    MetricAddLiquidity addition;
    SwapParams[] swaps;
}

struct MetricAutomatedExit {
    MetricRemoveLiquidity removal;
    SwapParams[] swaps;
    uint256 minimumOutput;
}

struct MetricBridgeDeposit {
    MetricAddLiquidity addition;
    SwapParams[] swaps;
}

struct MetricBridgeWithdrawal {
    MetricRemoveLiquidity removal;
    SwapParams[] swaps;
    address bridge;
    bytes bridgeCalldata;
    address bridgeToken;
    uint256 bridgeAmount;
}

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

lib/openzeppelin-contracts/contracts/proxy/Clones.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (proxy/Clones.sol)

pragma solidity ^0.8.0;

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 *
 * _Available since v3.4._
 */
library Clones {
    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(0, 0x09, 0x37)
        }
        require(instance != address(0), "ERC1167: create failed");
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(0, 0x09, 0x37, salt)
        }
        require(instance != address(0), "ERC1167: create2 failed");
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := keccak256(add(ptr, 0x43), 0x55)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(address implementation, bytes32 salt)
        internal
        view
        returns (address predicted)
    {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}

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

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

pragma solidity ^0.8.2;

import "../../utils/Address.sol";

/**
 * @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]
 * ```
 * 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 Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 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 functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _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 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _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() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @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 {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized < type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

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

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

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/utils/Address.sol

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

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @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://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @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, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * 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.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @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`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) 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
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

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

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

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

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10**64) {
                value /= 10**64;
                result += 64;
            }
            if (value >= 10**32) {
                value /= 10**32;
                result += 32;
            }
            if (value >= 10**16) {
                value /= 10**16;
                result += 16;
            }
            if (value >= 10**8) {
                value /= 10**8;
                result += 8;
            }
            if (value >= 10**4) {
                value /= 10**4;
                result += 4;
            }
            if (value >= 10**2) {
                value /= 10**2;
                result += 2;
            }
            if (value >= 10**1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
        }
    }
}

lib/solmate/src/tokens/ERC20.sol

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event Transfer(address indexed from, address indexed to, uint256 amount);

    event Approval(address indexed owner, address indexed spender, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                            METADATA STORAGE
    //////////////////////////////////////////////////////////////*/

    string public name;

    string public symbol;

    uint8 public immutable decimals;

    /*//////////////////////////////////////////////////////////////
                              ERC20 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 public totalSupply;

    mapping(address => uint256) public balanceOf;

    mapping(address => mapping(address => uint256)) public allowance;

    /*//////////////////////////////////////////////////////////////
                            EIP-2612 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 internal immutable INITIAL_CHAIN_ID;

    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;

    mapping(address => uint256) public nonces;

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(
        string memory _name,
        string memory _symbol,
        uint8 _decimals
    ) {
        name = _name;
        symbol = _symbol;
        decimals = _decimals;

        INITIAL_CHAIN_ID = block.chainid;
        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
    }

    /*//////////////////////////////////////////////////////////////
                               ERC20 LOGIC
    //////////////////////////////////////////////////////////////*/

    function approve(address spender, uint256 amount) public virtual returns (bool) {
        allowance[msg.sender][spender] = amount;

        emit Approval(msg.sender, spender, amount);

        return true;
    }

    function transfer(address to, uint256 amount) public virtual returns (bool) {
        balanceOf[msg.sender] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(msg.sender, to, amount);

        return true;
    }

    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual returns (bool) {
        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.

        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;

        balanceOf[from] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(from, to, amount);

        return true;
    }

    /*//////////////////////////////////////////////////////////////
                             EIP-2612 LOGIC
    //////////////////////////////////////////////////////////////*/

    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");

        // Unchecked because the only math done is incrementing
        // the owner's nonce which cannot realistically overflow.
        unchecked {
            address recoveredAddress = ecrecover(
                keccak256(
                    abi.encodePacked(
                        "\x19\x01",
                        DOMAIN_SEPARATOR(),
                        keccak256(
                            abi.encode(
                                keccak256(
                                    "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                ),
                                owner,
                                spender,
                                value,
                                nonces[owner]++,
                                deadline
                            )
                        )
                    )
                ),
                v,
                r,
                s
            );

            require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");

            allowance[recoveredAddress][spender] = value;
        }

        emit Approval(owner, spender, value);
    }

    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
    }

    function computeDomainSeparator() internal view virtual returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                    keccak256(bytes(name)),
                    keccak256("1"),
                    block.chainid,
                    address(this)
                )
            );
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL MINT/BURN LOGIC
    //////////////////////////////////////////////////////////////*/

    function _mint(address to, uint256 amount) internal virtual {
        totalSupply += amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(address(0), to, amount);
    }

    function _burn(address from, uint256 amount) internal virtual {
        balanceOf[from] -= amount;

        // Cannot underflow because a user's balance
        // will never be larger than the total supply.
        unchecked {
            totalSupply -= amount;
        }

        emit Transfer(from, address(0), amount);
    }
}

lib/solmate/src/utils/SafeTransferLib.sol

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

import {ERC20} from "../tokens/ERC20.sol";

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
    /*//////////////////////////////////////////////////////////////
                                ERRORS
    //////////////////////////////////////////////////////////////*/

    error ETHTransferFailed();
    error TransferFromFailed();
    error TransferFailed();
    error ApproveFailed();

    /*//////////////////////////////////////////////////////////////
                             ETH OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferETH(address to, uint256 amount) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Transfer the ETH and store if it succeeded or not.
            success := call(gas(), to, amount, 0, 0, 0, 0)
        }

        if (!success) revert ETHTransferFailed();
    }

    /*//////////////////////////////////////////////////////////////
                            ERC20 OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferFrom(
        address token,
        address from,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
            mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
            )
        }

        if (!success) revert TransferFromFailed();
    }

    function safeTransfer(
        address token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        if (!success) revert TransferFailed();
    }

    function safeApprove(
        address token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        if (!success) revert ApproveFailed();
    }
}
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/",
    "forge-std/=lib/forge-std/src/",
    "morpho-blue/=lib/morpho-blue/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.