Overview
ETH Balance
ETH Value
$0.00Latest 8 from a total of 8 transactions
| Transaction Hash |
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
| 0xa5214e18 | 37100260 | 19 days ago | IN | 0.001 ETH | 0 | ||||
| 0xf1716acf | 36505403 | 26 days ago | IN | 0.001 ETH | 0 | ||||
| 0xf1716acf | 36505013 | 26 days ago | IN | 0.001 ETH | 0 | ||||
| 0xf1716acf | 36504978 | 26 days ago | IN | 0.001 ETH | 0.00000001 | ||||
| 0xf1716acf | 36504395 | 26 days ago | IN | 0.001 ETH | 0 | ||||
| 0xf1716acf | 36504371 | 26 days ago | IN | 0.001 ETH | 0 | ||||
| Set Authorized S... | 36502969 | 26 days ago | IN | 0 ETH | 0.00000004 | ||||
| Set Shared Volat... | 36502962 | 26 days ago | IN | 0 ETH | 0.00000004 |
Latest 6 internal transactions
| Parent Transaction Hash | Block | From | To | |||
|---|---|---|---|---|---|---|
| 37100260 | 19 days ago | 0.001 ETH | ||||
| 37100260 | 19 days ago | Contract Creation | 0 ETH | |||
| 36504978 | 26 days ago | 0.001 ETH | ||||
| 36504978 | 26 days ago | Contract Creation | 0 ETH | |||
| 36504395 | 26 days ago | Contract Creation | 0 ETH | |||
| 36504371 | 26 days ago | Contract Creation | 0 ETH |
Cross-Chain Transactions
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {LPFeeLibrary} from "v4-core/libraries/LPFeeLibrary.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId} from "v4-core/types/PoolId.sol";
import {Currency, CurrencyLibrary} from "v4-core/types/Currency.sol";
import {LimitOrderManager} from "./LimitOrderManager.sol";
import {LimitOrderLens} from "./periphery/LimitOrderLens.sol";
import {LimitOrderHook} from "./hooks/LimitOrderHook.sol";
// Limit Order Hooks (with limit order execution)
import {DynamicFeeLimitOrderHookRegistry} from "./hooks/DynamicFeeLimitOrderHookRegistry.sol";
import {VolatilityDynamicFeeLimitOrderHookRegistry} from "./hooks/VolatilityDynamicFeeLimitOrderHookRegistry.sol";
import {IDynamicFeeLimitOrderHook} from "./interfaces/IDynamicFeeLimitOrderHook.sol";
import {IVolatilityDynamicFeeLimitOrderHook} from "./interfaces/IVolatilityDynamicFeeLimitOrderHook.sol";
// Fee-Only Hooks (no limit order execution)
import {DynamicFeeHookRegistry} from "./hooks/DynamicFeeHookRegistry.sol";
import {VolatilityDynamicFeeHookRegistry} from "./hooks/VolatilityDynamicFeeHookRegistry.sol";
import {IDynamicFeeHook} from "./interfaces/IDynamicFeeHook.sol";
import {IVolatilityDynamicFeeHook} from "./interfaces/IVolatilityDynamicFeeHook.sol";
import {HookMiner} from "v4-periphery/src/utils/HookMiner.sol";
import {CurrencySettler} from "./libraries/CurrencySettler.sol";
import {TransientStateLibrary} from "v4-core/libraries/TransientStateLibrary.sol";
import {Hooks} from "v4-core/libraries/Hooks.sol";
import {IHooks} from "v4-core/interfaces/IHooks.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {MultiPositionFactory} from "../MultiPositionManager/MultiPositionFactory.sol";
import {IMultiPositionManager} from "../MultiPositionManager/interfaces/IMultiPositionManager.sol";
import {RebalanceLogic} from "../MultiPositionManager/libraries/RebalanceLogic.sol";
import {VolatilityOracle} from "./libraries/VolatilityOracle.sol";
/**
* @title OrderBookFactory
* @notice Factory contract for creating Uniswap V4 pools with limit order support and initial liquidity
* @dev This contract creates pools and mints initial liquidity using PositionManager's command interface.
* Users must approve their tokens directly to the OrderBookFactory before calling pool creation functions.
*
* WARNING: TOKEN COMPATIBILITY
* ============================
* This contract and the associated LimitOrderManager DO NOT support the following token types:
*
* 1. Fee-on-transfer tokens: Tokens that charge a fee on transfer will cause transactions to fail
* because the received amount will not match the expected amount, breaking order accounting.
*
* 2. Rebasing tokens: Tokens that adjust balances will cause unpredictable behavior as position
* liquidity and order amounts will not match expected values after rebasing events.
*
* 3. Tokens with non-standard transfer behaviors: Including tokens with transfer hooks that can
* fail, pause mechanisms, or blacklisting features may cause orders to become stuck or fail.
*
* Using unsupported token types may result in:
* - Failed order creation, cancellation, or claiming
* - Loss of funds if tokens change behavior after pool creation
* - Inability to interact with positions
*
* POOLS ARE CREATED AT YOUR OWN RISK. Always verify token compatibility before creating pools.
*/
contract OrderBookFactory is AccessControl {
using CurrencySettler for Currency;
using CurrencyLibrary for Currency;
using TransientStateLibrary for IPoolManager;
using StateLibrary for IPoolManager;
using SafeERC20 for IERC20;
// Custom errors for better gas efficiency
error ZeroAddress();
error TokenOrderingIncorrect();
error NoLiquidityProvided();
error DynamicFeeNotAllowed();
error InsufficientETH();
error ETHRefundFailed();
error NoFeesToWithdraw();
error ETHTransferFailed();
error InvalidAmount();
error SharedVolatilityOracleNotSet();
error PoolAlreadyReserved();
error PoolReservedForOther();
error NotAuthorizedStrategyFactory();
error InvalidHookAddress();
bytes32 public constant FEE_COLLECTOR_ROLE = keccak256("FEE_COLLECTOR_ROLE");
// Struct to store pool information
struct PoolInfo {
bytes32 poolId;
PoolKey poolKey;
bool isDynamic;
}
// Struct for regular pool creation parameters
struct RegularPoolParams {
Currency currency0;
Currency currency1;
uint24 fee;
int24 tickSpacing;
uint160 sqrtPriceX96;
uint256 deposit0Desired;
uint256 deposit1Desired;
address managerOwner;
string name;
address to;
bool useSwap;
RebalanceLogic.SwapParams swapParams;
uint256[2][] inMin;
IMultiPositionManager.RebalanceParams rebalanceParams;
}
// Struct for dynamic pool creation parameters
struct DynamicPoolParams {
Currency currency0;
Currency currency1;
int24 tickSpacing;
uint160 sqrtPriceX96;
bytes32 salt;
uint24 initialFee;
uint256 deposit0Desired;
uint256 deposit1Desired;
address managerOwner;
string name;
address to;
bool useSwap;
RebalanceLogic.SwapParams swapParams;
uint256[2][] inMin;
IMultiPositionManager.RebalanceParams rebalanceParams;
}
// Struct for volatility dynamic pool creation parameters
struct VolatilityDynamicPoolParams {
Currency currency0;
Currency currency1;
int24 tickSpacing;
uint160 sqrtPriceX96;
bytes32 salt;
uint24 baseFee;
uint24 surgeMultiplier;
uint32 surgeDuration;
uint24 initialMaxTicksPerBlock;
uint256 deposit0Desired;
uint256 deposit1Desired;
address managerOwner;
string name;
address to;
bool useSwap;
RebalanceLogic.SwapParams swapParams;
uint256[2][] inMin;
IMultiPositionManager.RebalanceParams rebalanceParams;
address hookOwner; // Who owns the hook (can modify fee params). If zero, uses msg.sender.
}
LimitOrderManager public limitOrderManager;
LimitOrderLens public limitOrderLens;
IPoolManager public poolManager;
LimitOrderHook public limitOrderHook;
MultiPositionFactory public immutable multiPositionFactory;
// Pool creation fee settings for each pool type
uint256 public regularPoolCreationFee;
uint256 public dynamicPoolCreationFee;
uint256 public volatilityDynamicCreationFee;
uint256 public collectedFees;
// Bytecode registries for limit order hook deployments
DynamicFeeLimitOrderHookRegistry public dynamicFeeLimitOrderRegistry;
VolatilityDynamicFeeLimitOrderHookRegistry public volatilityDynamicLimitOrderRegistry;
// Bytecode registries for fee-only hook deployments
DynamicFeeHookRegistry public dynamicFeeRegistry;
VolatilityDynamicFeeHookRegistry public volatilityDynamicFeeRegistry;
// One dynamic fee limit order hook per creator
mapping(address => address) public creatorDynamicLimitOrderHooks;
// One volatility dynamic fee limit order hook per creator
mapping(address => address) public creatorVolatilityDynamicLimitOrderHooks;
// One dynamic fee hook (fee-only) per creator
mapping(address => address) public creatorDynamicFeeHooks;
// One volatility dynamic fee hook (fee-only) per creator
mapping(address => address) public creatorVolatilityDynamicFeeHooks;
// Track pool creators using pool ID as key
mapping(bytes32 => address) public poolCreators;
// Track pool info by user address (creator)
mapping(address => PoolInfo[]) public userToPoolInfo;
// Shared VolatilityOracle for all per-creator hooks
address public sharedVolatilityOracle;
// Reservation system for front-running protection
mapping(bytes32 => address) public reservedPools; // poolId => authorized strategy
address public authorizedStrategyFactory;
// Events for tracking pool creation
event PoolCreated(bytes32 indexed poolId, address indexed creator, address indexed hook, uint24 fee);
event PoolInfoStored(address indexed user, bytes32 indexed poolId, bool isDynamic);
event SharedVolatilityOracleSet(address indexed oracle);
event RegularPoolCreationFeeUpdated(uint256 newFee);
event DynamicPoolCreationFeeUpdated(uint256 newFee);
event VolatilityDynamicCreationFeeUpdated(uint256 newFee);
event PoolCreationFeeCollected(address indexed creator, uint256 fee);
event FeesWithdrawn(address indexed recipient, uint256 amount);
event DynamicFeeRegistryUpdated(address indexed oldRegistry, address indexed newRegistry);
event VolatilityDynamicRegistryUpdated(address indexed oldRegistry, address indexed newRegistry);
event PoolReserved(bytes32 indexed poolId, address indexed strategy);
event PoolReservationCleared(bytes32 indexed poolId);
event AuthorizedStrategyFactorySet(address indexed factory);
event VolatilityHookDeployed(address indexed hookOwner, address indexed hookAddr);
constructor(
address _limitOrderLens,
address _limitOrderHook,
address _multiPositionFactory,
address _dynamicFeeLimitOrderRegistry,
address _volatilityDynamicLimitOrderRegistry,
address _dynamicFeeRegistry,
address _volatilityDynamicFeeRegistry
) {
if (_limitOrderHook == address(0)) revert ZeroAddress();
if (_multiPositionFactory == address(0)) revert ZeroAddress();
if (_dynamicFeeLimitOrderRegistry == address(0)) revert ZeroAddress();
if (_volatilityDynamicLimitOrderRegistry == address(0)) revert ZeroAddress();
if (_dynamicFeeRegistry == address(0)) revert ZeroAddress();
if (_volatilityDynamicFeeRegistry == address(0)) revert ZeroAddress();
limitOrderLens = LimitOrderLens(_limitOrderLens);
poolManager = limitOrderLens.poolManager();
limitOrderManager = limitOrderLens.limitOrderManager();
// Store bytecode registries for limit order hooks
dynamicFeeLimitOrderRegistry = DynamicFeeLimitOrderHookRegistry(_dynamicFeeLimitOrderRegistry);
volatilityDynamicLimitOrderRegistry = VolatilityDynamicFeeLimitOrderHookRegistry(_volatilityDynamicLimitOrderRegistry);
// Store bytecode registries for fee-only hooks
dynamicFeeRegistry = DynamicFeeHookRegistry(_dynamicFeeRegistry);
volatilityDynamicFeeRegistry = VolatilityDynamicFeeHookRegistry(_volatilityDynamicFeeRegistry);
limitOrderHook = LimitOrderHook(_limitOrderHook);
multiPositionFactory = MultiPositionFactory(_multiPositionFactory);
// Grant roles to deployer
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(FEE_COLLECTOR_ROLE, msg.sender);
}
/**
* @notice Create a regular pool with limit order hook and deploy MultiPositionManager
* @dev Creates pool and deploys MPM with initial liquidity
* @dev WARNING: Do not use with fee-on-transfer, rebasing, or other non-standard tokens.
* Such tokens will cause order failures and potential loss of funds.
*/
function createRegularPoolWithManager(
RegularPoolParams calldata params
) external payable returns (PoolKey memory poolKey, address mpm) {
// Validate inputs
if (Currency.unwrap(params.currency0) >= Currency.unwrap(params.currency1)) revert TokenOrderingIncorrect();
if (params.managerOwner == address(0)) revert ZeroAddress();
if (params.to == address(0)) revert ZeroAddress();
if (params.deposit0Desired == 0 && params.deposit1Desired == 0) revert NoLiquidityProvided();
if (params.fee == LPFeeLibrary.DYNAMIC_FEE_FLAG) revert DynamicFeeNotAllowed();
if (params.useSwap && params.swapParams.aggregatorAddress == address(0)) revert ZeroAddress();
// Create the pool
poolKey = PoolKey({
currency0: params.currency0,
currency1: params.currency1,
fee: params.fee,
tickSpacing: params.tickSpacing,
hooks: limitOrderHook
});
// Initialize pool and store info
_initializePool(poolKey, params.sqrtPriceX96, false);
// Calculate ETH for deployment and collect fees
uint256 ethForDeployment = _validateETHAndCollectFee(params.currency0, params.deposit0Desired, regularPoolCreationFee);
// Deploy MultiPositionManager first
mpm = _deployMultiPositionManager(
poolKey,
ethForDeployment,
params.managerOwner,
params.name,
params.deposit0Desired,
params.deposit1Desired,
params.to,
params.useSwap,
params.swapParams,
params.inMin,
params.rebalanceParams
);
// Refund excess ETH
_refundExcessETH(params.currency0, params.deposit0Desired, regularPoolCreationFee);
}
/**
* @notice Create a dynamic fee pool with limit orders and deploy MultiPositionManager
* @dev Creates pool with dynamic fee + limit order hook and deploys MPM with initial liquidity
* @dev WARNING: Do not use with fee-on-transfer, rebasing, or other non-standard tokens.
* Such tokens will cause order failures and potential loss of funds.
*/
function createDynamicLimitOrderPoolWithManager(
DynamicPoolParams calldata params
) external payable returns (PoolKey memory poolKey, address mpm) {
// Validate inputs
if (Currency.unwrap(params.currency0) >= Currency.unwrap(params.currency1)) revert TokenOrderingIncorrect();
if (params.managerOwner == address(0)) revert ZeroAddress();
if (params.to == address(0)) revert ZeroAddress();
if (params.deposit0Desired == 0 && params.deposit1Desired == 0) revert NoLiquidityProvided();
if (params.useSwap && params.swapParams.aggregatorAddress == address(0)) revert ZeroAddress();
// Deploy or get dynamic fee limit order hook
address hookAddr = creatorDynamicLimitOrderHooks[msg.sender];
if (hookAddr == address(0)) {
hookAddr = _deployDynamicFeeLimitOrderHook(params.salt);
creatorDynamicLimitOrderHooks[msg.sender] = hookAddr;
}
// Create the pool
poolKey = PoolKey({
currency0: params.currency0,
currency1: params.currency1,
fee: LPFeeLibrary.DYNAMIC_FEE_FLAG,
tickSpacing: params.tickSpacing,
hooks: IHooks(hookAddr)
});
// Register and initialize
IDynamicFeeLimitOrderHook(hookAddr).registerPool(poolKey);
_initializePool(poolKey, params.sqrtPriceX96, true);
// Set initial fee if specified
if (params.initialFee > 0) {
IDynamicFeeLimitOrderHook(hookAddr).updateDynamicLPFee(poolKey, params.initialFee);
}
// Calculate ETH for deployment and collect fees
uint256 ethForDeployment = _validateETHAndCollectFee(params.currency0, params.deposit0Desired, dynamicPoolCreationFee);
// Deploy MultiPositionManager
mpm = _deployMultiPositionManager(
poolKey,
ethForDeployment,
params.managerOwner,
params.name,
params.deposit0Desired,
params.deposit1Desired,
params.to,
params.useSwap,
params.swapParams,
params.inMin,
params.rebalanceParams
);
// Refund excess ETH
_refundExcessETH(params.currency0, params.deposit0Desired, dynamicPoolCreationFee);
}
/**
* @notice Create a volatility dynamic fee pool with limit orders and deploy MultiPositionManager
* @dev Creates pool with volatility-based dynamic fee adjustment + limit orders and deploys MPM with initial liquidity
* @dev WARNING: Do not use with fee-on-transfer, rebasing, or other non-standard tokens.
* Such tokens will cause order failures and potential loss of funds.
*/
function createVolatilityDynamicLimitOrderPoolWithManager(
VolatilityDynamicPoolParams calldata params
) external payable returns (PoolKey memory poolKey, address mpm) {
// Validate inputs
if (Currency.unwrap(params.currency0) >= Currency.unwrap(params.currency1)) revert TokenOrderingIncorrect();
if (params.managerOwner == address(0)) revert ZeroAddress();
if (params.to == address(0)) revert ZeroAddress();
if (params.deposit0Desired == 0 && params.deposit1Desired == 0) revert NoLiquidityProvided();
if (params.surgeMultiplier > 100000) revert InvalidAmount(); // Max 10x multiplier (100000 BPS)
if (params.surgeMultiplier < 10000) revert InvalidAmount(); // Min 1x multiplier (10000 BPS)
if (params.useSwap && params.swapParams.aggregatorAddress == address(0)) revert ZeroAddress();
// Track creation fee (may be exempted for reserved pools)
uint256 creationFee;
// Scoped block to limit stack depth - hookAddr only needed for pool setup
{
// Determine which hook to use and check reservations
// wasReserved indicates if pool was reserved (fee should be skipped - charged at TokenLaunchFactory level)
(address hookAddr, bool wasReserved) = _getOrCheckVolatilityLimitOrderHook(params);
// Skip fee for reserved pools (TokenLaunchFactory collects fees instead)
creationFee = wasReserved ? 0 : volatilityDynamicCreationFee;
// Create the pool
poolKey = PoolKey({
currency0: params.currency0,
currency1: params.currency1,
fee: LPFeeLibrary.DYNAMIC_FEE_FLAG,
tickSpacing: params.tickSpacing,
hooks: IHooks(hookAddr)
});
// Register pool with volatility parameters (only if not already registered)
IVolatilityDynamicFeeLimitOrderHook(hookAddr).registerPool(
poolKey,
params.baseFee,
params.surgeMultiplier,
params.surgeDuration,
params.initialMaxTicksPerBlock
);
_initializePool(poolKey, params.sqrtPriceX96, true);
}
// Calculate ETH for deployment and collect fees
uint256 ethForDeployment = _validateETHAndCollectFee(params.currency0, params.deposit0Desired, creationFee);
// Deploy MultiPositionManager
mpm = _deployMultiPositionManager(
poolKey,
ethForDeployment,
params.managerOwner,
params.name,
params.deposit0Desired,
params.deposit1Desired,
params.to,
params.useSwap,
params.swapParams,
params.inMin,
params.rebalanceParams
);
// Refund excess ETH
_refundExcessETH(params.currency0, params.deposit0Desired, creationFee);
}
// ============ FEE-ONLY POOL CREATION FUNCTIONS (NO LIMIT ORDERS) ============
/**
* @notice Create a dynamic fee pool (fee-only, no limit orders) and deploy MultiPositionManager
* @dev Creates pool with fee-only dynamic fee hook and deploys MPM with initial liquidity
* @dev WARNING: Do not use with fee-on-transfer, rebasing, or other non-standard tokens.
*/
function createDynamicFeePoolWithManager(
DynamicPoolParams calldata params
) external payable returns (PoolKey memory poolKey, address mpm) {
// Validate inputs
if (Currency.unwrap(params.currency0) >= Currency.unwrap(params.currency1)) revert TokenOrderingIncorrect();
if (params.managerOwner == address(0)) revert ZeroAddress();
if (params.to == address(0)) revert ZeroAddress();
if (params.deposit0Desired == 0 && params.deposit1Desired == 0) revert NoLiquidityProvided();
if (params.useSwap && params.swapParams.aggregatorAddress == address(0)) revert ZeroAddress();
// Deploy or get fee-only dynamic fee hook
address hookAddr = creatorDynamicFeeHooks[msg.sender];
if (hookAddr == address(0)) {
hookAddr = _deployDynamicFeeHook(params.salt);
creatorDynamicFeeHooks[msg.sender] = hookAddr;
}
// Create the pool
poolKey = PoolKey({
currency0: params.currency0,
currency1: params.currency1,
fee: LPFeeLibrary.DYNAMIC_FEE_FLAG,
tickSpacing: params.tickSpacing,
hooks: IHooks(hookAddr)
});
// Register and initialize (fee-only - no limit order integration)
IDynamicFeeHook(hookAddr).registerPool(poolKey);
_initializePoolFeeOnly(poolKey, params.sqrtPriceX96);
// Set initial fee if specified
if (params.initialFee > 0) {
IDynamicFeeHook(hookAddr).updateDynamicLPFee(poolKey, params.initialFee);
}
// Calculate ETH for deployment and collect fees
uint256 ethForDeployment = _validateETHAndCollectFee(params.currency0, params.deposit0Desired, dynamicPoolCreationFee);
// Deploy MultiPositionManager
mpm = _deployMultiPositionManager(
poolKey,
ethForDeployment,
params.managerOwner,
params.name,
params.deposit0Desired,
params.deposit1Desired,
params.to,
params.useSwap,
params.swapParams,
params.inMin,
params.rebalanceParams
);
// Refund excess ETH
_refundExcessETH(params.currency0, params.deposit0Desired, dynamicPoolCreationFee);
}
/**
* @notice Create a volatility dynamic fee pool (fee-only, no limit orders) and deploy MultiPositionManager
* @dev Creates pool with volatility-based surge fees but no limit order execution
* @dev WARNING: Do not use with fee-on-transfer, rebasing, or other non-standard tokens.
*/
function createVolatilityDynamicFeePoolWithManager(
VolatilityDynamicPoolParams calldata params
) external payable returns (PoolKey memory poolKey, address mpm) {
// Validate inputs
if (Currency.unwrap(params.currency0) >= Currency.unwrap(params.currency1)) revert TokenOrderingIncorrect();
if (params.managerOwner == address(0)) revert ZeroAddress();
if (params.to == address(0)) revert ZeroAddress();
if (params.deposit0Desired == 0 && params.deposit1Desired == 0) revert NoLiquidityProvided();
if (params.surgeMultiplier > 100000) revert InvalidAmount(); // Max 10x multiplier (100000 BPS)
if (params.surgeMultiplier < 10000) revert InvalidAmount(); // Min 1x multiplier (10000 BPS)
if (params.useSwap && params.swapParams.aggregatorAddress == address(0)) revert ZeroAddress();
// Scoped block to limit stack depth
{
// Determine hook owner
address owner = params.hookOwner != address(0) ? params.hookOwner : msg.sender;
// Deploy or get fee-only volatility dynamic fee hook
address hookAddr = creatorVolatilityDynamicFeeHooks[owner];
if (hookAddr == address(0)) {
// Deploy with pre-computed salt from params (NOT on-chain computation)
hookAddr = _deployVolatilityDynamicFeeHook(params.salt, owner);
// Verify deployed address has correct hook flags
uint160 hookFlags = uint160(hookAddr) & Hooks.ALL_HOOK_MASK;
uint160 requiredFlags = Hooks.BEFORE_SWAP_FLAG | Hooks.AFTER_SWAP_FLAG;
if ((hookFlags & requiredFlags) != requiredFlags) {
revert InvalidHookAddress();
}
creatorVolatilityDynamicFeeHooks[owner] = hookAddr;
// Register newly deployed hook with the shared oracle
VolatilityOracle(sharedVolatilityOracle).addAuthorizedHook(hookAddr);
emit VolatilityHookDeployed(owner, hookAddr);
}
// Create the pool
poolKey = PoolKey({
currency0: params.currency0,
currency1: params.currency1,
fee: LPFeeLibrary.DYNAMIC_FEE_FLAG,
tickSpacing: params.tickSpacing,
hooks: IHooks(hookAddr)
});
// Register pool with volatility parameters (fee-only - no limit order integration)
IVolatilityDynamicFeeHook(hookAddr).registerPool(
poolKey,
params.baseFee,
params.surgeMultiplier,
params.surgeDuration,
params.initialMaxTicksPerBlock
);
_initializePoolFeeOnly(poolKey, params.sqrtPriceX96);
}
// Calculate ETH for deployment and collect fees
uint256 ethForDeployment = _validateETHAndCollectFee(params.currency0, params.deposit0Desired, volatilityDynamicCreationFee);
// Deploy MultiPositionManager
mpm = _deployMultiPositionManager(
poolKey,
ethForDeployment,
params.managerOwner,
params.name,
params.deposit0Desired,
params.deposit1Desired,
params.to,
params.useSwap,
params.swapParams,
params.inMin,
params.rebalanceParams
);
// Refund excess ETH
_refundExcessETH(params.currency0, params.deposit0Desired, volatilityDynamicCreationFee);
}
// ============ END FEE-ONLY POOL CREATION FUNCTIONS ============
function _initializePool(PoolKey memory poolKey, uint160 sqrtPriceX96, bool isDynamic) internal {
poolManager.initialize(poolKey, sqrtPriceX96);
limitOrderLens.addPoolId(poolKey.toId(), poolKey);
// Store pool creator information
bytes32 poolId = PoolId.unwrap(poolKey.toId());
poolCreators[poolId] = msg.sender;
userToPoolInfo[msg.sender].push(PoolInfo({
poolId: poolId,
poolKey: poolKey,
isDynamic: isDynamic
}));
emit PoolCreated(poolId, msg.sender, address(poolKey.hooks), isDynamic ? LPFeeLibrary.DYNAMIC_FEE_FLAG : poolKey.fee);
emit PoolInfoStored(msg.sender, poolId, isDynamic);
// Whitelist the pool and enable the hook
limitOrderManager.setWhitelistedPool(poolKey.toId(), true);
limitOrderManager.enableHook(address(poolKey.hooks));
}
/// @notice Initialize a pool for fee-only hooks (no limit order integration)
function _initializePoolFeeOnly(PoolKey memory poolKey, uint160 sqrtPriceX96) internal {
poolManager.initialize(poolKey, sqrtPriceX96);
limitOrderLens.addPoolId(poolKey.toId(), poolKey);
// Store pool creator information
bytes32 poolId = PoolId.unwrap(poolKey.toId());
poolCreators[poolId] = msg.sender;
userToPoolInfo[msg.sender].push(PoolInfo({
poolId: poolId,
poolKey: poolKey,
isDynamic: true
}));
emit PoolCreated(poolId, msg.sender, address(poolKey.hooks), LPFeeLibrary.DYNAMIC_FEE_FLAG);
emit PoolInfoStored(msg.sender, poolId, true);
// Note: No limitOrderManager integration for fee-only hooks
}
/**
* @notice Validate ETH amount and collect pool creation fees
* @param currency0 The first currency
* @param deposit0Desired Amount of currency0 to deposit
* @param creationFee The pool creation fee to collect
* @return ethForDeployment Amount of ETH to forward to MultiPositionFactory
*/
function _validateETHAndCollectFee(
Currency currency0,
uint256 deposit0Desired,
uint256 creationFee
) internal returns (uint256 ethForDeployment) {
// Calculate total ETH needed
uint256 ethNeeded = creationFee;
if (currency0.isAddressZero()) {
ethNeeded += deposit0Desired;
ethForDeployment = deposit0Desired;
}
if (msg.value < ethNeeded) revert InsufficientETH();
// Collect pool creation fee
if (creationFee > 0) {
collectedFees += creationFee;
emit PoolCreationFeeCollected(msg.sender, creationFee);
}
}
/**
* @notice Refund excess ETH to the user
* @param currency0 The first currency
* @param deposit0Desired Amount of currency0 deposited
* @param creationFee The pool creation fee collected
*/
function _refundExcessETH(
Currency currency0,
uint256 deposit0Desired,
uint256 creationFee
) internal {
uint256 ethUsed = creationFee;
if (currency0.isAddressZero()) {
ethUsed += deposit0Desired;
}
uint256 ethRemaining = msg.value - ethUsed;
if (ethRemaining > 0) {
(bool success, ) = msg.sender.call{value: ethRemaining}("");
if (!success) revert ETHRefundFailed();
}
}
/**
* @notice Transfer tokens from user to OrderBookFactory
* @param currency0 First currency
* @param currency1 Second currency
* @param amount0 Amount of currency0 to transfer
* @param amount1 Amount of currency1 to transfer
*/
function _transferTokensFromUser(
Currency currency0,
Currency currency1,
uint256 amount0,
uint256 amount1
) internal {
if (!currency0.isAddressZero() && amount0 > 0) {
IERC20(Currency.unwrap(currency0)).safeTransferFrom(msg.sender, address(this), amount0);
}
if (amount1 > 0) {
IERC20(Currency.unwrap(currency1)).safeTransferFrom(msg.sender, address(this), amount1);
}
}
/**
* @notice Approve tokens for future MultiPositionManager
* @param currency0 First currency
* @param currency1 Second currency
* @param amount0 Amount of currency0 to approve
* @param amount1 Amount of currency1 to approve
* @param mpm Address of MultiPositionManager to approve
*/
function _approveTokensForMPM(
Currency currency0,
Currency currency1,
uint256 amount0,
uint256 amount1,
address mpm
) internal {
if (!currency0.isAddressZero() && amount0 > 0) {
IERC20(Currency.unwrap(currency0)).forceApprove(mpm, amount0);
}
if (amount1 > 0) {
IERC20(Currency.unwrap(currency1)).forceApprove(mpm, amount1);
}
}
/**
* @notice Deploy MultiPositionManager via MultiPositionFactory
* @param poolKey The pool key
* @param ethForDeployment Amount of ETH to forward to the factory
* @param managerOwner Owner of the MultiPositionManager
* @param name Name for the MPM
* @param deposit0Desired Amount of currency0 to deposit
* @param deposit1Desired Amount of currency1 to deposit
* @param to Recipient of LP tokens
* @param useSwap Whether to use swap during deployment
* @param swapParams Swap parameters (if useSwap is true)
* @param inMin Minimum amounts for deposit
* @param rebalanceParams Rebalance parameters
* @return mpm Address of the deployed MultiPositionManager
*/
function _deployMultiPositionManager(
PoolKey memory poolKey,
uint256 ethForDeployment,
address managerOwner,
string memory name,
uint256 deposit0Desired,
uint256 deposit1Desired,
address to,
bool useSwap,
RebalanceLogic.SwapParams memory swapParams,
uint256[2][] memory inMin,
IMultiPositionManager.RebalanceParams memory rebalanceParams
) internal returns (address mpm) {
// Step 1: Transfer tokens from user to OrderBookFactory
_transferTokensFromUser(poolKey.currency0, poolKey.currency1, deposit0Desired, deposit1Desired);
// Step 2: Pre-compute future MPM address using factory's computeAddress
address futureMPM = multiPositionFactory.computeAddress(poolKey, managerOwner, name);
// Step 3: Pre-approve the future MPM address (before it exists!)
_approveTokensForMPM(poolKey.currency0, poolKey.currency1, deposit0Desired, deposit1Desired, futureMPM);
// Step 4: Deploy and deposit (with or without rebalance based on strategy)
if (rebalanceParams.strategy == address(0)) {
// No strategy - deploy and deposit with empty rebalance
mpm = multiPositionFactory.deployDepositAndRebalance{value: ethForDeployment}(
poolKey, managerOwner, name, deposit0Desired, deposit1Desired, to, inMin, rebalanceParams
);
} else if (useSwap) {
// With strategy and swap
mpm = multiPositionFactory.deployDepositAndRebalanceSwap{value: ethForDeployment}(
poolKey, managerOwner, name, deposit0Desired, deposit1Desired, to, swapParams, inMin, rebalanceParams
);
} else {
// With strategy, no swap
mpm = multiPositionFactory.deployDepositAndRebalance{value: ethForDeployment}(
poolKey, managerOwner, name, deposit0Desired, deposit1Desired, to, inMin, rebalanceParams
);
}
// Step 5: Sanity check - verify deployed address matches prediction
assert(mpm == futureMPM);
}
function _deployDynamicFeeLimitOrderHook(bytes32 salt) internal returns (address) {
address dynamicFeeHookAddr;
bytes memory bytecode = abi.encodePacked(
dynamicFeeLimitOrderRegistry.getBytecode(),
abi.encode(poolManager, address(limitOrderManager), msg.sender, address(this))
);
// Use CREATE2 to deploy the hook with specific bytecode and salt
// This is required for deterministic hook addresses with correct flags
assembly ("memory-safe") {
dynamicFeeHookAddr := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
if iszero(extcodesize(dynamicFeeHookAddr)) {
revert(0, 0)
}
}
return dynamicFeeHookAddr;
}
function _deployVolatilityDynamicFeeLimitOrderHook(bytes32 salt, address creator) internal returns (address) {
if (sharedVolatilityOracle == address(0)) revert SharedVolatilityOracleNotSet();
address volatilityHookAddr;
bytes memory bytecode = abi.encodePacked(
volatilityDynamicLimitOrderRegistry.getBytecode(),
abi.encode(
poolManager,
address(limitOrderManager),
sharedVolatilityOracle,
creator,
address(this)
)
);
// Use CREATE2 to deploy the hook with specific bytecode and salt
// This is required for deterministic hook addresses with correct flags
assembly ("memory-safe") {
volatilityHookAddr := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
if iszero(extcodesize(volatilityHookAddr)) {
revert(0, 0)
}
}
return volatilityHookAddr;
}
/// @notice Deploy a fee-only DynamicFeeHook (no limit orders)
function _deployDynamicFeeHook(bytes32 salt) internal returns (address) {
address dynamicFeeHookAddr;
bytes memory bytecode = abi.encodePacked(
dynamicFeeRegistry.getBytecode(),
abi.encode(poolManager, msg.sender, address(this))
);
// Use CREATE2 to deploy the hook with specific bytecode and salt
// This is required for deterministic hook addresses with correct flags
assembly ("memory-safe") {
dynamicFeeHookAddr := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
if iszero(extcodesize(dynamicFeeHookAddr)) {
revert(0, 0)
}
}
return dynamicFeeHookAddr;
}
/// @notice Deploy a fee-only VolatilityDynamicFeeHook (no limit orders)
function _deployVolatilityDynamicFeeHook(bytes32 salt, address creator) internal returns (address) {
if (sharedVolatilityOracle == address(0)) revert SharedVolatilityOracleNotSet();
address volatilityHookAddr;
bytes memory bytecode = abi.encodePacked(
volatilityDynamicFeeRegistry.getBytecode(),
abi.encode(
poolManager,
sharedVolatilityOracle,
creator,
address(this)
)
);
// Use CREATE2 to deploy the hook with specific bytecode and salt
// This is required for deterministic hook addresses with correct flags
assembly ("memory-safe") {
volatilityHookAddr := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
if iszero(extcodesize(volatilityHookAddr)) {
revert(0, 0)
}
}
return volatilityHookAddr;
}
function setRegularPoolCreationFee(uint256 _fee) external onlyRole(DEFAULT_ADMIN_ROLE) {
regularPoolCreationFee = _fee;
emit RegularPoolCreationFeeUpdated(_fee);
}
function setDynamicPoolCreationFee(uint256 _fee) external onlyRole(DEFAULT_ADMIN_ROLE) {
dynamicPoolCreationFee = _fee;
emit DynamicPoolCreationFeeUpdated(_fee);
}
function setVolatilityDynamicCreationFee(uint256 _fee) external onlyRole(DEFAULT_ADMIN_ROLE) {
volatilityDynamicCreationFee = _fee;
emit VolatilityDynamicCreationFeeUpdated(_fee);
}
function setDynamicFeeLimitOrderRegistry(address _registry) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (_registry == address(0)) revert ZeroAddress();
address oldRegistry = address(dynamicFeeLimitOrderRegistry);
dynamicFeeLimitOrderRegistry = DynamicFeeLimitOrderHookRegistry(_registry);
emit DynamicFeeRegistryUpdated(oldRegistry, _registry);
}
function setVolatilityDynamicLimitOrderRegistry(address _registry) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (_registry == address(0)) revert ZeroAddress();
address oldRegistry = address(volatilityDynamicLimitOrderRegistry);
volatilityDynamicLimitOrderRegistry = VolatilityDynamicFeeLimitOrderHookRegistry(_registry);
emit VolatilityDynamicRegistryUpdated(oldRegistry, _registry);
}
function setDynamicFeeRegistry(address _registry) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (_registry == address(0)) revert ZeroAddress();
address oldRegistry = address(dynamicFeeRegistry);
dynamicFeeRegistry = DynamicFeeHookRegistry(_registry);
emit DynamicFeeRegistryUpdated(oldRegistry, _registry);
}
function setVolatilityDynamicFeeRegistry(address _registry) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (_registry == address(0)) revert ZeroAddress();
address oldRegistry = address(volatilityDynamicFeeRegistry);
volatilityDynamicFeeRegistry = VolatilityDynamicFeeHookRegistry(_registry);
emit VolatilityDynamicRegistryUpdated(oldRegistry, _registry);
}
function withdrawFees(address recipient) external onlyRole(FEE_COLLECTOR_ROLE) {
if (recipient == address(0)) revert ZeroAddress();
uint256 amount = collectedFees;
if (amount == 0) revert NoFeesToWithdraw();
collectedFees = 0;
emit FeesWithdrawn(recipient, amount);
(bool success, ) = recipient.call{value: amount}("");
if (!success) revert ETHTransferFailed();
}
function computeSaltForDynamicLimitOrder(
address creator,
address _limitOrderManager,
address factory
) public view returns (bytes32 salt, address hookAddress) {
uint160 flags = uint160(
Hooks.BEFORE_SWAP_FLAG |
Hooks.AFTER_SWAP_FLAG
);
bytes memory creationCode = dynamicFeeLimitOrderRegistry.getBytecode();
bytes memory constructorArgs = abi.encode(
poolManager,
_limitOrderManager,
creator,
factory
);
(hookAddress, salt) = HookMiner.find(
factory, flags, creationCode, constructorArgs
);
}
function computeSaltForVolatilityDynamicLimitOrder(
address creator,
address _limitOrderManager,
address factory
) public view returns (bytes32 salt, address hookAddress) {
if (sharedVolatilityOracle == address(0)) revert SharedVolatilityOracleNotSet();
uint160 flags = uint160(
Hooks.BEFORE_SWAP_FLAG |
Hooks.AFTER_SWAP_FLAG |
Hooks.BEFORE_INITIALIZE_FLAG
);
bytes memory creationCode = volatilityDynamicLimitOrderRegistry.getBytecode();
bytes memory constructorArgs = abi.encode(
poolManager,
_limitOrderManager,
sharedVolatilityOracle,
creator,
factory
);
(hookAddress, salt) = HookMiner.find(
factory, flags, creationCode, constructorArgs
);
}
// ============ FEE-ONLY SALT COMPUTATION FUNCTIONS ============
function computeSaltForDynamicFee(
address creator,
address factory
) public view returns (bytes32 salt, address hookAddress) {
// DynamicFeeHook only needs BEFORE_SWAP (no AFTER_SWAP since no limit orders)
uint160 flags = uint160(Hooks.BEFORE_SWAP_FLAG);
bytes memory creationCode = dynamicFeeRegistry.getBytecode();
bytes memory constructorArgs = abi.encode(
poolManager,
creator,
factory
);
(hookAddress, salt) = HookMiner.find(
factory, flags, creationCode, constructorArgs
);
}
function computeSaltForVolatilityDynamicFee(
address creator,
address factory
) public view returns (bytes32 salt, address hookAddress) {
if (sharedVolatilityOracle == address(0)) revert SharedVolatilityOracleNotSet();
// VolatilityDynamicFeeHook needs BEFORE_SWAP + AFTER_SWAP (for CAP detection)
// but NO BEFORE_INITIALIZE (no pool reservation for fee-only hooks)
uint160 flags = uint160(
Hooks.BEFORE_SWAP_FLAG |
Hooks.AFTER_SWAP_FLAG
);
bytes memory creationCode = volatilityDynamicFeeRegistry.getBytecode();
bytes memory constructorArgs = abi.encode(
poolManager,
sharedVolatilityOracle,
creator,
factory
);
(hookAddress, salt) = HookMiner.find(
factory, flags, creationCode, constructorArgs
);
}
// ============ END FEE-ONLY SALT COMPUTATION FUNCTIONS ============
// ============ HOOK ADDRESS COMPUTATION FUNCTIONS ============
/// @notice Compute the CREATE2 address for a volatility limit order hook without deploying
/// @dev Pure CREATE2 math - cheap view function. Use for poolId computation before pool creation.
/// @param hookOwner The owner of the hook
/// @param salt The pre-computed salt from HookMiner
/// @return hookAddr The predicted hook address
function computeVolatilityLimitOrderHookAddress(
address hookOwner,
bytes32 salt
) public view returns (address hookAddr) {
if (sharedVolatilityOracle == address(0)) revert SharedVolatilityOracleNotSet();
bytes memory bytecode = abi.encodePacked(
volatilityDynamicLimitOrderRegistry.getBytecode(),
abi.encode(poolManager, address(limitOrderManager), sharedVolatilityOracle, hookOwner, address(this))
);
// CREATE2 address computation: keccak256(0xff ++ deployer ++ salt ++ keccak256(bytecode))
hookAddr = address(uint160(uint256(keccak256(abi.encodePacked(
bytes1(0xff),
address(this),
salt,
keccak256(bytecode)
)))));
}
/// @notice Compute the CREATE2 address for a volatility fee-only hook without deploying
/// @dev Pure CREATE2 math - cheap view function.
/// @param hookOwner The owner of the hook
/// @param salt The pre-computed salt from HookMiner
/// @return hookAddr The predicted hook address
function computeVolatilityFeeHookAddress(
address hookOwner,
bytes32 salt
) public view returns (address hookAddr) {
if (sharedVolatilityOracle == address(0)) revert SharedVolatilityOracleNotSet();
bytes memory bytecode = abi.encodePacked(
volatilityDynamicFeeRegistry.getBytecode(),
abi.encode(poolManager, sharedVolatilityOracle, hookOwner, address(this))
);
hookAddr = address(uint160(uint256(keccak256(abi.encodePacked(
bytes1(0xff),
address(this),
salt,
keccak256(bytecode)
)))));
}
// ============ END HOOK ADDRESS COMPUTATION FUNCTIONS ============
/// @notice Get all pool IDs created by a specific creator
/// @param creator The address of the creator
/// @return poolIds Array of pool IDs created by this address
function getPoolsByCreator(address creator) external view returns (bytes32[] memory poolIds) {
PoolInfo[] memory pools = userToPoolInfo[creator];
poolIds = new bytes32[](pools.length);
for (uint256 i = 0; i < pools.length; i++) {
poolIds[i] = pools[i].poolId;
}
}
/// @notice Get all pool information for a specific creator
/// @param creator The address of the creator
/// @return Array of PoolInfo structs containing pool details
function getPoolInfoByCreator(address creator) external view returns (PoolInfo[] memory) {
return userToPoolInfo[creator];
}
/// @notice Set the shared volatility oracle for all per-creator hooks
/// @dev Only admin can set this. Should be called once during deployment.
/// @param oracle The address of the shared VolatilityOracle
function setSharedVolatilityOracle(address oracle) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (oracle == address(0)) revert ZeroAddress();
sharedVolatilityOracle = oracle;
emit SharedVolatilityOracleSet(oracle);
}
/// @notice Set the authorized strategy factory for pool reservations
/// @dev Only admin can set this
/// @param factory The address of the authorized strategy factory
function setAuthorizedStrategyFactory(address factory) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (factory == address(0)) revert ZeroAddress();
authorizedStrategyFactory = factory;
emit AuthorizedStrategyFactorySet(factory);
}
/// @notice Reserve a pool ID for a specific strategy contract
/// @dev Only the authorized strategy factory can call this
/// @param poolId The pool ID to reserve
/// @param strategy The strategy contract that will be authorized to create this pool
function reservePoolForStrategy(bytes32 poolId, address strategy) external {
if (msg.sender != authorizedStrategyFactory) revert NotAuthorizedStrategyFactory();
if (reservedPools[poolId] != address(0)) revert PoolAlreadyReserved();
reservedPools[poolId] = strategy;
emit PoolReserved(poolId, strategy);
}
/// @notice Compute the pool ID for a volatility dynamic limit order pool
/// @dev Used by strategy factories to compute the pool ID for reservation.
/// Uses cheap CREATE2 address computation instead of expensive HookMiner.find().
/// @param hookOwner The owner of the hook (determines hook address)
/// @param salt The pre-computed salt for the hook (from computeSaltForVolatilityDynamicLimitOrder)
/// @param currency0 The first currency
/// @param currency1 The second currency
/// @param tickSpacing The tick spacing
/// @return poolId The computed pool ID
function computePoolIdForVolatilityLimitOrder(
address hookOwner,
bytes32 salt,
Currency currency0,
Currency currency1,
int24 tickSpacing
) public view returns (bytes32 poolId) {
// Get existing hook address or compute from salt (cheap CREATE2 math)
address hookAddr = creatorVolatilityDynamicLimitOrderHooks[hookOwner];
if (hookAddr == address(0)) {
// Hook doesn't exist yet, compute address from salt (no deployment, no HookMiner)
hookAddr = computeVolatilityLimitOrderHookAddress(hookOwner, salt);
}
// Compute the pool key and then the pool ID
PoolKey memory key = PoolKey({
currency0: currency0,
currency1: currency1,
fee: LPFeeLibrary.DYNAMIC_FEE_FLAG,
tickSpacing: tickSpacing,
hooks: IHooks(hookAddr)
});
poolId = PoolId.unwrap(key.toId());
}
/// @notice Internal helper to deploy or get per-creator volatility limit order hook
/// @dev Per-creator hooks provide natural front-running protection via unique addresses
/// @dev Salt must be computed off-chain using computeSaltForVolatilityDynamicLimitOrder()
/// @param params The pool creation parameters (includes pre-computed salt)
/// @return hookAddr The address of the hook to use
/// @return wasReserved True if the pool was reserved (fee should be skipped)
function _getOrCheckVolatilityLimitOrderHook(VolatilityDynamicPoolParams calldata params)
internal
returns (address hookAddr, bool wasReserved)
{
// Determine hook owner: use hookOwner if specified, otherwise msg.sender
address owner = params.hookOwner != address(0) ? params.hookOwner : msg.sender;
// Get or deploy hook FIRST (before computing poolId)
// This ensures poolId computation uses the actual deployed hook address
hookAddr = creatorVolatilityDynamicLimitOrderHooks[owner];
if (hookAddr == address(0)) {
// Deploy with pre-computed salt from params (NOT on-chain computation)
hookAddr = _deployVolatilityDynamicFeeLimitOrderHook(params.salt, owner);
// Verify deployed address has correct hook flags
uint160 hookFlags = uint160(hookAddr) & Hooks.ALL_HOOK_MASK;
uint160 requiredFlags = Hooks.BEFORE_SWAP_FLAG | Hooks.AFTER_SWAP_FLAG | Hooks.BEFORE_INITIALIZE_FLAG;
if ((hookFlags & requiredFlags) != requiredFlags) {
revert InvalidHookAddress();
}
creatorVolatilityDynamicLimitOrderHooks[owner] = hookAddr;
// Register newly deployed hook with the shared oracle
VolatilityOracle(sharedVolatilityOracle).addAuthorizedHook(hookAddr);
emit VolatilityHookDeployed(owner, hookAddr);
}
// Now compute poolId using the actual hook address and check reservation
bytes32 poolId = computePoolIdForVolatilityLimitOrder(owner, params.salt, params.currency0, params.currency1, params.tickSpacing);
address reserved = reservedPools[poolId];
if (reserved != address(0) && reserved != msg.sender) {
revert PoolReservedForOther();
}
// Clear reservation after use and mark as reserved for fee exemption
if (reserved != address(0)) {
delete reservedPools[poolId];
emit PoolReservationCleared(poolId);
wasReserved = true;
}
}
receive() external payable {}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @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 value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
/// @notice Thrown when a currency is not netted out after the contract is unlocked
error CurrencyNotSettled();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when unlock is called, but the contract is already unlocked
error AlreadyUnlocked();
/// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
error ManagerLocked();
/// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
error TickSpacingTooLarge(int24 tickSpacing);
/// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
error TickSpacingTooSmall(int24 tickSpacing);
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);
/// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
/// or on a pool that does not have a dynamic swap fee.
error UnauthorizedDynamicLPFeeUpdate();
/// @notice Thrown when trying to swap amount of 0
error SwapAmountCannotBeZero();
///@notice Thrown when native currency is passed to a non native settlement
error NonzeroNativeValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @notice Emitted when a new pool is initialized
/// @param id The abi encoded hash of the pool key struct for the new pool
/// @param currency0 The first currency of the pool by address sort order
/// @param currency1 The second currency of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param hooks The hooks contract address for the pool, or address(0) if none
/// @param sqrtPriceX96 The price of the pool on initialization
/// @param tick The initial tick of the pool corresponding to the initialized price
event Initialize(
PoolId indexed id,
Currency indexed currency0,
Currency indexed currency1,
uint24 fee,
int24 tickSpacing,
IHooks hooks,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted when a liquidity position is modified
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param liquidityDelta The amount of liquidity that was added or removed
/// @param salt The extra data to make positions unique
event ModifyLiquidity(
PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
);
/// @notice Emitted for swaps between currency0 and currency1
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that initiated the swap call, and that received the callback
/// @param amount0 The delta of the currency0 balance of the pool
/// @param amount1 The delta of the currency1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of the price of the pool after the swap
/// @param fee The swap fee in hundredths of a bip
event Swap(
PoolId indexed id,
address indexed sender,
int128 amount0,
int128 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick,
uint24 fee
);
/// @notice Emitted for donations
/// @param id The abi encoded hash of the pool key struct for the pool that was donated to
/// @param sender The address that initiated the donate call
/// @param amount0 The amount donated in currency0
/// @param amount1 The amount donated in currency1
event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);
/// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
/// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
/// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
/// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
/// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
function unlock(bytes calldata data) external returns (bytes memory);
/// @notice Initialize the state for a given pool ID
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The pool key for the pool to initialize
/// @param sqrtPriceX96 The initial square root price
/// @return tick The initial tick of the pool
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
/// @notice Modify the liquidity for the given pool
/// @dev Poke by calling with a zero liquidityDelta
/// @param key The pool to modify liquidity in
/// @param params The parameters for modifying the liquidity
/// @param hookData The data to pass through to the add/removeLiquidity hooks
/// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
/// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
/// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
/// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
/// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
external
returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);
/// @notice Swap against the given pool
/// @param key The pool to swap in
/// @param params The parameters for swapping
/// @param hookData The data to pass through to the swap hooks
/// @return swapDelta The balance delta of the address swapping
/// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
/// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
/// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
external
returns (BalanceDelta swapDelta);
/// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
/// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
/// Donors should keep this in mind when designing donation mechanisms.
/// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
/// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
/// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
/// Read the comments in `Pool.swap()` for more information about this.
/// @param key The key of the pool to donate to
/// @param amount0 The amount of currency0 to donate
/// @param amount1 The amount of currency1 to donate
/// @param hookData The data to pass through to the donate hooks
/// @return BalanceDelta The delta of the caller after the donate
function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
external
returns (BalanceDelta);
/// @notice Writes the current ERC20 balance of the specified currency to transient storage
/// This is used to checkpoint balances for the manager and derive deltas for the caller.
/// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
/// for native tokens because the amount to settle is determined by the sent value.
/// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
/// native funds, this function can be called with the native currency to then be able to settle the native currency
function sync(Currency currency) external;
/// @notice Called by the user to net out some value owed to the user
/// @dev Will revert if the requested amount is not available, consider using `mint` instead
/// @dev Can also be used as a mechanism for free flash loans
/// @param currency The currency to withdraw from the pool manager
/// @param to The address to withdraw to
/// @param amount The amount of currency to withdraw
function take(Currency currency, address to, uint256 amount) external;
/// @notice Called by the user to pay what is owed
/// @return paid The amount of currency settled
function settle() external payable returns (uint256 paid);
/// @notice Called by the user to pay on behalf of another address
/// @param recipient The address to credit for the payment
/// @return paid The amount of currency settled
function settleFor(address recipient) external payable returns (uint256 paid);
/// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
/// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
/// @dev This could be used to clear a balance that is considered dust.
/// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
function clear(Currency currency, uint256 amount) external;
/// @notice Called by the user to move value into ERC6909 balance
/// @param to The address to mint the tokens to
/// @param id The currency address to mint to ERC6909s, as a uint256
/// @param amount The amount of currency to mint
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function mint(address to, uint256 id, uint256 amount) external;
/// @notice Called by the user to move value from ERC6909 balance
/// @param from The address to burn the tokens from
/// @param id The currency address to burn from ERC6909s, as a uint256
/// @param amount The amount of currency to burn
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function burn(address from, uint256 id, uint256 amount) external;
/// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The key of the pool to update dynamic LP fees for
/// @param newDynamicLPFee The new dynamic pool LP fee
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @notice Library of helper functions for a pools LP fee
library LPFeeLibrary {
using LPFeeLibrary for uint24;
using CustomRevert for bytes4;
/// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.
error LPFeeTooLarge(uint24 fee);
/// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE
uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;
/// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
// only dynamic-fee pools can return a fee via the beforeSwap hook
uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;
/// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;
/// @notice the lp fee is represented in hundredths of a bip, so the max is 100%
uint24 public constant MAX_LP_FEE = 1000000;
/// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee
/// @param self The fee to check
/// @return bool True of the fee is dynamic
function isDynamicFee(uint24 self) internal pure returns (bool) {
return self == DYNAMIC_FEE_FLAG;
}
/// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee
/// @param self The fee to check
/// @return bool True of the fee is valid
function isValid(uint24 self) internal pure returns (bool) {
return self <= MAX_LP_FEE;
}
/// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
/// @param self The fee to validate
function validate(uint24 self) internal pure {
if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);
}
/// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.
/// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook
/// @param self The fee to get the initial LP from
/// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid)
function getInitialLPFee(uint24 self) internal pure returns (uint24) {
// the initial fee for a dynamic fee pool is 0
if (self.isDynamicFee()) return 0;
self.validate();
return self;
}
/// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)
/// @param self The fee to check
/// @return bool True of the fee has the override flag set
function isOverride(uint24 self) internal pure returns (bool) {
return self & OVERRIDE_FEE_FLAG != 0;
}
/// @notice returns a fee with the override flag removed
/// @param self The fee to remove the override flag from
/// @return fee The fee without the override flag set
function removeOverrideFlag(uint24 self) internal pure returns (uint24) {
return self & REMOVE_OVERRIDE_MASK;
}
/// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
/// @param self The fee to remove the override flag from, and then validate
/// @return fee The fee without the override flag set (if valid)
function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {
fee = self.removeOverrideFlag();
fee.validate();
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
using CustomRevert for bytes4;
/// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
error InvalidTick(int24 tick);
/// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
error InvalidSqrtPrice(uint160 sqrtPriceX96);
/// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MAX_TICK = 887272;
/// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
int24 internal constant MIN_TICK_SPACING = 1;
/// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
int24 internal constant MAX_TICK_SPACING = type(int16).max;
/// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
/// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
1461446703485210103287273052203988822378723970342 - 4295128739 - 1;
/// @notice Given a tickSpacing, compute the maximum usable tick
function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MAX_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Given a tickSpacing, compute the minimum usable tick
function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MIN_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
/// at the given tick
function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick;
assembly ("memory-safe") {
tick := signextend(2, tick)
// mask = 0 if tick >= 0 else -1 (all 1s)
let mask := sar(255, tick)
// if tick >= 0, |tick| = tick = 0 ^ tick
// if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
// either way, |tick| = mask ^ (tick + mask)
absTick := xor(mask, add(mask, tick))
}
if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);
// The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
// is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer
// Equivalent to:
// price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
// or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
uint256 price;
assembly ("memory-safe") {
price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
}
if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;
assembly ("memory-safe") {
// if (tick > 0) price = type(uint256).max / price;
if sgt(tick, 0) { price := div(not(0), price) }
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtPrice of the output price is always consistent
// `sub(shl(32, 1), 1)` is `type(uint32).max`
// `price + type(uint32).max` will not overflow because `price` fits in 192 bits
sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
}
}
}
/// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
// second inequality must be >= because the price can never reach the price at the max tick
// if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
// if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
}
uint256 price = uint256(sqrtPriceX96) << 32;
uint256 r = price;
uint256 msb = BitMath.mostSignificantBit(r);
if (msb >= 128) r = price >> (msb - 127);
else r = price << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number
// Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
// Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
// sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
// is changed, this may need to be changed too
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isAddressZero()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
}
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
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(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isAddressZero()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {ILimitOrderManager} from "./interfaces/ILimitOrderManager.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "v4-core/types/BalanceDelta.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency, CurrencyLibrary} from "v4-core/types/Currency.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
// import {TickMath} from "v4-core/libraries/TickMath.sol";
import {SafeCast} from "v4-core/libraries/SafeCast.sol";
// import {LiquidityAmounts} from "v4-periphery/lib/v4-core/test/utils/LiquidityAmounts.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IUnlockCallback} from "v4-core/interfaces/callback/IUnlockCallback.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
// import {FullMath} from "v4-core/libraries/FullMath.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import "./libraries/PositionManagement.sol";
import "./libraries/TickLibrary.sol";
import "./libraries/CallbackHandler.sol";
import "forge-std/console.sol";
import {TickBitmap} from "v4-core/libraries/TickBitmap.sol";
// import {BitMath} from "v4-core/libraries/BitMath.sol";
/// @title LimitOrderManager
/// @notice Manages limit orders for Uniswap v4 pools
/// @dev Handles creation, execution, and cancellation of limit orders with fee collection and position tracking
contract LimitOrderManager is ILimitOrderManager, IUnlockCallback, AccessControl, ReentrancyGuard, Pausable {
using CurrencySettler for Currency;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.Bytes32Set;
using BalanceDeltaLibrary for BalanceDelta;
using PoolIdLibrary for PoolKey;
using SafeCast for *;
using TickLibrary for int24;
using CallbackHandler for CallbackHandler.CallbackState;
using SafeERC20 for IERC20;
// Pool manager reference
IPoolManager public immutable poolManager;
address public orderBookFactoryAddr;
// // Hook address
// address public hook;
// Mapping of hook address
mapping(address => bool) public isHook;
// Constants
uint256 public constant FEE_DENOMINATOR = 100000;
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
// Role definitions
bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
CallbackHandler.CallbackState private callbackState;
address public override treasury;
// uint256 public override executablePositionsLimit = 75;
uint256 public hook_fee_percentage = 50000;
uint24 public maxOrderLimit = 100;
// Removed minAmount functionality
// mapping(address => bool) public override isKeeper;
// Original state mappings
mapping(PoolId => bool) public whitelistedPool;
mapping(PoolId => mapping(bytes32 => EnumerableSet.AddressSet)) private positionContributors;
mapping(PoolId => mapping(bytes32 => mapping(address => UserPosition))) public userPositions;
mapping(PoolId => mapping(bytes32 => uint256)) public override currentNonce;
mapping(PoolId => mapping(int16 => uint256)) public token0TickBitmap;
mapping(PoolId => mapping(int16 => uint256)) public token1TickBitmap;
mapping(PoolId => mapping(int24 => bytes32)) public token0PositionAtTick;
mapping(PoolId => mapping(int24 => bytes32)) public token1PositionAtTick;
mapping(PoolId => mapping(bytes32 => PositionState)) public positionState;
mapping(address => mapping(PoolId => EnumerableSet.Bytes32Set)) private userPositionKeys;
constructor(address _poolManagerAddr, address _treasury, address _owner, address _factory) {
require(_treasury != address(0) && _poolManagerAddr != address(0) && _owner != address(0));
treasury = _treasury;
poolManager = IPoolManager(_poolManagerAddr);
// Initialize callback state
callbackState.poolManager = poolManager;
callbackState.treasury = _treasury;
callbackState.feeDenominator = FEE_DENOMINATOR;
callbackState.hookFeePercentage = hook_fee_percentage;
// Set factory address
orderBookFactoryAddr = _factory;
// Grant roles to the owner
_grantRole(DEFAULT_ADMIN_ROLE, _owner);
_grantRole(MANAGER_ROLE, _owner);
}
// =========== Create Order Functions ===========
/// @notice Creates a single limit order in a specified pool
/// @param isToken0 True if order is for token0, false for token1
/// @param targetTick The target tick price for the order
/// @param amount The amount of tokens to use for the order
/// @param key The pool key identifying the specific pool
/// @return result Order creation result
/// @dev Validates parameters and transfers tokens from user before creating order
function createLimitOrder(
bool isToken0,
int24 targetTick,
uint256 amount,
PoolKey calldata key
) external payable override returns (CreateOrderResult memory) {
PoolId poolId = key.toId();
(, int24 currentTick, , ) = StateLibrary.getSlot0(poolManager, poolId);
(int24 bottomTick, int24 topTick) = TickLibrary.getValidTickRange(
currentTick,
targetTick,
key.tickSpacing,
isToken0
);
ILimitOrderManager.OrderInfo[] memory orders = new ILimitOrderManager.OrderInfo[](1);
orders[0] = ILimitOrderManager.OrderInfo({
bottomTick: bottomTick,
topTick: topTick,
amount: 0,
liquidity: 0
});
CreateOrderResult[] memory results = _createOrder(orders, isToken0, amount, 1, 0, key);
return results[0];
}
/// @notice Creates multiple scaled limit orders across a price range
/// @param isToken0 True if orders are for token0, false for token1
/// @param bottomTick The lower tick bound of the order range
/// @param topTick The upper tick bound of the order range
/// @param totalAmount Total amount of tokens to distribute across orders
/// @param totalOrders Number of orders to create
/// @param sizeSkew Skew factor for order size distribution (1 for equal distribution)
/// @param key The pool key identifying the specific pool
/// @return results containing details of all created orders
/// @dev Orders are distributed according to the sizeSkew parameter
function createScaleOrders(
bool isToken0,
int24 bottomTick,
int24 topTick,
uint256 totalAmount,
uint256 totalOrders,
uint256 sizeSkew,
PoolKey calldata key
) external payable returns (CreateOrderResult[] memory results) {
// Get current tick for validation
PoolId poolId = key.toId();
(, int24 currentTick, , ) = StateLibrary.getSlot0(poolManager, poolId);
require(totalOrders <= maxOrderLimit);
ILimitOrderManager.OrderInfo[] memory orders =
TickLibrary.validateAndPrepareScaleOrders(bottomTick, topTick, currentTick, isToken0, totalOrders, sizeSkew, key.tickSpacing);
results = _createOrder(orders, isToken0, totalAmount, totalOrders, sizeSkew, key);
}
/**
* @notice Internal function to create one or more limit orders with specified parameters
* @dev Handles the core logic of order creation
* @param orders Array of OrderInfo structs containing initial order parameters
* @param isToken0 True if orders are for token0, false for token1
* @param totalAmount Total amount of tokens to be used across all orders
* @param totalOrders Number of orders to create (used for scale calculations)
* @param sizeSkew Distribution factor for order sizes (0 for equal distribution)
* @param key Pool key identifying the specific Uniswap V4 pool
* @return results Array of CreateOrderResult structs containing created order details
*/
function _createOrder(
ILimitOrderManager.OrderInfo[] memory orders,
bool isToken0,
uint256 totalAmount,
uint256 totalOrders,
uint256 sizeSkew,
PoolKey calldata key
) internal whenNotPaused returns (CreateOrderResult[] memory results) {
// require(address(key.hooks) == hook);
require(isHook[address(key.hooks)], "DisabledHook");
require(totalAmount != 0);
PoolId poolId = key.toId();
if (!whitelistedPool[poolId]) revert NotWhitelistedPool();
orders = PositionManagement.calculateOrderSizes(orders, isToken0, totalAmount, totalOrders, sizeSkew);
// Removed minAmount validation
_handleTokenTransfer(isToken0, totalAmount, key);
results = new CreateOrderResult[](orders.length);
BalanceDelta[] memory feeDeltas = abi.decode(
poolManager.unlock(abi.encode(
UnlockCallbackData({
callbackType: CallbackType.CREATE_ORDERS,
data: abi.encode(CreateOrdersCallbackData({key: key, orders: orders, isToken0: isToken0, orderCreator: msg.sender}))
})
)),
(BalanceDelta[])
);
bytes32 positionKey;
OrderInfo memory order;
unchecked {
for (uint256 i; i < orders.length; i++) {
order = orders[i];
(, positionKey) = PositionManagement.getPositionKeys(currentNonce, poolId, order.bottomTick, order.topTick, isToken0);
// require(!positionState[poolId][positionKey].isWaitingKeeper);
_retrackPositionFee(poolId, positionKey, feeDeltas[i]);
if(!positionState[poolId][positionKey].isActive) {
positionState[poolId][positionKey].isActive = true;
bytes32 baseKey = bytes32(
uint256(uint24(order.bottomTick)) << 232 |
uint256(uint24(order.topTick)) << 208 |
uint256(isToken0 ? 1 : 0)
);
positionState[poolId][positionKey].currentNonce = currentNonce[poolId][baseKey];
int24 executableTick = isToken0 ? order.topTick : order.bottomTick;
PositionManagement.addPositionToTick(
isToken0 ? token0PositionAtTick : token1PositionAtTick,
isToken0 ? token0TickBitmap : token1TickBitmap,
key,
executableTick,
positionKey
);
}
_updateUserPosition(poolId, positionKey, order.liquidity, msg.sender);
results[i].usedAmount = order.amount;
results[i].isToken0 = isToken0;
results[i].bottomTick = order.bottomTick;
results[i].topTick = order.topTick;
emit OrderCreated(msg.sender, poolId, positionKey);
}
}
return results;
}
// =========== Cancel Order Functions ===========
/// @notice Cancels a single limit order position
/// @param key The pool key identifying the specific Uniswap V4 pool
/// @param positionKey The unique identifier of the position to cancel
function cancelOrder(PoolKey calldata key, bytes32 positionKey) external override nonReentrant{
_cancelOrder(key, positionKey, msg.sender);
}
/// @notice Cancels multiple limit order positions in a batch
/// @dev Uses pagination to handle large numbers of orders
/// @param key The pool key identifying the specific Uniswap V4 pool
/// @param offset Starting position in the user's position array
/// @param limit Maximum number of positions to process in this call
function cancelBatchOrders(
PoolKey calldata key,
uint256 offset,
uint256 limit
) external override nonReentrant {
PoolId poolId = key.toId();
EnumerableSet.Bytes32Set storage userKeys = userPositionKeys[msg.sender][poolId];
if (offset >= userKeys.length()) {
return;
}
uint256 endIndex = (offset + limit > userKeys.length()) ?
userKeys.length() :
offset + limit;
uint256 i = endIndex;
unchecked {
while (i > offset) {
i--;
if (i < userKeys.length()) {
bytes32 positionKey = userKeys.at(i);
_cancelOrder(key, positionKey, msg.sender);
}
}
}
}
/// @notice Cancels multiple limit order positions using direct position keys
/// @param key The pool key identifying the specific Uniswap V4 pool
/// @param positionKeys Array of position keys to cancel
function cancelPositionKeys(
PoolKey calldata key,
bytes32[] calldata positionKeys
) external nonReentrant {
unchecked {
for (uint256 i = 0; i < positionKeys.length; i++) {
_cancelOrder(key, positionKeys[i], msg.sender);
}
}
}
/// @notice Emergency function to cancel orders on behalf of a user
/// @dev Can only be called by accounts with MANAGER_ROLE in emergency situations
/// @param key The pool key identifying the specific Uniswap V4 pool
/// @param user The address of the user whose orders will be canceled
/// @param positionKeys Array of position keys to cancel
function emergencyCancelOrders(
PoolKey calldata key,
bytes32[] calldata positionKeys,
address user
) external nonReentrant onlyRole(MANAGER_ROLE) {
unchecked {
for (uint256 i = 0; i < positionKeys.length; i++) {
_cancelOrder(key, positionKeys[i], user);
}
}
}
/// @notice Emergency function to cancel batch orders on behalf of a user
/// @dev Can only be called by accounts with MANAGER_ROLE in emergency situations, uses pagination
/// @param key The pool key identifying the specific Uniswap V4 pool
/// @param user The address of the user whose orders will be canceled
/// @param offset Starting position in the user's position array
/// @param limit Maximum number of positions to process in this call
function emergencyCancelBatchOrders(
PoolKey calldata key,
address user,
uint256 offset,
uint256 limit
) external nonReentrant onlyRole(MANAGER_ROLE) {
PoolId poolId = key.toId();
EnumerableSet.Bytes32Set storage userKeys = userPositionKeys[user][poolId];
if (offset >= userKeys.length()) {
return;
}
uint256 endIndex = (offset + limit > userKeys.length()) ?
userKeys.length() :
offset + limit;
uint256 i = endIndex;
unchecked {
while (i > offset) {
i--;
if (i < userKeys.length()) {
bytes32 positionKey = userKeys.at(i);
_cancelOrder(key, positionKey, user);
}
}
}
}
/// @notice Internal function to handle the cancellation of a limit order
/// @dev Handles both cancellation and claiming in a single transaction
/// @param key The pool key identifying the specific Uniswap V4 pool
/// @param positionKey The unique identifier of the position to cancel
/// @param user The address of the position owner
function _cancelOrder(
PoolKey calldata key,
bytes32 positionKey,
address user
) internal {
PoolId poolId = key.toId();
// Check if user has liquidity in this position
uint128 userLiquidity = userPositions[poolId][positionKey][user].liquidity;
require(userLiquidity > 0, "ZeroLiquidity");
// Early return for claimable balance
if(userPositions[poolId][positionKey][user].claimablePrincipal != ZERO_DELTA || !positionState[poolId][positionKey].isActive) {
_claimOrder(key, positionKey, user);
return;
}
// Get position info
(int24 bottomTick, int24 topTick, bool isToken0, ) = _decodePositionKey(positionKey);
// Cancel order through pool manager
(BalanceDelta callerDelta, BalanceDelta feeDelta) = abi.decode(
poolManager.unlock(
abi.encode(
UnlockCallbackData({
callbackType: CallbackType.CANCEL_ORDER,
data: abi.encode(
CancelOrderCallbackData({
key: key,
bottomTick: bottomTick,
topTick: topTick,
liquidity: userLiquidity,
user: user,
isToken0: isToken0
})
)
})
)
),
(BalanceDelta, BalanceDelta)
);
_retrackPositionFee(poolId, positionKey, feeDelta);
userPositions[poolId][positionKey][user].claimablePrincipal = callerDelta - feeDelta;
positionState[poolId][positionKey].totalLiquidity -= userLiquidity;
int24 executableTick = isToken0 ? topTick : bottomTick;
_handlePositionRemoval(poolId, positionKey, user, key, isToken0, executableTick);
emit OrderCanceled(user, poolId, positionKey);
}
/// @notice Updated helper function
function _handlePositionRemoval(
PoolId poolId,
bytes32 positionKey,
address user,
PoolKey calldata key,
bool isToken0,
int24 executableTick
) internal {
_claimOrder(key, positionKey, user);
positionContributors[poolId][positionKey].remove(user);
if(positionContributors[poolId][positionKey].length() == 0) {
positionState[poolId][positionKey].isActive = false;
// positionState[poolId][positionKey].isWaitingKeeper = false;
PositionManagement.removePositionFromTick(
isToken0 ? token0PositionAtTick : token1PositionAtTick,
isToken0 ? token0TickBitmap : token1TickBitmap,
key,
executableTick
);
}
}
// Decode position key to get all components including nonce
function _decodePositionKey(bytes32 key) internal pure returns (
int24 bottomTick,
int24 topTick,
bool isToken0,
uint256 nonce
) {
uint256 value = uint256(key);
return (
int24(uint24(value >> 232)),
int24(uint24(value >> 208)),
(value & 1) == 1,
(value >> 8) & ((1 << 200) - 1)
);
}
/// @notice Allows claiming tokens from a canceled or executed limit order
/// @param key The pool key identifying the specific Uniswap V4 pool
/// @param positionKey The unique identifier of the position to claim
function claimOrder(PoolKey calldata key, bytes32 positionKey) nonReentrant external {
_claimOrder(key, positionKey, msg.sender);
}
/// @notice Batch claims multiple orders that were executed or canceled
/// @dev Uses pagination to handle large numbers of orders
/// @param key The pool key identifying the specific Uniswap V4 pool
/// @param offset Starting position in the user's position array
/// @param limit Maximum number of positions to process in this call
function claimBatchOrders(
PoolKey calldata key,
uint256 offset,
uint256 limit
) external nonReentrant {
PoolId poolId = key.toId();
EnumerableSet.Bytes32Set storage userKeys = userPositionKeys[msg.sender][poolId];
if (offset >= userKeys.length()) {
return;
}
uint256 endIndex = (offset + limit > userKeys.length()) ?
userKeys.length() :
offset + limit;
uint256 i = endIndex;
unchecked {
while (i > offset) {
i--;
if (i < userKeys.length()) {
bytes32 positionKey = userKeys.at(i);
UserPosition storage position = userPositions[poolId][positionKey][msg.sender];
if (position.liquidity > 0 &&
(position.claimablePrincipal != ZERO_DELTA || !positionState[poolId][positionKey].isActive)) {
_claimOrder(key, positionKey, msg.sender);
}
}
}
}
}
/// @notice Claims multiple limit order positions using direct position keys
/// @param key The pool key identifying the specific Uniswap V4 pool
/// @param positionKeys Array of position keys to claim
function claimPositionKeys(
PoolKey calldata key,
bytes32[] calldata positionKeys
) external nonReentrant {
unchecked {
for (uint256 i = 0; i < positionKeys.length; i++) {
_claimOrder(key, positionKeys[i], msg.sender);
}
}
}
/// @notice Internal function to process claiming of tokens from a position
/// @param key The pool key identifying the specific Uniswap V4 pool
/// @param positionKey The unique identifier of the position to claim
/// @param user The address that will receive the claimed tokens
function _claimOrder(PoolKey calldata key, bytes32 positionKey, address user) internal {
PoolId poolId = key.toId();
require(userPositions[poolId][positionKey][user].liquidity > 0, "ZeroLiquidity");
require(userPositions[poolId][positionKey][user].claimablePrincipal != ZERO_DELTA ||!positionState[poolId][positionKey].isActive, "NotClaimable");
UserPosition memory position = userPositions[poolId][positionKey][user];
// Calculate claimable principal in memory
BalanceDelta principal;
if (!positionState[poolId][positionKey].isActive) {
principal = PositionManagement.getBalanceDelta(positionKey, position.liquidity);
} else {
principal = position.claimablePrincipal;
}
// Calculate fees in memory
BalanceDelta fees = position.fees;
if (position.liquidity != 0) {
BalanceDelta feeDiff = positionState[poolId][positionKey].feePerLiquidity - position.lastFeePerLiquidity;
BalanceDelta pendingFees = PositionManagement.calculateScaledUserFee(feeDiff, position.liquidity);
fees = fees + pendingFees;
}
delete userPositions[poolId][positionKey][user];
userPositionKeys[user][poolId].remove(positionKey);
poolManager.unlock(
abi.encode(
UnlockCallbackData({
callbackType: CallbackType.CLAIM_ORDER,
data: abi.encode(
ClaimOrderCallbackData({
principal: principal,
fees: fees,
key: key,
user: user
})
)
})
)
);
emit OrderClaimed(
user,
poolId,
positionKey,
uint256(uint128(principal.amount0())),
uint256(uint128(principal.amount1())),
uint256(uint128(fees.amount0())),
uint256(uint128(fees.amount1())),
hook_fee_percentage
);
}
/**
* @notice Executes limit orders that have been triggered by price movements
* @param key The pool key identifying the specific pool
* @param tickBeforeSwap The tick price before the swap started
* @param tickAfterSwap The tick price after the swap completed
* @param zeroForOne The direction of the swap (true for token0 to token1)
*/
function executeOrder(
PoolKey calldata key,
int24 tickBeforeSwap,
int24 tickAfterSwap,
bool zeroForOne
) external override {
// require(msg.sender == hook);
require(isHook[msg.sender], "DisabledHook");
// require(executablePositionsLimit != 0);
PoolId poolId = key.toId();
int24[] memory executableTicks = _findOverlappingPositions(
poolId,
tickBeforeSwap,
tickAfterSwap,
zeroForOne,
key.tickSpacing
);
if(executableTicks.length == 0) return;
uint256 executableCount = executableTicks.length;
// Cache storage pointer to avoid repeated storage lookups
mapping(int24 => bytes32) storage positionMap = zeroForOne ?
token1PositionAtTick[poolId] :
token0PositionAtTick[poolId];
unchecked {
for(uint256 i = 0; i < executableCount; i++) {
int24 tick = executableTicks[i];
bytes32 posKey = positionMap[tick];
if(posKey == bytes32(0)) continue;
_executePosition(key, poolId, posKey, tick);
}
}
}
/**
* @notice Execute a single limit order position
* @dev Processes a single position identified by its position key
* @param key The pool key
* @param poolId The pool identifier
* @param posKey The position key to execute
* @param tick The tick with the executable position
*/
function _executePosition(
PoolKey memory key,
PoolId poolId,
bytes32 posKey,
int24 tick
) internal returns (BalanceDelta callerDelta, BalanceDelta feeDelta) {
// Decode position data
(int24 bottomTick, int24 topTick, bool isToken0, ) = _decodePositionKey(posKey);
// Cache position state to avoid multiple storage reads
PositionState storage posState = positionState[poolId][posKey];
uint128 totalLiquidity = posState.totalLiquidity;
// Burn position liquidity and collect fees
(callerDelta, feeDelta) = callbackState._burnLimitOrder(
key,
bottomTick,
topTick,
totalLiquidity,
isToken0
);
// Update position state
_retrackPositionFee(poolId, posKey, feeDelta);
posState.isActive = false;
// Remove position from tick tracking
PositionManagement.removePositionFromTick(
isToken0 ? token0PositionAtTick : token1PositionAtTick,
isToken0 ? token0TickBitmap : token1TickBitmap,
key,
tick
);
// Update nonce for this position type to prevent key reuse
bytes32 baseKey = bytes32(
uint256(uint24(bottomTick)) << 232 |
uint256(uint24(topTick)) << 208 |
uint256(isToken0 ? 1 : 0)
);
currentNonce[poolId][baseKey]++;
// Emit event for executed order
emit OrderExecuted(poolId, posKey);
}
/// @notice Finds ticks with executable limit orders based on price movement
/// @param poolId The pool identifier
/// @param tickBeforeSwap The tick before the swap started
/// @param tickAfterSwap The tick after the swap completed
/// @param zeroForOne Direction of the swap (true for 0→1, false for 1→0)
/// @param tickSpacing The pool's tick spacing
/// @return executableTicks Array of ticks with executable orders
function _findOverlappingPositions(
PoolId poolId,
int24 tickBeforeSwap,
int24 tickAfterSwap,
bool zeroForOne,
int24 tickSpacing
) internal view returns (int24[] memory) {
uint256 absDiff = uint256(int256(abs(tickBeforeSwap - tickAfterSwap)));
int24[] memory executableTicks = new int24[]((absDiff / uint256(int256(tickSpacing))) + 1);
uint256 resultCount = 0;
mapping(int16 => uint256) storage bitmap = zeroForOne ?
token1TickBitmap[poolId] : token0TickBitmap[poolId];
mapping(int24 => bytes32) storage positionMap = zeroForOne ?
token1PositionAtTick[poolId] : token0PositionAtTick[poolId];
int24 tick = tickBeforeSwap;
unchecked {
while (true) {
if (zeroForOne ? tick <= tickAfterSwap : tick >= tickAfterSwap) {
break;
}
(int24 nextInitializedTick, bool initialized) = TickBitmap.nextInitializedTickWithinOneWord(
bitmap,
tick,
tickSpacing,
zeroForOne
);
bool beyondBoundary = zeroForOne ?
nextInitializedTick <= tickAfterSwap :
nextInitializedTick > tickAfterSwap;
if (beyondBoundary) {
nextInitializedTick = tickAfterSwap;
initialized = false;
}
if (initialized) {
if (positionMap[nextInitializedTick] != bytes32(0)) {
executableTicks[resultCount++] = nextInitializedTick;
}
}
if (nextInitializedTick == tickAfterSwap) {
break;
}
tick = zeroForOne ?
nextInitializedTick - 1 :
nextInitializedTick;
}
}
assembly {
mstore(executableTicks, resultCount)
}
return executableTicks;
}
// Helper function to get absolute value
function abs(int24 x) private pure returns (int24) {
return x < 0 ? -x : x;
}
// Position Management Functions
/// @notice Updates or creates a user's position with new liquidity
/// @param poolId The unique identifier for the Uniswap V4 pool
/// @param positionKey The unique identifier for the position
/// @param liquidity The amount of liquidity to add
/// @param user The address of the position owner
function _updateUserPosition(PoolId poolId, bytes32 positionKey, uint128 liquidity, address user) internal {
PositionState storage posState = positionState[poolId][positionKey];
UserPosition storage position = userPositions[poolId][positionKey][user];
if(!positionContributors[poolId][positionKey].contains(user)) {
position.claimablePrincipal = ZERO_DELTA;
position.fees = ZERO_DELTA;
positionContributors[poolId][positionKey].add(user);
userPositionKeys[user][poolId].add(positionKey);
} else {
if (position.liquidity != 0) {
BalanceDelta feeDelta = posState.feePerLiquidity - position.lastFeePerLiquidity;
int128 liq = int128(position.liquidity);
BalanceDelta pendingFees = PositionManagement.calculateScaledUserFee(feeDelta, uint128(liq));
if (pendingFees != ZERO_DELTA)
position.fees = position.fees + pendingFees;
}
}
position.lastFeePerLiquidity = posState.feePerLiquidity;
position.liquidity += liquidity;
posState.totalLiquidity += liquidity;
}
/// @notice Callback function for handling pool manager unlock operations
/// @dev Called by the pool manager during operations that modify pool state
/// @param data Encoded callback data containing operation type and parameters
/// @return bytes Encoded response data based on the callback type
function unlockCallback(bytes calldata data) external returns (bytes memory) {
require(msg.sender == address(poolManager));
UnlockCallbackData memory cbd = abi.decode(data, (UnlockCallbackData));
CallbackType ct = cbd.callbackType;
if(ct == CallbackType.CREATE_ORDERS) return callbackState.handleCreateOrdersCallback(abi.decode(cbd.data, (CreateOrdersCallbackData)));
if(ct == CallbackType.CLAIM_ORDER) return callbackState.handleClaimOrderCallback(abi.decode(cbd.data, (ClaimOrderCallbackData)));
if(ct == CallbackType.CANCEL_ORDER) return callbackState.handleCancelOrderCallback(abi.decode(cbd.data, (CancelOrderCallbackData)));
// If none of the callback types match, return empty bytes
return "";
}
/// @notice Updates the accumulated fees per liquidity for a position
/// @param poolId The unique identifier of the pool containing the position
/// @param positionKey The unique identifier of the position being updated
/// @param feeDelta The change in fees to be distributed, containing both token0 and token1 amounts
function _retrackPositionFee(
PoolId poolId,
bytes32 positionKey,
BalanceDelta feeDelta
) internal {
PositionState storage posState = positionState[poolId][positionKey];
if (posState.totalLiquidity == 0) return;
if(feeDelta == ZERO_DELTA) return;
posState.feePerLiquidity = posState.feePerLiquidity +
PositionManagement.calculateScaledFeePerLiquidity(feeDelta, posState.totalLiquidity);
}
function _handleTokenTransfer(
bool isToken0,
uint256 amount,
PoolKey memory key
) internal nonReentrant {
if (isToken0) {
if (key.currency0.isAddressZero()) {
require(msg.value >= amount);
if (msg.value > amount) {
(bool success, ) = msg.sender.call{value: msg.value - amount}("");
require(success);
}
} else {
require(msg.value == 0);
IERC20(Currency.unwrap(key.currency0)).safeTransferFrom(msg.sender, address(this), amount);
}
} else {
require(msg.value == 0);
IERC20(Currency.unwrap(key.currency1)).safeTransferFrom(msg.sender, address(this), amount);
}
}
// =========== Getter Functions ===========
/// @notice Get positions for a user in a specific pool with pagination
/// @param user The address of the user
/// @param poolId The pool identifier
/// @param offset Starting position index (optional, default 0)
/// @param limit Maximum number of positions to return (optional, use 0 for all positions)
/// @return positions Array of position information
function getUserPositions(
address user,
PoolId poolId,
uint256 offset,
uint256 limit
) external view returns (PositionInfo[] memory positions) {
EnumerableSet.Bytes32Set storage userKeys = userPositionKeys[user][poolId];
uint256 totalLength = userKeys.length();
if (limit == 0) {
limit = totalLength;
}
if (offset >= totalLength) {
return new PositionInfo[](0);
}
uint256 resultCount = (offset + limit > totalLength) ?
(totalLength - offset) : limit;
positions = new PositionInfo[](resultCount);
unchecked {
for(uint256 i = 0; i < resultCount; i++) {
uint256 keyIndex = offset + i;
bytes32 key = userKeys.at(keyIndex);
UserPosition memory userPosition = userPositions[poolId][key][user];
positions[i] = PositionInfo({
liquidity: userPosition.liquidity,
fees: userPosition.fees,
positionKey: key
});
}
}
}
function getUserPositionCount(
address user,
PoolId poolId
) external view returns (uint256) {
return userPositionKeys[user][poolId].length();
}
// =========== Admin Functions ===========
function enableHook(address _hook) external {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || msg.sender == orderBookFactoryAddr, "UnauthorizedAdminOrOrderBookFactoryNotSet");
require(_hook != address(0), "ZeroAddress");
isHook[_hook] = true;
}
function disableHook(address _hook) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_hook != address(0), "ZeroAddress");
isHook[_hook] = false;
}
function setOrderBookFactory(address _orderBookFactoryAddr) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_orderBookFactoryAddr != address(0), "ZeroAddress");
orderBookFactoryAddr = _orderBookFactoryAddr;
}
function setWhitelistedPool(PoolId poolId, bool isWhitelisted) external {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || msg.sender == orderBookFactoryAddr, "UnauthorizedAdminOrOrderBookFactoryNotSet");
whitelistedPool[poolId] = isWhitelisted;
}
// Removed setMinAmount and setMinAmounts functions
/// @notice Sets the hook fee percentage
/// @param _percentage New fee percentage (scaled by FEE_DENOMINATOR)
function setHookFeePercentage(uint256 _percentage) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_percentage < FEE_DENOMINATOR);
hook_fee_percentage = _percentage;
callbackState.hookFeePercentage = _percentage;
}
/// @notice Sets the maximum number of orders that can be created at once
/// @param _limit The new maximum number of orders allowed per pool
function setMaxOrderLimit(uint24 _limit) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_limit > 1);
maxOrderLimit = _limit;
}
/// @notice Sets the treasury address for fee collection
/// @param _treasury The new treasury address
function setTreasury(address _treasury) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_treasury != address(0), "ZeroAddress");
treasury = _treasury;
callbackState.treasury = _treasury;
}
/// @notice Pauses contract functionality
/// @dev Only callable by the contract owner
function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
_pause();
}
/// @notice Unpauses contract functionality
/// @dev Only callable by the contract owner
function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {LimitOrderManager} from "../LimitOrderManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {BalanceDelta, toBalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {Currency, CurrencyLibrary} from "v4-core/types/Currency.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {LiquidityAmounts} from "v4-periphery/lib/v4-core/test/utils/LiquidityAmounts.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {OwnableUpgradeable} from "openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol";
import {AccessControlUpgradeable} from "openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol";
import {Initializable} from "openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol";
import {ILimitOrderManager} from "../interfaces/ILimitOrderManager.sol";
import {TickLibrary} from "../libraries/TickLibrary.sol";
import {PositionManagement} from "../libraries/PositionManagement.sol";
interface ERC20MinimalInterface {
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
/// @title LimitOrderLens
/// @notice Helper contract to provide view functions for accessing data from LimitOrderManager
/// @dev This contract is designed to aid frontend development by providing easy access to user information
contract LimitOrderLens is Initializable, OwnableUpgradeable, AccessControlUpgradeable, UUPSUpgradeable {
using EnumerableSet for EnumerableSet.Bytes32Set;
using PoolIdLibrary for PoolKey;
using CurrencyLibrary for Currency;
error InvalidScaleParameters();
error OrderLimitExceeded(uint256 totalOrders, uint256 maxOrderLimit);
error InsufficientOrders(uint256 totalOrders, uint256 minOrders);
error TickRangeTooSmall();
bytes32 public constant FACTORY_ROLE = keccak256("FACTORY_ROLE");
// Reference to the LimitOrderManager contract
LimitOrderManager public limitOrderManager;
// Direct reference to the pool manager
IPoolManager public poolManager;
// Mapping from PoolId to PoolKey
mapping(PoolId => PoolKey) public poolIdToKey;
// Set of pool IDs for iteration (stored as bytes32)
EnumerableSet.Bytes32Set private poolIdBytes;
// Constants
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
uint256 public constant MIN_ORDERS = 2;
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[47] private __gap;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(address _limitOrderManagerAddr) public initializer {
__Ownable_init(msg.sender);
__AccessControl_init();
__UUPSUpgradeable_init();
require(_limitOrderManagerAddr != address(0));
limitOrderManager = LimitOrderManager(_limitOrderManagerAddr);
// Get poolManager directly from LimitOrderManager
poolManager = IPoolManager(limitOrderManager.poolManager());
// Grant _owner the role which can grant FACTORY_ROLE role to another
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
// Grant _owner the role which can add or remove PoolId
_grantRole(FACTORY_ROLE, msg.sender);
}
/// @notice Add a PoolId and its corresponding PoolKey to the mapping
/// @param poolId The pool identifier
/// @param key The corresponding PoolKey
function addPoolId(PoolId poolId, PoolKey calldata key) external onlyRole(FACTORY_ROLE) {
// Compare the unwrapped bytes32 values
require(PoolId.unwrap(key.toId()) == PoolId.unwrap(poolId));
poolIdToKey[poolId] = key;
poolIdBytes.add(PoolId.unwrap(poolId));
}
/// @dev Required by UUPSUpgradeable to authorize upgrades
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
/// @notice Remove a PoolId from the mapping
/// @param poolId The pool identifier to remove
function removePoolId(PoolId poolId) external onlyOwner {
delete poolIdToKey[poolId];
poolIdBytes.remove(PoolId.unwrap(poolId));
}
/// @notice Decode a position key to extract its components
/// @param positionKey The position key to decode
/// @return bottomTick The bottom tick of the position
/// @return topTick The top tick of the position
/// @return isToken0 Whether the position is for token0
/// @return nonce The nonce value used in the position
function decodePositionKey(bytes32 positionKey) public pure returns (
int24 bottomTick,
int24 topTick,
bool isToken0,
uint256 nonce
) {
uint256 value = uint256(positionKey);
return (
int24(uint24(value >> 232)), // bottomTick
int24(uint24(value >> 208)), // topTick
(value & 1) == 1, // isToken0
(value >> 8) & ((1 << 200) - 1) // nonce (200 bits)
);
}
/// @notice Get positions for a specific user in a specific pool
/// @param user The address of the user
/// @param poolId The pool identifier
/// @return positions Array of position information
function getAllUserPositionsForPool(
address user,
PoolId poolId
) public view returns (LimitOrderManager.PositionInfo[] memory positions) {
// Use getUserPositions from LimitOrderManager, not getUserPositionBalances
// For detailed balance info, use the getPositionBalances function in this contract
return limitOrderManager.getUserPositions(user, poolId, 0, 0);
}
/// @notice Get the PoolId for a given PoolKey
/// @param key The pool key
/// @return poolId The corresponding PoolId
function getPoolId(PoolKey calldata key) external pure returns (PoolId) {
return key.toId();
}
// Helper function to get claimable balances for a user in a pool
function _getClaimableBalances(
address user,
PoolKey memory key
) internal view returns (
LimitOrderManager.ClaimableTokens memory token0Balance,
LimitOrderManager.ClaimableTokens memory token1Balance
) {
PoolId poolId = key.toId();
// Initialize the balance structures
token0Balance.token = key.currency0;
token1Balance.token = key.currency1;
// Get all positions for the user in this pool
LimitOrderManager.PositionInfo[] memory positions = limitOrderManager.getUserPositions(user, poolId, 0, 0);
// Iterate through each position and accumulate balances
for (uint i = 0; i < positions.length;) {
// Get position-specific balances
LimitOrderManager.PositionBalances memory posBalances =
getPositionBalances(user, poolId, positions[i].positionKey);
// Accumulate principals and fees
unchecked {
token0Balance.principal += posBalances.principal0;
token1Balance.principal += posBalances.principal1;
token0Balance.fees += posBalances.fees0;
token1Balance.fees += posBalances.fees1;
i++;
}
}
return (token0Balance, token1Balance);
}
/// @notice Tick information including liquidity and token amounts
struct TickInfo {
int24 tick;
uint160 sqrtPrice;
uint256 token0Amount;
uint256 token1Amount;
uint256 totalTokenAmountsinToken1;
}
/// @notice Populated tick data from the pool
struct PopulatedTick {
int24 tick;
int128 liquidityNet;
uint128 liquidityGross;
}
/// @notice Get tick information for a range around the current tick with orderbook-style liquidity
/// @param poolId The pool identifier
/// @param numTicks Number of ticks to include on each side of the current tick
/// @return currentTick The current tick from slot0
/// @return sqrtPriceX96 The sqrt price from slot0
/// @return tickInfos Array of tick information with orderbook liquidity
function getTickInfosAroundCurrent(
PoolId poolId,
uint24 numTicks
) external view returns (int24 currentTick, uint160 sqrtPriceX96, TickInfo[] memory tickInfos) {
PoolKey memory poolKey = poolIdToKey[poolId];
(sqrtPriceX96, currentTick, , ) = StateLibrary.getSlot0(poolManager, poolId);
// Calculate tick range
(int24 startTick, int24 endTick) = _calculateTickRange(
currentTick, poolKey.tickSpacing, numTicks
);
// Get populated ticks in a broader range to capture AMM liquidity boundaries
// that might be outside our display range but affect liquidity calculation
int24 broadStartTick = TickMath.minUsableTick(poolKey.tickSpacing);
// Get all populated ticks from min tick to our end tick to properly calculate liquidity
PopulatedTick[] memory populatedTicks = _getPopulatedTicksInRange(
poolId, poolKey.tickSpacing, broadStartTick, endTick
);
// Calculate orderbook-style liquidity for each tick in range
tickInfos = _calculateOrderbookLiquidity(
populatedTicks,
startTick,
endTick,
poolKey.tickSpacing,
currentTick,
sqrtPriceX96
);
return (currentTick, sqrtPriceX96, tickInfos);
}
/// @notice Calculate the tick range around the current tick
/// @param currentTick The current tick
/// @param tickSpacing The tick spacing
/// @param numTicks Number of ticks on each side
/// @return startTick The start of the range
/// @return endTick The end of the range
function _calculateTickRange(
int24 currentTick,
int24 tickSpacing,
uint24 numTicks
) internal pure returns (int24 startTick, int24 endTick) {
int24 alignedTick = (currentTick / tickSpacing) * tickSpacing;
startTick = alignedTick - int24(numTicks);
endTick = alignedTick + int24(numTicks);
int24 minTick = TickMath.minUsableTick(tickSpacing);
int24 maxTick = TickMath.maxUsableTick(tickSpacing);
if (startTick < minTick) startTick = minTick;
if (endTick > maxTick) endTick = maxTick;
return (startTick, endTick);
}
/// @notice Get all populated ticks within a range
/// @param poolId The pool identifier
/// @param tickSpacing The tick spacing
/// @param startTick The start of the range
/// @param endTick The end of the range
/// @return populatedTicks Array of populated tick data
function _getPopulatedTicksInRange(
PoolId poolId,
int24 tickSpacing,
int24 startTick,
int24 endTick
) internal view returns (PopulatedTick[] memory populatedTicks) {
// Count total populated ticks in range
uint256 totalPopulatedTicks = 0;
for (int16 wordPos = int16((startTick / tickSpacing) >> 8); wordPos <= int16((endTick / tickSpacing) >> 8);) {
uint256 bitmap = StateLibrary.getTickBitmap(poolManager, poolId, wordPos);
if (bitmap != 0) {
// Inline count bits logic directly here
for (uint256 i = 0; i < 256;) {
if (bitmap & (1 << i) == 0) {
unchecked { i++; }
continue;
}
int24 tick = ((int24(wordPos) << 8) + int24(uint24(i))) * tickSpacing;
if (tick >= startTick && tick <= endTick) {
unchecked { totalPopulatedTicks++; }
}
unchecked { i++; }
}
}
unchecked { wordPos++; }
}
if (totalPopulatedTicks == 0) {
return new PopulatedTick[](0);
}
// Collect the actual populated tick data
populatedTicks = new PopulatedTick[](totalPopulatedTicks);
uint256 index = 0;
for (int16 wordPos = int16((startTick / tickSpacing) >> 8); wordPos <= int16((endTick / tickSpacing) >> 8);) {
uint256 bitmap = StateLibrary.getTickBitmap(poolManager, poolId, wordPos);
if (bitmap != 0) {
// Inline the _fillPopulatedTicksFromWord logic
for (uint256 i = 0; i < 256;) {
if (bitmap & (1 << i) != 0) {
int24 tick = ((int24(wordPos) << 8) + int24(uint24(i))) * tickSpacing;
if (tick >= startTick && tick <= endTick) {
(uint128 liquidityGross, int128 liquidityNet) =
StateLibrary.getTickLiquidity(poolManager, poolId, tick);
populatedTicks[index++] = PopulatedTick({
tick: tick,
liquidityNet: liquidityNet,
liquidityGross: liquidityGross
});
}
}
unchecked { i++; }
}
}
unchecked { wordPos++; }
}
return populatedTicks;
}
/// @notice Calculate orderbook-style liquidity for each tick in the range
/// @param populatedTicks Array of populated tick data
/// @param startTick The start of the range
/// @param endTick The end of the range
/// @param tickSpacing The tick spacing
/// @param currentTick The current tick
/// @param sqrtPriceX96 The current sqrt price
/// @return tickInfos Array of tick information with calculated liquidity
function _calculateOrderbookLiquidity(
PopulatedTick[] memory populatedTicks,
int24 startTick,
int24 endTick,
int24 tickSpacing,
int24 currentTick,
uint160 sqrtPriceX96
) internal pure returns (TickInfo[] memory tickInfos) {
// Calculate number of ticks in range
uint256 totalTicks = uint256(int256((endTick - startTick) / tickSpacing)) + 1;
tickInfos = new TickInfo[](totalTicks);
// Fill tick info for each tick in range
for (uint256 i = 0; i < totalTicks;) {
int24 tick = startTick + int24(int256(i) * int256(tickSpacing));
// Calculate active liquidity at this tick
uint128 liquidityAtTick = _calculateLiquidityAtTickFromPopulated(
populatedTicks, tick
);
// Set tick info with conditional logic based on currentTick
if (currentTick >= tick) {
tickInfos[i].tick = tick;
tickInfos[i].sqrtPrice = TickMath.getSqrtPriceAtTick(tick);
} else {
tickInfos[i].tick = tick + tickSpacing;
tickInfos[i].sqrtPrice = TickMath.getSqrtPriceAtTick(tick + tickSpacing);
}
// Calculate token amounts based on liquidity and price position
if (liquidityAtTick > 0) {
_calculateTokenAmountsFromLiquidity(
tickInfos[i],
liquidityAtTick,
tick,
tickSpacing,
currentTick,
sqrtPriceX96
);
}
unchecked { i++; }
}
return tickInfos;
}
/// @notice Calculate active liquidity at a specific tick from populated tick data
/// @param populatedTicks Array of populated tick data
/// @param targetTick The tick to calculate liquidity for
/// @return activeLiquidity The active liquidity at the target tick
function _calculateLiquidityAtTickFromPopulated(
PopulatedTick[] memory populatedTicks,
int24 targetTick
) internal pure returns (uint128 activeLiquidity) {
// Walk through all populated ticks and accumulate liquidityNet
// for ticks <= targetTick
for (uint256 i = 0; i < populatedTicks.length;) {
if (populatedTicks[i].tick <= targetTick) {
// Inline _addDelta logic
int128 liquidityNet = populatedTicks[i].liquidityNet;
unchecked {
if (liquidityNet < 0) {
activeLiquidity = activeLiquidity - uint128(-liquidityNet);
} else {
activeLiquidity = activeLiquidity + uint128(liquidityNet);
}
}
}
unchecked { i++; }
}
return activeLiquidity;
}
/// @notice Calculate token amounts for a tick based on its liquidity
/// @param tickInfo The tick info struct to populate
/// @param liquidity The liquidity amount
/// @param tick The tick value
/// @param tickSpacing The tick spacing
/// @param currentTick The current tick
/// @param sqrtPriceX96 The current sqrt price
function _calculateTokenAmountsFromLiquidity(
TickInfo memory tickInfo,
uint128 liquidity,
int24 tick,
int24 tickSpacing,
int24 currentTick,
uint160 sqrtPriceX96
) internal pure {
uint160 sqrtPriceLowerX96 = TickMath.getSqrtPriceAtTick(tick);
uint160 sqrtPriceUpperX96 = TickMath.getSqrtPriceAtTick(tick + tickSpacing);
// Determine which token amounts to calculate based on current price
if (currentTick < tick) {
// Price is below this tick range - all token0
tickInfo.token0Amount = LiquidityAmounts.getAmount0ForLiquidity(
sqrtPriceLowerX96,
sqrtPriceUpperX96,
liquidity
);
} else if (currentTick >= tick + tickSpacing) {
// Price is above this tick range - all token1
tickInfo.token1Amount = LiquidityAmounts.getAmount1ForLiquidity(
sqrtPriceLowerX96,
sqrtPriceUpperX96,
liquidity
);
} else {
// Price is within this tick range - both tokens
(tickInfo.token0Amount, tickInfo.token1Amount) = LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96,
sqrtPriceLowerX96,
sqrtPriceUpperX96,
liquidity
);
}
// Calculate total value in token1 terms
if (tickInfo.token0Amount > 0) {
tickInfo.totalTokenAmountsinToken1 = FullMath.mulDiv(
tickInfo.token0Amount,
FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, 1 << 96),
1 << 96
) + tickInfo.token1Amount;
} else {
tickInfo.totalTokenAmountsinToken1 = tickInfo.token1Amount;
}
}
/// @notice Get positions for a user across all tracked pools with pagination
/// @param user The address of the user
/// @param offset Starting position index in the global list
/// @param limit Maximum number of positions to return (optional, use 0 for all positions)
/// @return positions Array of detailed user position information
/// @return totalCount Total number of positions across all pools
function getUserPositionsPaginated(
address user,
uint256 offset,
uint256 limit
) external view returns (
DetailedUserPosition[] memory positions,
uint256 totalCount
) {
totalCount = _countTotalUserPositions(user);
if (limit == 0) {
limit = totalCount; // normalize to mean "all positions"
}
if (offset >= totalCount) {
return (new DetailedUserPosition[](0), totalCount);
}
uint256 count = (offset + limit > totalCount) ?
(totalCount - offset) : limit;
positions = new DetailedUserPosition[](count);
_processPositionsWithPagination(user, offset, count, positions);
return (positions, totalCount);
}
struct PaginationParams {
uint256 positionsSoFar;
uint256 positionsToSkip;
uint256 resultIndex;
uint256 count;
uint256 poolPositionCount;
}
function _processPositionsWithPagination(
address user,
uint256 offset,
uint256 count,
DetailedUserPosition[] memory positions
) internal view {
uint256 poolCount = poolIdBytes.length();
PaginationParams memory params = PaginationParams({
positionsSoFar: 0,
positionsToSkip: offset,
resultIndex: 0,
count: count,
poolPositionCount: 0
});
for (uint256 i = 0; i < poolCount && params.resultIndex < params.count;) {
PoolId poolId = PoolId.wrap(poolIdBytes.at(i));
params.poolPositionCount = limitOrderManager.getUserPositionCount(user, poolId);
if (params.poolPositionCount == 0) {
unchecked { i++; }
continue;
}
PoolKey memory poolKey = poolIdToKey[poolId];
if (poolKey.fee == 0) {
unchecked { i++; }
continue;
}
if (params.positionsSoFar + params.poolPositionCount <= params.positionsToSkip) {
params.positionsSoFar += params.poolPositionCount;
unchecked { i++; }
continue;
}
(params.resultIndex, params.positionsSoFar) = _processPoolPositionsForPagination(
user,
poolId,
poolKey,
params,
positions
);
unchecked { i++; }
}
}
function _processPoolPositionsForPagination(
address user,
PoolId poolId,
PoolKey memory poolKey,
PaginationParams memory params,
DetailedUserPosition[] memory positions
) internal view returns (uint256, uint256) {
uint256 poolOffset = 0;
uint256 poolLimit = params.poolPositionCount;
if (params.positionsSoFar < params.positionsToSkip) {
poolOffset = params.positionsToSkip - params.positionsSoFar;
poolLimit = params.poolPositionCount - poolOffset;
}
if (params.resultIndex + poolLimit > params.count) {
poolLimit = params.count - params.resultIndex;
}
PoolStateData memory poolData = _getPoolStateData(poolId, poolKey, user);
LimitOrderManager.PositionInfo[] memory poolPositions =
limitOrderManager.getUserPositions(user, poolId, poolOffset, poolLimit);
for (uint256 j = 0; j < poolPositions.length && params.resultIndex < params.count; j++) {
_processPosition(
user,
poolId,
poolKey,
poolPositions[j].positionKey,
poolData,
positions,
params.resultIndex
);
params.resultIndex++;
params.positionsSoFar++;
}
params.positionsSoFar += (params.poolPositionCount - poolOffset - poolPositions.length);
return (params.resultIndex, params.positionsSoFar);
}
/// @notice Count total positions for a user across all pools
/// @param user The user address
/// @return totalPositions The total number of positions
function _countTotalUserPositions(address user) internal view returns (uint256 totalPositions) {
uint256 poolCount = poolIdBytes.length();
for (uint256 i = 0; i < poolCount;) {
PoolId poolId = PoolId.wrap(poolIdBytes.at(i));
unchecked {
totalPositions += limitOrderManager.getUserPositionCount(user, poolId);
i++;
}
}
return totalPositions;
}
/// @notice Get pool state data for a specific pool
/// @param poolId The pool ID
/// @param poolKey The pool key
/// @param user The user address
/// @return data The pool state data
function _getPoolStateData(
PoolId poolId,
PoolKey memory poolKey,
address user
) internal view returns (PoolStateData memory data) {
data = _getPoolBasicStateData(poolId, poolKey);
_getPoolUserBalances(user, poolKey, data);
return data;
}
/// @notice Get basic pool state data
/// @param poolId The pool ID
/// @param poolKey The pool key
/// @return data The basic pool state data
function _getPoolBasicStateData(
PoolId poolId,
PoolKey memory poolKey
) internal view returns (PoolStateData memory data) {
(data.sqrtPriceX96, data.currentTick, , ) = StateLibrary.getSlot0(poolManager, poolId);
(data.token0Symbol, data.token0Decimals) = _getTokenInfo(poolKey.currency0);
(data.token1Symbol, data.token1Decimals) = _getTokenInfo(poolKey.currency1);
return data;
}
/// @notice Get user balance data for a pool
/// @param user The user address
/// @param poolKey The pool key
/// @param data The pool state data to update with balance information
function _getPoolUserBalances(
address user,
PoolKey memory poolKey,
PoolStateData memory data
) internal view {
(
LimitOrderManager.ClaimableTokens memory token0Balance,
LimitOrderManager.ClaimableTokens memory token1Balance
) = _getClaimableBalances(user, poolKey);
data.token0Principal = token0Balance.principal;
data.token0Fees = token0Balance.fees;
data.token1Principal = token1Balance.principal;
data.token1Fees = token1Balance.fees;
}
/// @notice Process a single position and add to result array
/// @param user The user address
/// @param poolId The pool ID
/// @param poolKey The pool key
/// @param positionKey The position key
/// @param poolData The pool state data
/// @param allPositions The result array to populate
/// @param index The index in the result array
function _processPosition(
address user,
PoolId poolId,
PoolKey memory poolKey,
bytes32 positionKey,
PoolStateData memory poolData,
DetailedUserPosition[] memory allPositions,
uint256 index
) internal view {
uint256 keyValue = uint256(positionKey);
int24 bottomTick = int24(uint24(keyValue >> 232));
int24 topTick = int24(uint24(keyValue >> 208));
bool isToken0 = (keyValue & 1) == 1;
_createBasicPositionInfo(allPositions, index, poolId, poolKey, poolData, bottomTick, topTick, isToken0);
_addTickPriceInfo(allPositions, index, bottomTick, topTick, poolData.sqrtPriceX96);
_addBalanceInfo(allPositions, index, poolId, positionKey, user, poolData, bottomTick, topTick, isToken0);
}
/// @notice Add basic position information to a DetailedUserPosition
function _createBasicPositionInfo(
DetailedUserPosition[] memory positions,
uint256 index,
PoolId poolId,
PoolKey memory poolKey,
PoolStateData memory poolData,
int24 bottomTick,
int24 topTick,
bool isToken0
) internal pure {
positions[index].poolId = poolId;
positions[index].currency0 = poolKey.currency0;
positions[index].currency1 = poolKey.currency1;
positions[index].token0Symbol = poolData.token0Symbol;
positions[index].token1Symbol = poolData.token1Symbol;
positions[index].token0Decimals = poolData.token0Decimals;
positions[index].token1Decimals = poolData.token1Decimals;
positions[index].isToken0 = isToken0;
positions[index].bottomTick = bottomTick;
positions[index].topTick = topTick;
positions[index].currentTick = poolData.currentTick;
positions[index].tickSpacing = poolKey.tickSpacing;
}
/// @notice Add tick price information to a DetailedUserPosition
function _addTickPriceInfo(
DetailedUserPosition[] memory positions,
uint256 index,
int24 bottomTick,
int24 topTick,
uint160 sqrtPriceX96
) internal pure {
// Calculate sqrt prices at ticks
uint160 sqrtPriceBottomTickX96 = TickMath.getSqrtPriceAtTick(bottomTick);
uint160 sqrtPriceTopTickX96 = TickMath.getSqrtPriceAtTick(topTick);
positions[index].sqrtPrice = sqrtPriceX96;
positions[index].sqrtPriceBottomTick = sqrtPriceBottomTickX96;
positions[index].sqrtPriceTopTick = sqrtPriceTopTickX96;
}
/// @notice Add balance information to a DetailedUserPosition
function _addBalanceInfo(
DetailedUserPosition[] memory positions,
uint256 index,
PoolId poolId,
bytes32 positionKey,
address user,
PoolStateData memory poolData,
int24 bottomTick,
int24 topTick,
bool isToken0
) internal view {
(uint128 liquidity, , , ) = limitOrderManager.userPositions(poolId, positionKey, user);
(,,bool isActive,) = limitOrderManager.positionState(poolId, positionKey);
positions[index].liquidity = liquidity;
positions[index].positionKey = positionKey;
positions[index].totalCurrentToken0Principal = poolData.token0Principal;
positions[index].totalCurrentToken1Principal = poolData.token1Principal;
positions[index].feeRevenue0 = poolData.token0Fees;
positions[index].feeRevenue1 = poolData.token1Fees;
LimitOrderManager.PositionBalances memory posBalances =
getPositionBalances(user, poolId, positionKey);
positions[index].positionToken0Principal = posBalances.principal0;
positions[index].positionToken1Principal = posBalances.principal1;
positions[index].positionFeeRevenue0 = posBalances.fees0;
positions[index].positionFeeRevenue1 = posBalances.fees1;
_addExecutionAmounts(positions, index, bottomTick, topTick, liquidity, isToken0);
positions[index].claimable = !isActive;
uint160 sqrtPriceBottomTickX96 = positions[index].sqrtPriceBottomTick;
uint160 sqrtPriceTopTickX96 = positions[index].sqrtPriceTopTick;
if (isToken0) {
positions[index].orderSize = LiquidityAmounts.getAmount0ForLiquidity(
sqrtPriceBottomTickX96,
sqrtPriceTopTickX96,
liquidity
);
} else {
positions[index].orderSize = LiquidityAmounts.getAmount1ForLiquidity(
sqrtPriceBottomTickX96,
sqrtPriceTopTickX96,
liquidity
);
}
}
/// @notice Add execution amount information to a DetailedUserPosition
function _addExecutionAmounts(
DetailedUserPosition[] memory positions,
uint256 index,
int24 bottomTick,
int24 topTick,
uint128 liquidity,
bool isToken0
) internal pure {
// Get sqrt prices only once
uint160 sqrtPriceBottomTickX96 = TickMath.getSqrtPriceAtTick(bottomTick);
uint160 sqrtPriceTopTickX96 = TickMath.getSqrtPriceAtTick(topTick);
if (isToken0) {
positions[index].totalToken0AtExecution = 0;
positions[index].totalToken1AtExecution = LiquidityAmounts.getAmount1ForLiquidity(
sqrtPriceBottomTickX96,
sqrtPriceTopTickX96,
liquidity
);
} else {
positions[index].totalToken0AtExecution = LiquidityAmounts.getAmount0ForLiquidity(
sqrtPriceBottomTickX96,
sqrtPriceTopTickX96,
liquidity
);
positions[index].totalToken1AtExecution = 0;
}
}
/// @notice Get token symbol and decimals information
/// @param currency The currency to get information for
/// @return symbol The token symbol
/// @return decimals The token decimals
function _getTokenInfo(Currency currency) internal view returns (string memory symbol, uint8 decimals) {
if (currency.isAddressZero()) {
return ("NATIVE", 18);
} else {
ERC20MinimalInterface token = ERC20MinimalInterface(Currency.unwrap(currency));
symbol = token.symbol();
decimals = token.decimals();
}
}
/// @notice Get the minimum and maximum valid ticks for a limit order in a pool
/// @param poolId The pool identifier
/// @param isToken0 True if order is for token0, false for token1
/// @return minTick The minimum valid tick for the order
/// @return maxTick The maximum valid tick for the order
function getMinAndMaxTickForLimitOrders(PoolId poolId, bool isToken0) external view returns (int24 minTick, int24 maxTick) {
PoolKey memory poolKey = poolIdToKey[poolId];
(, int24 currentTick, ,) = StateLibrary.getSlot0(poolManager, poolId);
int24 tickSpacing = poolKey.tickSpacing;
int24 absoluteMinTick = TickMath.minUsableTick(tickSpacing);
int24 absoluteMaxTick = TickMath.maxUsableTick(tickSpacing);
int24 roundedCurrentTick;
if (isToken0) {
roundedCurrentTick = currentTick >= 0 ?
(currentTick / tickSpacing) * tickSpacing + tickSpacing :
((currentTick % tickSpacing == 0) ? currentTick + tickSpacing : (currentTick / tickSpacing) * tickSpacing);
minTick = roundedCurrentTick + tickSpacing;
maxTick = absoluteMaxTick;
} else {
roundedCurrentTick = currentTick >= 0 ?
(currentTick / tickSpacing) * tickSpacing :
((currentTick % tickSpacing == 0) ? currentTick : (currentTick / tickSpacing) * tickSpacing - tickSpacing);
minTick = absoluteMinTick;
maxTick = roundedCurrentTick - tickSpacing;
}
return (minTick, maxTick);
}
/// @notice Get the minimum and maximum valid ticks for scale orders in a pool
/// @param poolId The pool identifier
/// @param isToken0 True if order is for token0, false for token1
/// @return minTick The minimum valid tick for the order
/// @return maxTick The maximum valid tick for the order
function getMinAndMaxTickForScaleOrders(PoolId poolId, bool isToken0) external view returns (int24 minTick, int24 maxTick) {
PoolKey memory poolKey = poolIdToKey[poolId];
(, int24 currentTick, ,) = StateLibrary.getSlot0(poolManager, poolId);
int24 tickSpacing = poolKey.tickSpacing;
int24 absoluteMinTick = TickMath.minUsableTick(tickSpacing);
int24 absoluteMaxTick = TickMath.maxUsableTick(tickSpacing);
if (isToken0) {
minTick = currentTick + 1;
minTick = minTick % tickSpacing == 0 ? minTick :
minTick > 0 ? (minTick / tickSpacing + 1) * tickSpacing :
(minTick / tickSpacing) * tickSpacing;
maxTick = absoluteMaxTick;
} else {
minTick = absoluteMinTick;
maxTick = currentTick;
maxTick = maxTick % tickSpacing == 0 ? maxTick :
maxTick > 0 ? (maxTick / tickSpacing) * tickSpacing :
(maxTick / tickSpacing - 1) * tickSpacing;
}
return (minTick, maxTick);
}
/// @notice Calculate the minimum and maximum number of scale orders that can fit between two ticks
/// @param poolId The pool identifier
/// @param bottomTick The bottom tick of the range
/// @param topTick The top tick of the range
/// @return minOrders The minimum number of scale orders (always 2)
/// @return maxOrders The maximum number of scale orders possible
function minAndMaxScaleOrders(
PoolId poolId,
int24 bottomTick,
int24 topTick
) public view returns (uint256 minOrders, uint256 maxOrders) {
PoolKey memory poolKey = poolIdToKey[poolId];
int24 tickSpacing = poolKey.tickSpacing;
int24 minTickRange = 2 * tickSpacing;
if (topTick - bottomTick < minTickRange) {
revert TickRangeTooSmall();
}
maxOrders = uint256(uint24((topTick - bottomTick) / tickSpacing));
minOrders = 2;
return (minOrders, maxOrders);
}
/// @notice Calculate the scaled user fee based on the fee difference and liquidity
/// @dev Used by the LimitOrderManager to calculate user fees
/// @param feeDiff The fee difference to scale
/// @param liquidity The user's liquidity amount
/// @return The scaled fee as a BalanceDelta
function calculateScaledUserFee(
BalanceDelta feeDiff,
uint128 liquidity
) internal pure returns (BalanceDelta) {
if(feeDiff == BalanceDelta.wrap(0) || liquidity == 0) return BalanceDelta.wrap(0);
return toBalanceDelta(
feeDiff.amount0() >= 0
? int128(int256(FullMath.mulDiv(uint256(uint128(feeDiff.amount0())), uint256(liquidity), 1e18)))
: -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDiff.amount0())), uint256(liquidity), 1e18))),
feeDiff.amount1() >= 0
? int128(int256(FullMath.mulDiv(uint256(uint128(feeDiff.amount1())), uint256(liquidity), 1e18)))
: -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDiff.amount1())), uint256(liquidity), 1e18)))
);
}
// Add these helper functions before getPositionBalances
function calculatePositionFee(
PoolId poolId,
int24 bottomTick,
int24 topTick,
bool isToken0
) internal view returns (uint256 fee0, uint256 fee1) {
(uint128 liquidityBefore, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) =
StateLibrary.getPositionInfo(
poolManager,
poolId,
address(limitOrderManager),
bottomTick,
topTick,
bytes32(uint256(isToken0 ? 0 : 1)) // salt
);
(uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = StateLibrary.getFeeGrowthInside(
poolManager,
poolId,
bottomTick,
topTick
);
uint256 feeGrowthDelta0 = 0;
uint256 feeGrowthDelta1 = 0;
unchecked {
if (feeGrowthInside0X128 != feeGrowthInside0LastX128) {
feeGrowthDelta0 = feeGrowthInside0X128 - feeGrowthInside0LastX128;
}
if (feeGrowthInside1X128 != feeGrowthInside1LastX128) {
feeGrowthDelta1 = feeGrowthInside1X128 - feeGrowthInside1LastX128;
}
fee0 = FullMath.mulDiv(feeGrowthDelta0, liquidityBefore, 1 << 128);
fee1 = FullMath.mulDiv(feeGrowthDelta1, liquidityBefore, 1 << 128);
}
return (fee0, fee1);
}
// Add this function before getPositionBalances
function _constructPositionParams(
bytes32 positionKey,
address user,
PoolId poolId
) internal view returns (PositionManagement.PositionParams memory) {
(int24 bottomTick, int24 topTick, bool isToken0, ) = decodePositionKey(positionKey);
return PositionManagement.PositionParams({
position: userPositions(poolId, positionKey, user),
posState: positionState(poolId, positionKey),
poolManager: poolManager,
poolId: poolId,
bottomTick: bottomTick,
topTick: topTick,
isToken0: isToken0,
feeDenom: limitOrderManager.FEE_DENOMINATOR(),
hookFeePercentage: limitOrderManager.hook_fee_percentage()
});
}
// Helper function to get user position data
function userPositions(
PoolId poolId,
bytes32 positionKey,
address user
) internal view returns (ILimitOrderManager.UserPosition memory position) {
(uint128 liquidity, BalanceDelta lastFeePerLiquidity, BalanceDelta claimablePrincipal, BalanceDelta fees) =
limitOrderManager.userPositions(poolId, positionKey, user);
position.liquidity = liquidity;
position.lastFeePerLiquidity = lastFeePerLiquidity;
position.claimablePrincipal = claimablePrincipal;
position.fees = fees;
}
// Helper function to get position state data
function positionState(
PoolId poolId,
bytes32 positionKey
) internal view returns (ILimitOrderManager.PositionState memory posState) {
(BalanceDelta feePerLiquidity, uint128 totalLiquidity, bool isActive, uint256 currentNonce) =
limitOrderManager.positionState(poolId, positionKey);
posState.feePerLiquidity = feePerLiquidity;
posState.totalLiquidity = totalLiquidity;
posState.isActive = isActive;
// posState.isWaitingKeeper = isWaitingKeeper;
posState.currentNonce = currentNonce;
}
// Replace the existing getPositionBalances function with this updated version
function getPositionBalances(
address user,
PoolId poolId,
bytes32 positionKey
) public view returns (LimitOrderManager.PositionBalances memory balances) {
PositionManagement.PositionParams memory params = _constructPositionParams(positionKey, user, poolId);
balances = PositionManagement.getPositionBalances(params, address(limitOrderManager));
}
// Add a new struct and function
struct PoolPositionCount {
PoolId poolId;
uint256 count;
}
/// @notice Get position counts for a user across all tracked pools
/// @param user The address of the user
/// @return counts Array of poolId and position count pairs
function getUserPositionCountsAcrossPools(address user) external view returns (
PoolPositionCount[] memory counts
) {
uint256 poolCount = poolIdBytes.length();
counts = new PoolPositionCount[](poolCount);
for (uint256 i = 0; i < poolCount;) {
PoolId poolId = PoolId.wrap(poolIdBytes.at(i));
uint256 positionCount = limitOrderManager.getUserPositionCount(user, poolId);
counts[i] = PoolPositionCount({
poolId: poolId,
count: positionCount
});
unchecked { i++; }
}
return counts;
}
/// @notice Get position keys that can be claimed by a user
/// @dev Returns position keys for positions that are inactive or have claimable principal
/// @dev Limited by offset/limit to avoid gas issues with large position counts
/// @param user The address of the user
/// @param poolId The pool identifier
/// @param offset Starting position to fetch from
/// @param limit Maximum number of positions to return
/// @return positionKeys Array of claimable position keys
function getClaimablePositions(
address user,
PoolId poolId,
uint256 offset,
uint256 limit
) external view returns (bytes32[] memory positionKeys, uint256 count) {
LimitOrderManager.PositionInfo[] memory positions =
limitOrderManager.getUserPositions(user, poolId, offset, limit);
bytes32[] memory temp = new bytes32[](positions.length);
count = 0;
for (uint256 i = 0; i < positions.length;) {
bytes32 positionKey = positions[i].positionKey;
uint128 liquidity = positions[i].liquidity;
(,, BalanceDelta claimablePrincipal,) =
limitOrderManager.userPositions(poolId, positionKey, user);
(,,bool isActive,) = limitOrderManager.positionState(poolId, positionKey);
if (liquidity > 0 && (!isActive || claimablePrincipal != ZERO_DELTA)) {
temp[count++] = positionKey;
}
unchecked { i++; }
}
positionKeys = new bytes32[](count);
for (uint256 i = 0; i < count;) {
positionKeys[i] = temp[i];
unchecked { i++; }
}
return (positionKeys, count);
}
/// @notice Get position keys that can be cancelled by a user
/// @dev Returns position keys for active positions with liquidity
/// @dev Limited by offset/limit to avoid gas issues with large position counts
/// @param user The address of the user
/// @param poolId The pool identifier
/// @param offset Starting position to fetch from
/// @param limit Maximum number of positions to return
/// @return positionKeys Array of cancellable position keys
function getCancellablePositions(
address user,
PoolId poolId,
uint256 offset,
uint256 limit
) external view returns (bytes32[] memory positionKeys, uint256 count) {
LimitOrderManager.PositionInfo[] memory positions =
limitOrderManager.getUserPositions(user, poolId, offset, limit);
bytes32[] memory temp = new bytes32[](positions.length);
count = 0;
for (uint256 i = 0; i < positions.length;) {
bytes32 positionKey = positions[i].positionKey;
uint128 liquidity = positions[i].liquidity;
(,,bool isActive,) = limitOrderManager.positionState(poolId, positionKey);
if (liquidity > 0 && isActive) {
temp[count++] = positionKey;
}
unchecked { i++; }
}
positionKeys = new bytes32[](count);
for (uint256 i = 0; i < count;) {
positionKeys[i] = temp[i];
unchecked { i++; }
}
return (positionKeys, count);
}
/// @notice Helper function to assign tick ranges to orders
function _assignTickRanges(
OrderStruct[] memory orders,
PoolId poolId,
int24 bottomTick,
int24 topTick,
bool isToken0,
uint256 totalOrders,
uint256 sizeSkew,
int24 tickSpacing
) internal view {
(, int24 currentTick, , ) = StateLibrary.getSlot0(poolManager, poolId);
ILimitOrderManager.OrderInfo[] memory ticks = TickLibrary.validateAndPrepareScaleOrders(
bottomTick, topTick, currentTick, isToken0, totalOrders, sizeSkew, tickSpacing
);
for (uint256 i = 0; i < totalOrders;) {
orders[i].lowerTick = ticks[i].bottomTick;
orders[i].upperTick = ticks[i].topTick;
unchecked { i++; }
}
}
function verifyOrderSizes(
PoolId poolId,
bool isToken0,
int24 bottomTick,
int24 topTick,
uint256 totalAmount,
uint256 totalOrders,
uint256 sizeSkew
) public view returns (OrderStruct[] memory) {
if (totalOrders < MIN_ORDERS) {
revert InsufficientOrders(totalOrders, MIN_ORDERS);
}
if (totalOrders > limitOrderManager.maxOrderLimit()) {
revert OrderLimitExceeded(totalOrders, limitOrderManager.maxOrderLimit());
}
require(sizeSkew != 0);
OrderStruct[] memory orders = new OrderStruct[](totalOrders);
// Block 1: Calculate order amounts
{
uint256 totalAmountUsed;
for (uint256 i = 0; i < totalOrders;) {
orders[i].amount = (i == totalOrders - 1) ?
totalAmount - totalAmountUsed :
PositionManagement._calculateOrderSize(totalAmount, totalOrders, sizeSkew, i + 1);
totalAmountUsed += orders[i].amount;
unchecked { i++; }
}
}
// Block 2: Assign tick ranges
{
(, int24 currentTick, , ) = StateLibrary.getSlot0(poolManager, poolId);
int24 tickSpacing = poolIdToKey[poolId].tickSpacing;
ILimitOrderManager.OrderInfo[] memory ticks = TickLibrary.validateAndPrepareScaleOrders(
bottomTick, topTick, currentTick, isToken0, totalOrders, sizeSkew, tickSpacing
);
for (uint256 i = 0; i < totalOrders;) {
orders[i].lowerTick = ticks[i].bottomTick;
orders[i].upperTick = ticks[i].topTick;
unchecked { i++; }
}
}
return orders;
}
/// @notice Calculate order sizes for a distribution without validation checks
/// @param totalAmount Total amount of tokens to distribute
/// @param totalOrders Number of orders to create
/// @param sizeSkew Skew factor (scaled by 1e18, where 1e18 = no skew)
/// @return An array of order sizes
function calculateOrderSizes(
uint256 totalAmount,
uint256 totalOrders,
uint256 sizeSkew
) public pure returns (uint256[] memory) {
uint256[] memory orderSizes = new uint256[](totalOrders);
uint256 totalAmountUsed;
for (uint256 i = 0; i < totalOrders;) {
if (i == totalOrders - 1) {
orderSizes[i] = totalAmount - totalAmountUsed;
} else {
orderSizes[i] = PositionManagement._calculateOrderSize(
totalAmount,
totalOrders,
sizeSkew,
i + 1
);
totalAmountUsed += orderSizes[i];
}
unchecked { i++; }
}
return orderSizes;
}
/// @notice Retrieve information for all tracked pools
/// @dev Leverages the private set of pool IDs that the contract owner has added via addPoolId().
/// This is a read-only helper for front-ends to quickly discover the available pools.
/// @return pools Array of PoolStruct containing pool id, key and token symbols for each pool
function getAllPools() external view returns (PoolStruct[] memory pools) {
uint256 poolCount = poolIdBytes.length();
pools = new PoolStruct[](poolCount);
for (uint256 i = 0; i < poolCount;) {
PoolId poolId = PoolId.wrap(poolIdBytes.at(i));
PoolKey memory poolKey = poolIdToKey[poolId];
// Fetch token symbols via the shared helper
(string memory token0Symbol,) = _getTokenInfo(poolKey.currency0);
(string memory token1Symbol,) = _getTokenInfo(poolKey.currency1);
pools[i] = PoolStruct({
poolId: PoolId.unwrap(poolId),
poolKey: poolKey,
token0Symbol: token0Symbol,
token1Symbol: token1Symbol
});
unchecked { i++; }
}
}
}
/// @notice Helper struct to hold pool state data to reduce stack variables
struct PoolStateData {
uint160 sqrtPriceX96;
int24 currentTick;
string token0Symbol;
string token1Symbol;
uint8 token0Decimals;
uint8 token1Decimals;
uint256 token0Principal;
uint256 token0Fees;
uint256 token1Principal;
uint256 token1Fees;
}
/// @notice Detailed position information including pool and token details
/// @dev Used by getAllUserPositions to return comprehensive position data
struct DetailedUserPosition {
PoolId poolId;
bytes32 positionKey;
Currency currency0;
Currency currency1;
string token0Symbol;
string token1Symbol;
uint8 token0Decimals;
uint8 token1Decimals;
bool isToken0;
int24 bottomTick;
int24 topTick;
int24 currentTick;
int24 tickSpacing;
uint160 sqrtPrice;
uint160 sqrtPriceBottomTick;
uint160 sqrtPriceTopTick;
uint128 liquidity;
uint256 positionToken0Principal; // This position's specific token0 principal
uint256 positionToken1Principal; // This position's specific token1 principal
uint256 positionFeeRevenue0; // This position's specific token0 fees
uint256 positionFeeRevenue1; // This position's specific token1 fees
uint256 totalCurrentToken0Principal; // Total for all user positions in this pool
uint256 totalCurrentToken1Principal; // Total for all user positions in this pool
uint256 feeRevenue0; // Total fees for all user positions in this pool
uint256 feeRevenue1; // Total fees for all user positions in this pool
uint256 totalToken0AtExecution;
uint256 totalToken1AtExecution;
uint256 orderSize;
bool claimable;
}
/// @notice Basic pool information structure
struct PoolStruct {
bytes32 poolId;
PoolKey poolKey;
string token0Symbol;
string token1Symbol;
}
/// @notice Order information structure combining tick range and amount
struct OrderStruct {
int24 lowerTick;
int24 upperTick;
uint256 amount;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {Hooks} from "v4-core/libraries/Hooks.sol";
import {BaseHook} from "v4-periphery/src/utils/BaseHook.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {BalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {BeforeSwapDelta} from "v4-core/types/BeforeSwapDelta.sol";
import {SwapParams} from "v4-core/types/PoolOperation.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {TransientSlot} from "openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol";
import {ILimitOrderManager} from "../interfaces/ILimitOrderManager.sol";
import {BeforeSwapDeltaLibrary} from "v4-core/types/BeforeSwapDelta.sol";
contract LimitOrderHook is BaseHook {
using PoolIdLibrary for PoolKey;
ILimitOrderManager public immutable limitOrderManager;
address public orderBookFactory;
// Track trading enabled block per pool (1-block delay)
mapping(PoolId => uint256) public tradingEnabledBlock;
// Errors
error TradingNotYetEnabled(uint256 enabledBlock, uint256 currentBlock);
/// @notice Get pool-specific transient storage slot for previous tick
/// @dev Each pool gets unique slot to avoid collisions in multi-pool transactions
function _getPreviousTickSlot(PoolId poolId) private pure returns (bytes32) {
return keccak256(abi.encodePacked("xyz.hooks.limitorder.previous-tick", poolId));
}
constructor(
IPoolManager _poolManager,
address _limitOrderManager,
address _orderBookFactory
) BaseHook(_poolManager) {
require(_limitOrderManager != address(0), "ZeroAddress");
// OrderBookFactory can be set to address(0) for standalone deployments
limitOrderManager = ILimitOrderManager(_limitOrderManager);
orderBookFactory = _orderBookFactory;
}
function getHookPermissions() public pure override returns (Hooks.Permissions memory) {
return Hooks.Permissions({
beforeInitialize: false,
afterInitialize: true, // Enable to set trading delay on pool initialization
beforeAddLiquidity: false,
afterAddLiquidity: false,
beforeRemoveLiquidity: false,
afterRemoveLiquidity: false,
beforeSwap: true,
afterSwap: true,
beforeDonate: false,
afterDonate: false,
beforeSwapReturnDelta: false,
afterSwapReturnDelta: false,
afterAddLiquidityReturnDelta: false,
afterRemoveLiquidityReturnDelta: false
});
}
function _afterInitialize(
address,
PoolKey calldata key,
uint160,
int24
) internal override returns (bytes4) {
// Set trading enabled block (1-block delay)
tradingEnabledBlock[key.toId()] = block.number + 1;
return BaseHook.afterInitialize.selector;
}
function _beforeSwap(
address,
PoolKey calldata key,
SwapParams calldata params,
bytes calldata
) internal override returns (bytes4, BeforeSwapDelta, uint24) {
PoolId poolId = key.toId();
// Enforce 1-block delay before trading is enabled
uint256 enabledBlock = tradingEnabledBlock[poolId];
if (enabledBlock > 0) {
if (block.number < enabledBlock) {
revert TradingNotYetEnabled(enabledBlock, block.number);
}
// Delete storage slot after first successful trade to save gas on future swaps
delete tradingEnabledBlock[poolId];
}
(,int24 tickBeforeSwap,,) = StateLibrary.getSlot0(poolManager, poolId);
bytes32 slot = _getPreviousTickSlot(poolId);
assembly ("memory-safe") {
tstore(slot, tickBeforeSwap)
}
return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
}
function _afterSwap(
address,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta,
bytes calldata
) internal override returns (bytes4, int128) {
PoolId poolId = key.toId();
(,int24 tickAfterSwap,,) = StateLibrary.getSlot0(poolManager, poolId);
int24 tickBeforeSwap;
bytes32 slot = _getPreviousTickSlot(poolId);
assembly ("memory-safe") {
tickBeforeSwap := tload(slot)
}
limitOrderManager.executeOrder(key, tickBeforeSwap, tickAfterSwap, params.zeroForOne);
return (BaseHook.afterSwap.selector, 0);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {DynamicFeeLimitOrderHook} from "./DynamicFeeLimitOrderHook.sol";
/**
* @title DynamicFeeLimitOrderHookRegistry
* @notice Stores bytecode for DynamicFeeLimitOrderHook to reduce factory contract size
*/
contract DynamicFeeLimitOrderHookRegistry {
/**
* @notice Get the creation bytecode for DynamicFeeLimitOrderHook
* @return The creation bytecode
*/
function getBytecode() external pure returns (bytes memory) {
return type(DynamicFeeLimitOrderHook).creationCode;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {VolatilityDynamicFeeLimitOrderHook} from "./VolatilityDynamicFeeLimitOrderHook.sol";
/**
* @title VolatilityDynamicFeeLimitOrderHookRegistry
* @notice Stores bytecode for VolatilityDynamicFeeLimitOrderHook to reduce factory contract size
*/
contract VolatilityDynamicFeeLimitOrderHookRegistry {
/**
* @notice Get the creation bytecode for VolatilityDynamicFeeLimitOrderHook
* @return The creation bytecode
*/
function getBytecode() external pure returns (bytes memory) {
return type(VolatilityDynamicFeeLimitOrderHook).creationCode;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {PoolKey} from "v4-core/types/PoolKey.sol";
interface IDynamicFeeLimitOrderHook {
function registerPool(PoolKey calldata key) external;
function updateDynamicLPFee(PoolKey calldata key, uint24 newFee) external;
function setCommunityAddress(address _communityAddress) external;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {PoolKey} from "v4-core/types/PoolKey.sol";
interface IVolatilityDynamicFeeLimitOrderHook {
function registerPool(
PoolKey calldata key,
uint24 baseFee,
uint24 surgeMultiplier,
uint32 surgeDuration,
uint24 initialMaxTicksPerBlock
) external;
function updateFeeParams(
PoolKey calldata key,
uint24 baseFee,
uint24 surgeMultiplier,
uint32 surgeDuration,
uint24 initialMaxTicksPerBlock
) external;
function increaseCardinalityNext(PoolKey calldata key, uint32 cardinalityNext) external;
function getCurrentVolatility(PoolKey calldata key) external view returns (uint256);
function setCommunityAddress(address _communityAddress) external;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {DynamicFeeHook} from "./DynamicFeeHook.sol";
/**
* @title DynamicFeeHookRegistry
* @notice Stores bytecode for DynamicFeeHook (fee-only, no limit orders) to reduce factory contract size
*/
contract DynamicFeeHookRegistry {
/**
* @notice Get the creation bytecode for DynamicFeeHook
* @return The creation bytecode
*/
function getBytecode() external pure returns (bytes memory) {
return type(DynamicFeeHook).creationCode;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {VolatilityDynamicFeeHook} from "./VolatilityDynamicFeeHook.sol";
/**
* @title VolatilityDynamicFeeHookRegistry
* @notice Stores bytecode for VolatilityDynamicFeeHook (fee-only, no limit orders) to reduce factory contract size
*/
contract VolatilityDynamicFeeHookRegistry {
/**
* @notice Get the creation bytecode for VolatilityDynamicFeeHook
* @return The creation bytecode
*/
function getBytecode() external pure returns (bytes memory) {
return type(VolatilityDynamicFeeHook).creationCode;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {PoolKey} from "v4-core/types/PoolKey.sol";
/// @title IDynamicFeeHook
/// @notice Interface for fee-only dynamic fee hook (no limit order functionality)
interface IDynamicFeeHook {
function registerPool(PoolKey calldata key) external;
function updateDynamicLPFee(PoolKey calldata key, uint24 newFee) external;
function getDynamicLPFee(PoolKey calldata key) external view returns (uint24);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {PoolKey} from "v4-core/types/PoolKey.sol";
/// @title IVolatilityDynamicFeeHook
/// @notice Interface for volatility-based dynamic fee hook (no limit order functionality)
/// @dev Supports base fee + surge fees triggered by CAP detection, but no limit order execution
interface IVolatilityDynamicFeeHook {
function registerPool(
PoolKey calldata key,
uint24 baseFee,
uint24 surgeMultiplier,
uint32 surgeDuration,
uint24 initialMaxTicksPerBlock
) external;
function updateBaseFee(PoolKey calldata key, uint24 newBaseFee) external;
function updateSurgeParams(
PoolKey calldata key,
uint24 multiplier,
uint32 duration
) external;
function updateOraclePolicy(
PoolKey calldata key,
uint24 minCap,
uint24 maxCap,
uint32 stepPpm,
uint32 budgetPpm,
uint32 decayWindow,
uint32 updateInterval
) external;
function pauseAutoTune(PoolKey calldata key, bool paused) external;
function observe(PoolKey calldata key, uint32 secondsAgo0, uint32 secondsAgo1)
external
view
returns (int56 tickCumulative0, int56 tickCumulative1);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
/// @title HookMiner
/// @notice a minimal library for mining hook addresses
library HookMiner {
// mask to slice out the bottom 14 bit of the address
uint160 constant FLAG_MASK = Hooks.ALL_HOOK_MASK; // 0000 ... 0000 0011 1111 1111 1111
// Maximum number of iterations to find a salt, avoid infinite loops or MemoryOOG
// (arbitrarily set)
uint256 constant MAX_LOOP = 160_444;
/// @notice Find a salt that produces a hook address with the desired `flags`
/// @param deployer The address that will deploy the hook. In `forge test`, this will be the test contract `address(this)` or the pranking address
/// In `forge script`, this should be `0x4e59b44847b379578588920cA78FbF26c0B4956C` (CREATE2 Deployer Proxy)
/// @param flags The desired flags for the hook address. Example `uint160(Hooks.BEFORE_SWAP_FLAG | Hooks.AFTER_SWAP_FLAG | ...)`
/// @param creationCode The creation code of a hook contract. Example: `type(Counter).creationCode`
/// @param constructorArgs The encoded constructor arguments of a hook contract. Example: `abi.encode(address(manager))`
/// @return (hookAddress, salt) The hook deploys to `hookAddress` when using `salt` with the syntax: `new Hook{salt: salt}(<constructor arguments>)`
function find(address deployer, uint160 flags, bytes memory creationCode, bytes memory constructorArgs)
internal
view
returns (address, bytes32)
{
flags = flags & FLAG_MASK; // mask for only the bottom 14 bits
bytes memory creationCodeWithArgs = abi.encodePacked(creationCode, constructorArgs);
address hookAddress;
for (uint256 salt; salt < MAX_LOOP; salt++) {
hookAddress = computeAddress(deployer, salt, creationCodeWithArgs);
// if the hook's bottom 14 bits match the desired flags AND the address does not have bytecode, we found a match
if (uint160(hookAddress) & FLAG_MASK == flags && hookAddress.code.length == 0) {
return (hookAddress, bytes32(salt));
}
}
revert("HookMiner: could not find salt");
}
/// @notice Precompute a contract address deployed via CREATE2
/// @param deployer The address that will deploy the hook. In `forge test`, this will be the test contract `address(this)` or the pranking address
/// In `forge script`, this should be `0x4e59b44847b379578588920cA78FbF26c0B4956C` (CREATE2 Deployer Proxy)
/// @param salt The salt used to deploy the hook
/// @param creationCodeWithArgs The creation code of a hook contract, with encoded constructor arguments appended. Example: `abi.encodePacked(type(Counter).creationCode, abi.encode(constructorArg1, constructorArg2))`
function computeAddress(address deployer, uint256 salt, bytes memory creationCodeWithArgs)
internal
pure
returns (address hookAddress)
{
return address(
uint160(uint256(keccak256(abi.encodePacked(bytes1(0xFF), deployer, salt, keccak256(creationCodeWithArgs)))))
);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import {Currency} from "v4-core/types/Currency.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
/// @notice Library used to interact with PoolManager.sol to settle any open deltas.
/// @dev Note that sync() is called before any erc-20 transfer in `settle`.
library CurrencySettler {
using SafeERC20 for IERC20;
/// @notice Settle (pay) a currency to the PoolManager
/// @param currency Currency to settle
/// @param manager IPoolManager to settle to
/// @param payer Address of the payer, the token sender
/// @param amount Amount to send
/// @param burn If true, burn the ERC-6909 token, otherwise ERC20-transfer to the PoolManager
function settle(Currency currency, IPoolManager manager, address payer, uint256 amount, bool burn) internal {
if (burn) {
manager.burn(payer, currency.toId(), amount);
} else if (currency.isAddressZero()) {
manager.settle{value: amount}();
} else {
manager.sync(currency);
if (payer != address(this)) {
IERC20(Currency.unwrap(currency)).safeTransferFrom(payer, address(manager), amount);
} else {
IERC20(Currency.unwrap(currency)).safeTransfer(address(manager), amount);
}
manager.settle();
}
}
/// @notice Take (receive) a currency from the PoolManager
/// @param currency Currency to take
/// @param manager IPoolManager to take from
/// @param recipient Address of the recipient, the token receiver
/// @param amount Amount to receive
/// @param claims If true, mint the ERC-6909 token, otherwise ERC20-transfer from the PoolManager to recipient
function take(Currency currency, IPoolManager manager, address recipient, uint256 amount, bool claims) internal {
claims ? manager.mint(recipient, currency.toId(), amount) : manager.take(currency, recipient, amount);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Currency} from "../types/Currency.sol";
import {CurrencyReserves} from "./CurrencyReserves.sol";
import {NonzeroDeltaCount} from "./NonzeroDeltaCount.sol";
import {Lock} from "./Lock.sol";
/// @notice A helper library to provide state getters that use exttload
library TransientStateLibrary {
/// @notice returns the reserves for the synced currency
/// @param manager The pool manager contract.
/// @return uint256 The reserves of the currency.
/// @dev returns 0 if the reserves are not synced or value is 0.
/// Checks the synced currency to only return valid reserve values (after a sync and before a settle).
function getSyncedReserves(IPoolManager manager) internal view returns (uint256) {
if (getSyncedCurrency(manager).isAddressZero()) return 0;
return uint256(manager.exttload(CurrencyReserves.RESERVES_OF_SLOT));
}
function getSyncedCurrency(IPoolManager manager) internal view returns (Currency) {
return Currency.wrap(address(uint160(uint256(manager.exttload(CurrencyReserves.CURRENCY_SLOT)))));
}
/// @notice Returns the number of nonzero deltas open on the PoolManager that must be zeroed out before the contract is locked
function getNonzeroDeltaCount(IPoolManager manager) internal view returns (uint256) {
return uint256(manager.exttload(NonzeroDeltaCount.NONZERO_DELTA_COUNT_SLOT));
}
/// @notice Get the current delta for a caller in the given currency
/// @param target The credited account address
/// @param currency The currency for which to lookup the delta
function currencyDelta(IPoolManager manager, address target, Currency currency) internal view returns (int256) {
bytes32 key;
assembly ("memory-safe") {
mstore(0, and(target, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(32, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
key := keccak256(0, 64)
}
return int256(uint256(manager.exttload(key)));
}
/// @notice Returns whether the contract is unlocked or not
function isUnlocked(IPoolManager manager) internal view returns (bool) {
return manager.exttload(Lock.IS_UNLOCKED_SLOT) != 0x0;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {SafeCast} from "./SafeCast.sol";
import {LPFeeLibrary} from "./LPFeeLibrary.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {ParseBytes} from "./ParseBytes.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
library Hooks {
using LPFeeLibrary for uint24;
using Hooks for IHooks;
using SafeCast for int256;
using BeforeSwapDeltaLibrary for BeforeSwapDelta;
using ParseBytes for bytes;
using CustomRevert for bytes4;
uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1);
uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13;
uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12;
uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11;
uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10;
uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9;
uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8;
uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7;
uint160 internal constant AFTER_SWAP_FLAG = 1 << 6;
uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5;
uint160 internal constant AFTER_DONATE_FLAG = 1 << 4;
uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3;
uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2;
uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1;
uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0;
struct Permissions {
bool beforeInitialize;
bool afterInitialize;
bool beforeAddLiquidity;
bool afterAddLiquidity;
bool beforeRemoveLiquidity;
bool afterRemoveLiquidity;
bool beforeSwap;
bool afterSwap;
bool beforeDonate;
bool afterDonate;
bool beforeSwapReturnDelta;
bool afterSwapReturnDelta;
bool afterAddLiquidityReturnDelta;
bool afterRemoveLiquidityReturnDelta;
}
/// @notice Thrown if the address will not lead to the specified hook calls being called
/// @param hooks The address of the hooks contract
error HookAddressNotValid(address hooks);
/// @notice Hook did not return its selector
error InvalidHookResponse();
/// @notice Additional context for ERC-7751 wrapped error when a hook call fails
error HookCallFailed();
/// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa
error HookDeltaExceedsSwapAmount();
/// @notice Utility function intended to be used in hook constructors to ensure
/// the deployed hooks address causes the intended hooks to be called
/// @param permissions The hooks that are intended to be called
/// @dev permissions param is memory as the function will be called from constructors
function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure {
if (
permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG)
|| permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG)
|| permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)
|| permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)
|| permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)
|| permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
|| permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG)
|| permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG)
|| permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG)
|| permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG)
|| permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)
|| permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
|| permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
|| permissions.afterRemoveLiquidityReturnDelta
!= self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
) {
HookAddressNotValid.selector.revertWith(address(self));
}
}
/// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address
/// @param self The hook to verify
/// @param fee The fee of the pool the hook is used with
/// @return bool True if the hook address is valid
function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) {
// The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag
if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false;
if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false;
if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG))
{
return false;
}
if (
!self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
&& self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
) return false;
// If there is no hook contract set, then fee cannot be dynamic
// If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee
return address(self) == address(0)
? !fee.isDynamicFee()
: (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee());
}
/// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta
/// @return result The complete data returned by the hook
function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {
bool success;
assembly ("memory-safe") {
success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)
}
// Revert with FailedHookCall, containing any error message to bubble up
if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);
// The call was successful, fetch the returned data
assembly ("memory-safe") {
// allocate result byte array from the free memory pointer
result := mload(0x40)
// store new free memory pointer at the end of the array padded to 32 bytes
mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
// store length in memory
mstore(result, returndatasize())
// copy return data to result
returndatacopy(add(result, 0x20), 0, returndatasize())
}
// Length must be at least 32 to contain the selector. Check expected selector and returned selector match.
if (result.length < 32 || result.parseSelector() != data.parseSelector()) {
InvalidHookResponse.selector.revertWith();
}
}
/// @notice performs a hook call using the given calldata on the given hook
/// @return int256 The delta returned by the hook
function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) {
bytes memory result = callHook(self, data);
// If this hook wasn't meant to return something, default to 0 delta
if (!parseReturn) return 0;
// A length of 64 bytes is required to return a bytes4, and a 32 byte delta
if (result.length != 64) InvalidHookResponse.selector.revertWith();
return result.parseReturnDelta();
}
/// @notice modifier to prevent calling a hook if they initiated the action
modifier noSelfCall(IHooks self) {
if (msg.sender != address(self)) {
_;
}
}
/// @notice calls beforeInitialize hook if permissioned and validates return value
function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) {
if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96)));
}
}
/// @notice calls afterInitialize hook if permissioned and validates return value
function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick)
internal
noSelfCall(self)
{
if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick)));
}
}
/// @notice calls beforeModifyLiquidity hook if permissioned and validates return value
function beforeModifyLiquidity(
IHooks self,
PoolKey memory key,
ModifyLiquidityParams memory params,
bytes calldata hookData
) internal noSelfCall(self) {
if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData)));
} else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData)));
}
}
/// @notice calls afterModifyLiquidity hook if permissioned and validates return value
function afterModifyLiquidity(
IHooks self,
PoolKey memory key,
ModifyLiquidityParams memory params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {
if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA);
callerDelta = delta;
if (params.liquidityDelta > 0) {
if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) {
hookDelta = BalanceDelta.wrap(
self.callHookWithReturnDelta(
abi.encodeCall(
IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
),
self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
)
);
callerDelta = callerDelta - hookDelta;
}
} else {
if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) {
hookDelta = BalanceDelta.wrap(
self.callHookWithReturnDelta(
abi.encodeCall(
IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
),
self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
)
);
callerDelta = callerDelta - hookDelta;
}
}
}
/// @notice calls beforeSwap hook if permissioned and validates return value
function beforeSwap(IHooks self, PoolKey memory key, SwapParams memory params, bytes calldata hookData)
internal
returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride)
{
amountToSwap = params.amountSpecified;
if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);
if (self.hasPermission(BEFORE_SWAP_FLAG)) {
bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData)));
// A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee
if (result.length != 96) InvalidHookResponse.selector.revertWith();
// dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag
// is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used
if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();
// skip this logic for the case where the hook return is 0
if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {
hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());
// any return in unspecified is passed to the afterSwap hook for handling
int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();
// Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)
if (hookDeltaSpecified != 0) {
bool exactInput = amountToSwap < 0;
amountToSwap += hookDeltaSpecified;
if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {
HookDeltaExceedsSwapAmount.selector.revertWith();
}
}
}
}
}
/// @notice calls afterSwap hook if permissioned and validates return value
function afterSwap(
IHooks self,
PoolKey memory key,
SwapParams memory params,
BalanceDelta swapDelta,
bytes calldata hookData,
BeforeSwapDelta beforeSwapHookReturn
) internal returns (BalanceDelta, BalanceDelta) {
if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA);
int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta();
int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta();
if (self.hasPermission(AFTER_SWAP_FLAG)) {
hookDeltaUnspecified += self.callHookWithReturnDelta(
abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)),
self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
).toInt128();
}
BalanceDelta hookDelta;
if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
hookDelta = (params.amountSpecified < 0 == params.zeroForOne)
? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
: toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);
// the caller has to pay for (or receive) the hook's delta
swapDelta = swapDelta - hookDelta;
}
return (swapDelta, hookDelta);
}
/// @notice calls beforeDonate hook if permissioned and validates return value
function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
internal
noSelfCall(self)
{
if (self.hasPermission(BEFORE_DONATE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
/// @notice calls afterDonate hook if permissioned and validates return value
function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
internal
noSelfCall(self)
{
if (self.hasPermission(AFTER_DONATE_FLAG)) {
self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));
}
}
function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {
return uint160(address(self)) & flag != 0;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolId} from "../types/PoolId.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Position} from "./Position.sol";
/// @notice A helper library to provide state getters that use extsload
library StateLibrary {
/// @notice index of pools mapping in the PoolManager
bytes32 public constant POOLS_SLOT = bytes32(uint256(6));
/// @notice index of feeGrowthGlobal0X128 in Pool.State
uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;
// feeGrowthGlobal1X128 offset in Pool.State = 2
/// @notice index of liquidity in Pool.State
uint256 public constant LIQUIDITY_OFFSET = 3;
/// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;
uint256 public constant TICKS_OFFSET = 4;
/// @notice index of tickBitmap mapping in Pool.State
uint256 public constant TICK_BITMAP_OFFSET = 5;
/// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;
uint256 public constant POSITIONS_OFFSET = 6;
/**
* @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee
* @dev Corresponds to pools[poolId].slot0
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.
* @return tick The current tick of the pool.
* @return protocolFee The protocol fee of the pool.
* @return lpFee The swap fee of the pool.
*/
function getSlot0(IPoolManager manager, PoolId poolId)
internal
view
returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
bytes32 data = manager.extsload(stateSlot);
// 24 bits |24bits|24bits |24 bits|160 bits
// 0x000000 |000bb8|000000 |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7
// ---------- | fee |protocolfee | tick | sqrtPriceX96
assembly ("memory-safe") {
// bottom 160 bits of data
sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
// next 24 bits of data
tick := signextend(2, shr(160, data))
// next 24 bits of data
protocolFee := and(shr(184, data), 0xFFFFFF)
// last 24 bits of data
lpFee := and(shr(208, data), 0xFFFFFF)
}
}
/**
* @notice Retrieves the tick information of a pool at a specific tick.
* @dev Corresponds to pools[poolId].ticks[tick]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve information for.
* @return liquidityGross The total position liquidity that references this tick
* @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
* @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
* @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
*/
function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128
)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
// read all 3 words of the TickInfo struct
bytes32[] memory data = manager.extsload(slot, 3);
assembly ("memory-safe") {
let firstWord := mload(add(data, 32))
liquidityNet := sar(128, firstWord)
liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
feeGrowthOutside0X128 := mload(add(data, 64))
feeGrowthOutside1X128 := mload(add(data, 96))
}
}
/**
* @notice Retrieves the liquidity information of a pool at a specific tick.
* @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve liquidity for.
* @return liquidityGross The total position liquidity that references this tick
* @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
*/
function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (uint128 liquidityGross, int128 liquidityNet)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
bytes32 value = manager.extsload(slot);
assembly ("memory-safe") {
liquidityNet := sar(128, value)
liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
}
/**
* @notice Retrieves the fee growth outside a tick range of a pool
* @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve fee growth for.
* @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
* @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
*/
function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)
internal
view
returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)
{
bytes32 slot = _getTickInfoSlot(poolId, tick);
// offset by 1 word, since the first word is liquidityGross + liquidityNet
bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);
assembly ("memory-safe") {
feeGrowthOutside0X128 := mload(add(data, 32))
feeGrowthOutside1X128 := mload(add(data, 64))
}
}
/**
* @notice Retrieves the global fee growth of a pool.
* @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return feeGrowthGlobal0 The global fee growth for token0.
* @return feeGrowthGlobal1 The global fee growth for token1.
* @dev Note that feeGrowthGlobal can be artificially inflated
* For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal
* atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
*/
function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)
internal
view
returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State, `uint256 feeGrowthGlobal0X128`
bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);
// read the 2 words of feeGrowthGlobal
bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);
assembly ("memory-safe") {
feeGrowthGlobal0 := mload(add(data, 32))
feeGrowthGlobal1 := mload(add(data, 64))
}
}
/**
* @notice Retrieves total the liquidity of a pool.
* @dev Corresponds to pools[poolId].liquidity
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @return liquidity The liquidity of the pool.
*/
function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `uint128 liquidity`
bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);
liquidity = uint128(uint256(manager.extsload(slot)));
}
/**
* @notice Retrieves the tick bitmap of a pool at a specific tick.
* @dev Corresponds to pools[poolId].tickBitmap[tick]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tick The tick to retrieve the bitmap for.
* @return tickBitmap The bitmap of the tick.
*/
function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)
internal
view
returns (uint256 tickBitmap)
{
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(int16 => uint256) tickBitmap;`
bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);
// slot id of the mapping key: `pools[poolId].tickBitmap[tick]
bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));
tickBitmap = uint256(manager.extsload(slot));
}
/**
* @notice Retrieves the position information of a pool without needing to calculate the `positionId`.
* @dev Corresponds to pools[poolId].positions[positionId]
* @param poolId The ID of the pool.
* @param owner The owner of the liquidity position.
* @param tickLower The lower tick of the liquidity range.
* @param tickUpper The upper tick of the liquidity range.
* @param salt The bytes32 randomness to further distinguish position state.
* @return liquidity The liquidity of the position.
* @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
* @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
*/
function getPositionInfo(
IPoolManager manager,
PoolId poolId,
address owner,
int24 tickLower,
int24 tickUpper,
bytes32 salt
) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {
// positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);
(liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);
}
/**
* @notice Retrieves the position information of a pool at a specific position ID.
* @dev Corresponds to pools[poolId].positions[positionId]
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param positionId The ID of the position.
* @return liquidity The liquidity of the position.
* @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
* @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
*/
function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)
internal
view
returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)
{
bytes32 slot = _getPositionInfoSlot(poolId, positionId);
// read all 3 words of the Position.State struct
bytes32[] memory data = manager.extsload(slot, 3);
assembly ("memory-safe") {
liquidity := mload(add(data, 32))
feeGrowthInside0LastX128 := mload(add(data, 64))
feeGrowthInside1LastX128 := mload(add(data, 96))
}
}
/**
* @notice Retrieves the liquidity of a position.
* @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param positionId The ID of the position.
* @return liquidity The liquidity of the position.
*/
function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)
internal
view
returns (uint128 liquidity)
{
bytes32 slot = _getPositionInfoSlot(poolId, positionId);
liquidity = uint128(uint256(manager.extsload(slot)));
}
/**
* @notice Calculate the fee growth inside a tick range of a pool
* @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside
* @param manager The pool manager contract.
* @param poolId The ID of the pool.
* @param tickLower The lower tick of the range.
* @param tickUpper The upper tick of the range.
* @return feeGrowthInside0X128 The fee growth inside the tick range for token0.
* @return feeGrowthInside1X128 The fee growth inside the tick range for token1.
*/
function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)
internal
view
returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)
{
(uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);
(uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =
getTickFeeGrowthOutside(manager, poolId, tickLower);
(uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =
getTickFeeGrowthOutside(manager, poolId, tickUpper);
(, int24 tickCurrent,,) = getSlot0(manager, poolId);
unchecked {
if (tickCurrent < tickLower) {
feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
} else if (tickCurrent >= tickUpper) {
feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;
feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;
} else {
feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
}
}
}
function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));
}
function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(int24 => TickInfo) ticks`
bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);
// slot key of the tick key: `pools[poolId].ticks[tick]
return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));
}
function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {
// slot key of Pool.State value: `pools[poolId]`
bytes32 stateSlot = _getPoolStateSlot(poolId);
// Pool.State: `mapping(bytes32 => Position.State) positions;`
bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);
// slot of the mapping key: `pools[poolId].positions[positionId]
return keccak256(abi.encodePacked(positionId, positionMapping));
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IMultiPositionFactory} from "./interfaces/IMultiPositionFactory.sol";
import {IMultiPositionManager} from "./interfaces/IMultiPositionManager.sol";
import {MultiPositionDeployer} from "./MultiPositionDeployer.sol";
import {MultiPositionManager} from "./MultiPositionManager.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {RebalanceLogic} from "./libraries/RebalanceLogic.sol";
import {Multicall} from "./base/Multicall.sol";
contract MultiPositionFactory is IMultiPositionFactory, Ownable, Multicall {
using PoolIdLibrary for PoolKey;
using StateLibrary for IPoolManager;
// Role constants
bytes32 public constant override CLAIM_MANAGER = keccak256("CLAIM_MANAGER");
bytes32 public constant FEE_MANAGER = keccak256("FEE_MANAGER");
// Role storage
mapping(bytes32 => mapping(address => bool)) private _roles;
// Deployed managers tracking
mapping(address => ManagerInfo) public managers;
// Track managers by owner
mapping(address => address[]) public managersByOwner;
// Track all managers for pagination
address[] private allManagers;
// Track used names to prevent duplicates
mapping(string => bool) public usedNames;
// Track managers by token pair (key = keccak256(currency0, currency1))
mapping(bytes32 => address[]) private _managersByTokenPair;
// Track all unique token pairs
TokenPairInfo[] private _allTokenPairs;
// Track if a token pair has been seen (key = keccak256(currency0, currency1))
mapping(bytes32 => bool) private _tokenPairExists;
// Protocol fee recipient
address public feeRecipient;
// Protocol fee (denominator for fee calculation, e.g., 10 = 10%, 20 = 5%)
uint16 public protocolFee = 20;
// Pool manager for all deployments
IPoolManager public immutable poolManager;
// Deployer contract for MultiPositionManager
MultiPositionDeployer public immutable deployer;
// Custom errors
error UnauthorizedAccess();
error ManagerAlreadyExists();
error InvalidAddress();
error InitializationFailed();
error InvalidFee();
error InsufficientMsgValue();
error NameAlreadyUsed(string name);
error PoolNotInitialized();
error InvalidSqrtPriceX96();
constructor(address _owner, IPoolManager _poolManager) Ownable(_owner) {
if (_owner == address(0)) revert InvalidAddress();
if (address(_poolManager) == address(0)) revert InvalidAddress();
feeRecipient = _owner; // Initialize fee recipient to owner
poolManager = _poolManager;
deployer = new MultiPositionDeployer();
}
/**
* @notice Checks if an account has a specific role or is the owner
* @param role The role to check
* @param account The account to check
* @return True if the account has the role or is the owner
*/
function hasRoleOrOwner(bytes32 role, address account) external view override returns (bool) {
return account == owner() || _roles[role][account];
}
/**
* @notice Checks if an account has a specific role
* @param role The role to check
* @param account The account to check
* @return True if the account has the role
*/
function hasRole(bytes32 role, address account) external view override returns (bool) {
return _roles[role][account];
}
/**
* @notice Grants a role to an account
* @param role The role to grant
* @param account The account to grant the role to
*/
function grantRole(bytes32 role, address account) external override onlyOwner {
if (account == address(0)) revert InvalidAddress();
if (!_roles[role][account]) {
_roles[role][account] = true;
emit RoleGranted(role, account, msg.sender);
}
}
/**
* @notice Revokes a role from an account
* @param role The role to revoke
* @param account The account to revoke the role from
*/
function revokeRole(bytes32 role, address account) external override onlyOwner {
if (_roles[role][account]) {
_roles[role][account] = false;
emit RoleRevoked(role, account, msg.sender);
}
}
/**
* @notice Deploys a new MultiPositionManager
* @param poolKey The pool key for the Uniswap V4 pool
* @param managerOwner The owner of the new MultiPositionManager
* @param name The name for the LP token
* @return The address of the deployed MultiPositionManager
*/
function deployMultiPositionManager(PoolKey memory poolKey, address managerOwner, string memory name)
external
returns (address)
{
if (managerOwner == address(0)) revert InvalidAddress();
// Check if name is already used
if (usedNames[name]) revert NameAlreadyUsed(name);
// Generate deterministic salt for CREATE2
// Include name to ensure unique deployments for same poolKey/owner with different names
bytes32 salt = keccak256(abi.encode(poolKey, managerOwner, name));
// Use fixed symbol for all deployments
string memory symbol = "GAMMA-LP";
// Deploy using deployer contract
address managerAddress = deployer.deploy(
poolManager,
poolKey,
managerOwner,
address(this), // factory address
name,
symbol,
protocolFee,
salt
);
// Mark name as used
usedNames[name] = true;
// Store manager info in mapping
managers[managerAddress] =
ManagerInfo({managerAddress: managerAddress, managerOwner: managerOwner, poolKey: poolKey, name: name});
// Track manager by owner
managersByOwner[managerOwner].push(managerAddress);
// Track in global list
allManagers.push(managerAddress);
// Track by token pair
address currency0 = Currency.unwrap(poolKey.currency0);
address currency1 = Currency.unwrap(poolKey.currency1);
bytes32 pairKey = keccak256(abi.encodePacked(currency0, currency1));
_managersByTokenPair[pairKey].push(managerAddress);
// Track unique token pair if new
if (!_tokenPairExists[pairKey]) {
_tokenPairExists[pairKey] = true;
_allTokenPairs.push(TokenPairInfo({currency0: currency0, currency1: currency1, managerCount: 1}));
} else {
// Increment count for existing pair
for (uint256 i = 0; i < _allTokenPairs.length; i++) {
if (_allTokenPairs[i].currency0 == currency0 && _allTokenPairs[i].currency1 == currency1) {
_allTokenPairs[i].managerCount++;
break;
}
}
}
emit MultiPositionManagerDeployed(managerAddress, managerOwner, poolKey);
return managerAddress;
}
/**
* @notice Atomically deploys MPM, deposits liquidity, and rebalances to strategy
* @param poolKey The pool key for the Uniswap V4 pool
* @param managerOwner The owner of the new MultiPositionManager (also receives LP shares)
* @param name The name for the LP token
* @param deposit0Desired Amount of token0 to deposit
* @param deposit1Desired Amount of token1 to deposit
* @param inMin Minimum amounts for slippage protection
* @param rebalanceParams Strategy and rebalance parameters
* @return mpm The address of the deployed and initialized MultiPositionManager
* @dev LP shares are always minted to managerOwner
*/
function deployDepositAndRebalance(
PoolKey memory poolKey,
address managerOwner,
string memory name,
uint256 deposit0Desired,
uint256 deposit1Desired,
address to,
uint256[2][] memory inMin,
IMultiPositionManager.RebalanceParams memory rebalanceParams
) external payable returns (address mpm) {
// Input validation
if (managerOwner == address(0)) revert InvalidAddress();
if (to == address(0)) revert InvalidAddress();
// Deploy MPM (call external function using 'this')
mpm = this.deployMultiPositionManager(poolKey, managerOwner, name);
// Deposit liquidity (Factory can call because it's s.factory in MPM)
// Tokens pulled from msg.sender (user), shares minted to 'to'
MultiPositionManager(payable(mpm)).deposit{value: msg.value}(
deposit0Desired,
deposit1Desired,
to,
msg.sender // from = msg.sender (the user calling this function)
);
// Rebalance to strategy (Factory can call because it's s.factory in MPM)
MultiPositionManager(payable(mpm)).rebalance(
rebalanceParams,
new uint256[2][](0), // outMin - empty for initial rebalance
inMin // inMin from deposit
);
return mpm;
}
/**
* @notice Deploy MPM, deposit, and rebalance with swap in one atomic transaction
* @dev Enables single-token deposits by swapping to achieve strategy's target ratio
* @param poolKey The pool key for the Uniswap V4 pool
* @param managerOwner The owner of the new MultiPositionManager (also receives LP shares)
* @param name The name of the LP token
* @param deposit0Desired Amount of token0 to deposit (can be 0)
* @param deposit1Desired Amount of token1 to deposit (can be 0)
* @param swapParams Complete swap parameters (aggregator, calldata, amounts, etc.)
* @param inMin Minimum amounts for each position (slippage protection)
* @param rebalanceParams Rebalance parameters (strategy, center, ticks, weights, etc.)
* @return mpm Address of the deployed MultiPositionManager
* @dev LP shares are always minted to managerOwner
*/
function deployDepositAndRebalanceSwap(
PoolKey memory poolKey,
address managerOwner,
string memory name,
uint256 deposit0Desired,
uint256 deposit1Desired,
address to,
RebalanceLogic.SwapParams calldata swapParams,
uint256[2][] memory inMin,
IMultiPositionManager.RebalanceParams memory rebalanceParams
) external payable returns (address mpm) {
// Input validation
if (managerOwner == address(0)) revert InvalidAddress();
if (to == address(0)) revert InvalidAddress();
if (swapParams.aggregatorAddress == address(0)) revert InvalidAddress();
// Deploy MPM (call external function using 'this')
mpm = this.deployMultiPositionManager(poolKey, managerOwner, name);
// Deposit liquidity (tokens will sit idle in MPM, no positions yet)
// Tokens pulled from msg.sender (user), shares minted to 'to'
MultiPositionManager(payable(mpm)).deposit{value: msg.value}(
deposit0Desired,
deposit1Desired,
to,
msg.sender // from = msg.sender (the user calling this function)
);
// RebalanceSwap: swaps to target ratio + creates positions
MultiPositionManager(payable(mpm)).rebalanceSwap(
IMultiPositionManager.RebalanceSwapParams({rebalanceParams: rebalanceParams, swapParams: swapParams}),
new uint256[2][](0), // outMin empty (no positions to burn)
inMin // inMin for new positions after swap
);
return mpm;
}
/**
* @notice Computes the address where a MultiPositionManager will be deployed
* @param poolKey The pool key for the Uniswap V4 pool
* @param managerOwner The owner of the new MultiPositionManager
* @param name The name of the LP token
* @return The address where the MultiPositionManager will be deployed
*/
function computeAddress(PoolKey memory poolKey, address managerOwner, string memory name)
external
view
returns (address)
{
// Use fixed symbol for all deployments
string memory symbol = "GAMMA-LP";
// Use the same salt calculation as deployMultiPositionManager
// Include name to ensure unique deployments for same poolKey/owner with different names
bytes32 salt = keccak256(abi.encode(poolKey, managerOwner, name));
// Delegate to deployer which has access to the bytecode
return
deployer.computeAddress(poolManager, poolKey, managerOwner, address(this), name, symbol, protocolFee, salt);
}
/**
* @notice Gets all managers owned by a specific address
* @param managerOwner The owner address to query
* @return Array of ManagerInfo for all managers owned by the address
*/
function getManagersByOwner(address managerOwner) external view returns (ManagerInfo[] memory) {
address[] memory ownerManagers = managersByOwner[managerOwner];
ManagerInfo[] memory result = new ManagerInfo[](ownerManagers.length);
for (uint256 i = 0; i < ownerManagers.length; i++) {
address managerAddress = ownerManagers[i];
result[i] = managers[managerAddress];
result[i].managerAddress = managerAddress;
}
return result;
}
/**
* @notice Get all deployed managers with pagination
* @param offset Starting index in the global manager list
* @param limit Maximum number of managers to return (0 for all remaining)
* @return managersInfo Array of ManagerInfo structs
* @return totalCount Total number of deployed managers
*/
function getAllManagersPaginated(uint256 offset, uint256 limit)
external
view
returns (ManagerInfo[] memory managersInfo, uint256 totalCount)
{
totalCount = allManagers.length;
if (limit == 0) {
limit = totalCount; // 0 means return all managers
}
if (offset >= totalCount) {
return (new ManagerInfo[](0), totalCount);
}
uint256 count = (offset + limit > totalCount) ? (totalCount - offset) : limit;
managersInfo = new ManagerInfo[](count);
for (uint256 i = 0; i < count; i++) {
address managerAddress = allManagers[offset + i];
managersInfo[i] = managers[managerAddress];
managersInfo[i].managerAddress = managerAddress;
}
return (managersInfo, totalCount);
}
/**
* @notice Get the total number of deployed managers
* @return The total count of deployed managers
*/
function getTotalManagersCount() external view returns (uint256) {
return allManagers.length;
}
/**
* @notice Checks if a pool has been initialized in the PoolManager
* @param poolKey The pool key to check
* @return initialized True if the pool has been initialized (sqrtPriceX96 != 0)
*/
function isPoolInitialized(PoolKey memory poolKey) public view returns (bool initialized) {
PoolId poolId = poolKey.toId();
(uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolId);
return sqrtPriceX96 != 0;
}
/**
* @notice Initializes a pool if it hasn't been initialized yet
* @param poolKey The pool key to initialize
* @param sqrtPriceX96 The initial sqrt price (Q64.96 format)
* @return tick The initial tick of the pool
* @dev Reverts if sqrtPriceX96 is 0 or if pool is already initialized
* Marked payable for multicall compatibility - msg.value persists across delegatecalls.
* Does not consume msg.value; it just needs to accept it to prevent multicall reverts.
*/
function initializePoolIfNeeded(PoolKey memory poolKey, uint160 sqrtPriceX96)
external
payable
returns (int24 tick)
{
if (sqrtPriceX96 == 0) revert InvalidSqrtPriceX96();
if (!isPoolInitialized(poolKey)) {
tick = poolManager.initialize(poolKey, sqrtPriceX96);
} else {
// Pool already initialized, return current tick
PoolId poolId = poolKey.toId();
(, tick,,) = poolManager.getSlot0(poolId);
}
}
/**
* @notice Sets the protocol fee recipient
* @param _feeRecipient The new fee recipient address
*/
function setFeeRecipient(address _feeRecipient) external onlyOwner {
if (_feeRecipient == address(0)) revert InvalidAddress();
feeRecipient = _feeRecipient;
}
/**
* @notice Sets the protocol fee for all new deployments
* @param _fee The new protocol fee denominator (e.g., 10 = 10%)
*/
function setProtocolFee(uint16 _fee) external onlyOwner {
if (_fee == 0) revert InvalidFee();
protocolFee = _fee;
}
/**
* @notice Get all unique token pairs with pagination
* @param offset Starting index in the token pairs list
* @param limit Maximum number of pairs to return (0 for all remaining)
* @return pairsInfo Array of TokenPairInfo structs with currency addresses and manager counts
* @return totalCount Total number of unique token pairs
*/
function getAllTokenPairsPaginated(uint256 offset, uint256 limit)
external
view
returns (TokenPairInfo[] memory pairsInfo, uint256 totalCount)
{
totalCount = _allTokenPairs.length;
if (limit == 0) {
limit = totalCount;
}
if (offset >= totalCount) {
return (new TokenPairInfo[](0), totalCount);
}
uint256 count = (offset + limit > totalCount) ? (totalCount - offset) : limit;
pairsInfo = new TokenPairInfo[](count);
for (uint256 i = 0; i < count; i++) {
pairsInfo[i] = _allTokenPairs[offset + i];
}
return (pairsInfo, totalCount);
}
/**
* @notice Get all managers for a specific token pair with pagination
* @param currency0 The first currency address (token0)
* @param currency1 The second currency address (token1)
* @param offset Starting index in the managers list for this pair
* @param limit Maximum number of managers to return (0 for all remaining)
* @return managersInfo Array of ManagerInfo structs
* @return totalCount Total number of managers for this token pair
*/
function getAllManagersByTokenPair(address currency0, address currency1, uint256 offset, uint256 limit)
external
view
returns (ManagerInfo[] memory managersInfo, uint256 totalCount)
{
bytes32 pairKey = keccak256(abi.encodePacked(currency0, currency1));
address[] storage pairManagers = _managersByTokenPair[pairKey];
totalCount = pairManagers.length;
if (limit == 0) {
limit = totalCount;
}
if (offset >= totalCount) {
return (new ManagerInfo[](0), totalCount);
}
uint256 count = (offset + limit > totalCount) ? (totalCount - offset) : limit;
managersInfo = new ManagerInfo[](count);
for (uint256 i = 0; i < count; i++) {
address managerAddress = pairManagers[offset + i];
managersInfo[i] = managers[managerAddress];
managersInfo[i].managerAddress = managerAddress;
}
return (managersInfo, totalCount);
}
}/// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {IImmutableState} from "v4-periphery/src/interfaces/IImmutableState.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {RebalanceLogic} from "../libraries/RebalanceLogic.sol";
interface IMultiPositionManager is IERC20, IImmutableState {
enum Action {
WITHDRAW,
REBALANCE,
ZERO_BURN,
CLAIM_FEE,
BURN_ALL,
COMPOUND
}
struct Range {
int24 lowerTick;
int24 upperTick;
}
// @deprecated Use Range instead - Position included redundant poolKey
struct Position {
PoolKey poolKey;
int24 lowerTick;
int24 upperTick;
}
struct PositionData {
uint128 liquidity;
uint256 amount0;
uint256 amount1;
}
struct RebalanceParams {
address strategy;
int24 center;
uint24 tLeft;
uint24 tRight;
uint24 limitWidth;
uint256 weight0;
uint256 weight1;
bool useCarpet;
}
struct RebalanceSwapParams {
RebalanceParams rebalanceParams;
RebalanceLogic.SwapParams swapParams;
}
event Rebalance(Range[] ranges, PositionData[] positionData, RebalanceParams params);
event Deposit(address indexed from, address indexed to, uint256 amount0, uint256 amount1, uint256 shares);
function getPositions() external view returns (Range[] memory, PositionData[] memory);
function getBasePositions() external view returns (Range[] memory, PositionData[] memory);
function poolKey() external view returns (PoolKey memory);
function fee() external view returns (uint16);
function factory() external view returns (address);
function basePositionsLength() external view returns (uint256);
function limitPositionsLength() external view returns (uint256);
function limitPositions(uint256 index) external view returns (Range memory);
function getTotalAmounts()
external
view
returns (uint256 total0, uint256 total1, uint256 totalFee0, uint256 totalFee1);
function currentTick() external view returns (int24);
function rebalance(RebalanceParams calldata params, uint256[2][] memory outMin, uint256[2][] memory inMin)
external
payable;
function rebalanceSwap(RebalanceSwapParams calldata params, uint256[2][] memory outMin, uint256[2][] memory inMin)
external
payable;
function claimFee() external;
function setFee(uint16 fee) external;
// function setTickOffset(uint24 offset) external;
function deposit(uint256 deposit0Desired, uint256 deposit1Desired, address to, address from)
external
payable
returns (uint256, uint256, uint256);
function compound(uint256[2][] calldata inMin) external payable;
function compoundSwap(RebalanceLogic.SwapParams calldata swapParams, uint256[2][] calldata inMin)
external
payable;
function withdraw(uint256 shares, uint256[2][] memory outMin, bool withdrawToWallet)
external
returns (uint256 amount0, uint256 amount1);
function withdrawCustom(uint256 amount0Desired, uint256 amount1Desired, uint256[2][] memory outMin)
external
returns (uint256 amount0Out, uint256 amount1Out, uint256 sharesBurned);
// Role management functions
function grantRelayerRole(address account) external;
function revokeRelayerRole(address account) external;
function isRelayer(address account) external view returns (bool);
// Ratio functions
function getRatios()
external
view
returns (
uint256 pool0Ratio,
uint256 pool1Ratio,
uint256 total0Ratio,
uint256 total1Ratio,
uint256 inPositionRatio,
uint256 outOfPositionRatio,
uint256 baseRatio,
uint256 limitRatio,
uint256 base0Ratio,
uint256 base1Ratio,
uint256 limit0Ratio,
uint256 limit1Ratio
);
// Strategy parameters
function lastStrategyParams()
external
view
returns (
address strategy,
int24 centerTick,
uint24 ticksLeft,
uint24 ticksRight,
uint24 limitWidth,
uint120 weight0,
uint120 weight1,
bool useCarpet,
bool useSwap,
bool useAssetWeights
);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {FixedPoint96} from "v4-core/libraries/FixedPoint96.sol";
import {LiquidityAmounts} from "v4-periphery/lib/v4-core/test/utils/LiquidityAmounts.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.sol";
import {ILiquidityStrategy} from "../strategies/ILiquidityStrategy.sol";
import {SharedStructs} from "../base/SharedStructs.sol";
import {PoolManagerUtils} from "./PoolManagerUtils.sol";
import {PositionLogic} from "./PositionLogic.sol";
/**
* @title RebalanceLogic
* @notice Library containing all rebalance-related logic for MultiPositionManager
*/
library RebalanceLogic {
using PoolIdLibrary for PoolKey;
using StateLibrary for IPoolManager;
using SafeERC20 for IERC20;
uint256 constant PRECISION = 1e18;
// Custom errors
error OutMinLengthMismatch();
error InvalidWeightSum();
error NoStrategySpecified();
error CarpetRequiresBothTokens();
error InsufficientLiquidityForCarpet();
error InvalidTickRange();
error DuplicatedRange(IMultiPositionManager.Range range);
error InvalidAggregator();
error InMinLengthMismatch(uint256 provided, uint256 required);
error InsufficientTokensForSwap();
error InsufficientOutput();
// Events
event SwapExecuted(address indexed aggregator, uint256 amountIn, uint256 amountOut, bool swapToken0);
struct StrategyContext {
address resolvedStrategy;
int24 center;
uint24 tLeft;
uint24 tRight;
ILiquidityStrategy strategy;
uint256 weight0;
uint256 weight1;
bool useCarpet;
uint24 limitWidth;
bool useAssetWeights;
}
struct DensityParams {
int24[] lowerTicks;
int24[] upperTicks;
int24 tick;
int24 center;
uint24 tLeft;
uint24 tRight;
uint256 weight0;
uint256 weight1;
bool useCarpet;
int24 tickSpacing;
}
struct WeightCalculationParams {
ILiquidityStrategy strategy;
int24 center;
uint24 tLeft;
uint24 tRight;
int24 tickSpacing;
bool useCarpet;
uint160 sqrtPriceX96;
int24 currentTick;
}
/// @notice Supported swap aggregators
enum Aggregator {
ZERO_X, // 0
KYBERSWAP, // 1
ODOS, // 2
PARASWAP // 3
}
/// @notice Parameters for executing a swap through an aggregator
struct SwapParams {
Aggregator aggregator; // Which aggregator to use
address aggregatorAddress; // Aggregator router address
bytes swapData; // Complete encoded function call from JavaScript
bool swapToken0; // Direction: true = swap token0 for token1
uint256 swapAmount; // Amount being swapped (for validation)
uint256 minAmountOut; // Minimum output amount (slippage protection)
}
/**
* @notice Main rebalance function
* @param s Storage struct
* @param poolManager Pool manager contract
* @param params Rebalance parameters
* @param outMin Minimum output amounts for withdrawals
* @param inMin Minimum input amounts for new positions (slippage protection)
* @return baseRanges The base ranges to rebalance to
* @return liquidities The liquidity amounts for each range
* @return limitWidth The limit width for limit positions
*/
function rebalance(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
IMultiPositionManager.RebalanceParams calldata params,
uint256[2][] memory outMin,
uint256[2][] memory inMin
)
external
returns (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities, uint24 limitWidth)
{
if (outMin.length != s.basePositionsLength + s.limitPositionsLength) {
revert OutMinLengthMismatch();
}
// Process in helper to avoid stack issues
return _processRebalance(s, poolManager, params, outMin, inMin);
}
function _processRebalance(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
IMultiPositionManager.RebalanceParams memory params,
uint256[2][] memory outMin,
uint256[2][] memory inMin
)
internal
returns (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities, uint24 limitWidth)
{
// Bundle strategy parameters in a struct to reduce stack depth
StrategyContext memory ctx;
ctx.weight0 = params.weight0;
ctx.weight1 = params.weight1;
ctx.useAssetWeights = (ctx.weight0 == 0 && ctx.weight1 == 0);
if (ctx.useAssetWeights) {
(uint256 available0, uint256 available1) = _getTotalAvailable(s, poolManager);
(uint160 sqrtPriceX96,,,) = poolManager.getSlot0(s.poolKey.toId());
(ctx.weight0, ctx.weight1) = calculateWeightsFromAmounts(available0, available1, sqrtPriceX96);
}
if (ctx.weight0 + ctx.weight1 != 1e18) revert InvalidWeightSum();
// Resolve strategy parameters
ctx.resolvedStrategy = params.strategy != address(0) ? params.strategy : s.lastStrategyParams.strategy;
if (params.center == type(int24).max) {
(, int24 currentTick,,) = poolManager.getSlot0(s.poolKey.toId());
// Always round down to ensure the range contains the current tick
int24 compressed = currentTick / s.poolKey.tickSpacing;
if (currentTick < 0 && currentTick % s.poolKey.tickSpacing != 0) {
compressed--; // Round down for negative ticks with remainder
}
ctx.center = compressed * s.poolKey.tickSpacing;
} else {
ctx.center = params.center;
}
ctx.tLeft = params.tLeft;
ctx.tRight = params.tRight;
ctx.useCarpet = params.useCarpet;
// In proportional mode (weights 0,0), force limitWidth to 0
// Limit positions don't make sense when weights are derived from amounts
if (params.weight0 == 0 && params.weight1 == 0) {
ctx.limitWidth = 0;
} else {
ctx.limitWidth = params.limitWidth;
}
// Get strategy interface
if (ctx.resolvedStrategy == address(0)) revert NoStrategySpecified();
ctx.strategy = ILiquidityStrategy(ctx.resolvedStrategy);
// Generate ranges
(int24[] memory lowerTicks, int24[] memory upperTicks) =
ctx.strategy.generateRanges(ctx.center, ctx.tLeft, ctx.tRight, s.poolKey.tickSpacing, ctx.useCarpet);
// Convert to Range array
uint256 length = lowerTicks.length;
baseRanges = new IMultiPositionManager.Range[](length);
for (uint256 i = 0; i < length;) {
baseRanges[i] = IMultiPositionManager.Range(lowerTicks[i], upperTicks[i]);
unchecked {
++i;
}
}
// Calculate weights in separate function to avoid stack issues
uint256[] memory weights = calculateWeights(s, poolManager, ctx, lowerTicks, upperTicks);
// Continue processing in another helper to further reduce stack
return _executeRebalance(s, poolManager, ctx, baseRanges, weights, outMin, inMin);
}
/**
* @notice Calculate weights for positions from strategy
* @dev Made public so SimpleLens can use the exact same logic for preview
*/
function calculateWeights(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
StrategyContext memory ctx,
int24[] memory lowerTicks,
int24[] memory upperTicks
) public view returns (uint256[] memory) {
return calculateWeightsWithPoolKey(s.poolKey, poolManager, ctx, lowerTicks, upperTicks);
}
/**
* @notice Calculate weights (pure version for SimpleLens)
* @dev Accepts poolKey as parameter instead of reading from storage
*/
function calculateWeightsWithPoolKey(
PoolKey memory poolKey,
IPoolManager poolManager,
StrategyContext memory ctx,
int24[] memory lowerTicks,
int24[] memory upperTicks
) public view returns (uint256[] memory) {
// Store flag early to avoid stack too deep
bool useAssetWeights = ctx.useAssetWeights;
DensityParams memory params;
params.lowerTicks = lowerTicks;
params.upperTicks = upperTicks;
// Get current tick
(, params.tick,,) = poolManager.getSlot0(poolKey.toId());
params.center = ctx.center;
params.tLeft = ctx.tLeft;
params.tRight = ctx.tRight;
params.weight0 = ctx.weight0;
params.weight1 = ctx.weight1;
params.useCarpet = ctx.useCarpet;
params.tickSpacing = poolKey.tickSpacing;
// Check weights support
{
bool supportsWeightedDist = false;
try ctx.strategy.supportsWeights() returns (bool supported) {
supportsWeightedDist = supported;
} catch {}
// Use default weights if needed
if (!params.useCarpet && !supportsWeightedDist && (params.weight0 != 0.5e18 || params.weight1 != 0.5e18)) {
params.weight0 = 0.5e18;
params.weight1 = 0.5e18;
}
}
return ctx.strategy.calculateDensities(
params.lowerTicks,
params.upperTicks,
params.tick,
params.center,
params.tLeft,
params.tRight,
params.weight0,
params.weight1,
params.useCarpet,
params.tickSpacing,
useAssetWeights
);
}
function _executeRebalance(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
StrategyContext memory ctx,
IMultiPositionManager.Range[] memory baseRanges,
uint256[] memory weights,
uint256[2][] memory, /* outMin */
uint256[2][] memory /* inMin */
) internal returns (IMultiPositionManager.Range[] memory, uint128[] memory, uint24) {
// Calculate liquidities from weights
uint128[] memory liquidities = new uint128[](baseRanges.length);
// Store flag early to avoid stack too deep
bool useAssetWeights = ctx.useAssetWeights;
// Process in separate scope to reduce stack
{
// Get current pool state
(uint160 sqrtPriceX96,,,) = poolManager.getSlot0(s.poolKey.toId());
// Get total available amounts (will be calculated by caller)
(uint256 available0, uint256 available1) = _getTotalAvailable(s, poolManager);
// Carpet mode requires both tokens to create base layer across all positions
if (ctx.useCarpet && (available0 == 0 || available1 == 0)) {
revert CarpetRequiresBothTokens();
}
// Use existing helper to calculate liquidities from weights
_calculateLiquiditiesFromWeights(
liquidities, weights, baseRanges, available0, available1, sqrtPriceX96, useAssetWeights
);
}
// Verify carpet positions have sufficient liquidity
if (ctx.useCarpet) {
_validateCarpetLiquidity(baseRanges, liquidities, s.poolKey.tickSpacing);
}
// Store the parameters for future use (useSwap = false for regular rebalance)
_updateStrategyParams(s, ctx, false);
// Return the data needed for the unlock
// Note: Rebalance event will be emitted in MultiPositionManager after unlock completes
return (baseRanges, liquidities, ctx.limitWidth);
}
function _updateStrategyParams(SharedStructs.ManagerStorage storage s, StrategyContext memory ctx, bool useSwap)
internal
{
s.lastStrategyParams = SharedStructs.StrategyParams({
strategy: ctx.resolvedStrategy,
centerTick: ctx.center,
ticksLeft: ctx.tLeft,
ticksRight: ctx.tRight,
limitWidth: ctx.limitWidth,
weight0: uint120(ctx.weight0),
weight1: uint120(ctx.weight1),
useCarpet: ctx.useCarpet,
useSwap: useSwap,
useAssetWeights: ctx.useAssetWeights
});
}
struct AllocationData {
uint256[] token0Allocations;
uint256[] token1Allocations;
uint256 totalToken0Needed;
uint256 totalToken1Needed;
uint256 currentRangeIndex;
int24 currentTick;
bool hasCurrentRange;
}
/**
* @notice Helper to calculate liquidities from weights using pre-mint allocation fixing
* @dev Allocate, fix current range, redistribute excess, then mint
*/
function _calculateLiquiditiesFromWeights(
uint128[] memory liquidities,
uint256[] memory weights,
IMultiPositionManager.Range[] memory baseRanges,
uint256 total0,
uint256 total1,
uint160 sqrtPriceX96,
bool useAssetWeights
) internal pure {
if (!useAssetWeights) {
// For explicit weights, use direct liquidity calculation (old approach)
calculateLiquiditiesDirectly(liquidities, weights, baseRanges, total0, total1, sqrtPriceX96);
return;
}
// For proportional weights, use allocation-based approach with redistribution
AllocationData memory data;
uint256 rangesLength = baseRanges.length;
// Initialize arrays
data.token0Allocations = new uint256[](rangesLength);
data.token1Allocations = new uint256[](rangesLength);
// Get current tick from sqrtPrice
data.currentTick = TickMath.getTickAtSqrtPrice(sqrtPriceX96);
// Step 1: Calculate initial token allocations based on weights
calculateInitialAllocations(data, baseRanges, weights, sqrtPriceX96);
// Step 2: Scale allocations proportionally to available tokens
scaleAllocations(data, total0, total1, true);
// Step 3: Fix current range allocation and redistribute excess
if (data.hasCurrentRange) {
fixCurrentRangeAndRedistribute(data, baseRanges, sqrtPriceX96);
}
// Step 4: Mint all positions with corrected allocations
mintFromAllocations(liquidities, data, baseRanges, sqrtPriceX96);
}
/**
* @notice Calculate liquidities directly using limiting token approach (for explicit weights)
* @dev Old approach: calculate global limiting factor, then set each position's liquidity
*/
function calculateLiquiditiesDirectly(
uint128[] memory liquidities,
uint256[] memory weights,
IMultiPositionManager.Range[] memory baseRanges,
uint256 total0,
uint256 total1,
uint160 sqrtPriceX96
) internal pure {
uint256 rangesLength = baseRanges.length;
// Calculate total weighted amounts needed for liquidity = 1e18
uint256 totalWeightedToken0;
uint256 totalWeightedToken1;
for (uint256 i = 0; i < rangesLength;) {
uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(baseRanges[i].lowerTick);
uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(baseRanges[i].upperTick);
// Get amounts needed for 1e18 liquidity
(uint256 amount0For1e18, uint256 amount1For1e18) =
LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, 1e18);
// Add weighted amounts
totalWeightedToken0 += FullMath.mulDiv(amount0For1e18, weights[i], 1e18);
totalWeightedToken1 += FullMath.mulDiv(amount1For1e18, weights[i], 1e18);
unchecked {
++i;
}
}
// Calculate maximum liquidity we can provide given our token amounts
uint256 maxLiquidityFromToken0 =
totalWeightedToken0 != 0 ? FullMath.mulDiv(total0, 1e18, totalWeightedToken0) : type(uint256).max;
uint256 maxLiquidityFromToken1 =
totalWeightedToken1 != 0 ? FullMath.mulDiv(total1, 1e18, totalWeightedToken1) : type(uint256).max;
// Use the limiting factor (smaller of the two)
uint256 totalLiquidity =
maxLiquidityFromToken0 < maxLiquidityFromToken1 ? maxLiquidityFromToken0 : maxLiquidityFromToken1;
// Set each position's liquidity based on its weight and the total liquidity
for (uint256 i = 0; i < rangesLength;) {
liquidities[i] = uint128(FullMath.mulDiv(weights[i], totalLiquidity, 1e18));
unchecked {
++i;
}
}
}
/**
* @notice Calculate initial token allocations based on weights
*/
function calculateInitialAllocations(
AllocationData memory data,
IMultiPositionManager.Range[] memory baseRanges,
uint256[] memory weights,
uint160 sqrtPriceX96
) internal pure {
uint256 rangesLength = baseRanges.length;
for (uint256 i = 0; i < rangesLength;) {
uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(baseRanges[i].lowerTick);
uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(baseRanges[i].upperTick);
// Calculate token amounts for 1e18 liquidity
(uint256 token0For1e18, uint256 token1For1e18) =
LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, 1e18);
// Apply weights to get initial allocations
data.token0Allocations[i] = FullMath.mulDiv(token0For1e18, weights[i], 1e18);
data.token1Allocations[i] = FullMath.mulDiv(token1For1e18, weights[i], 1e18);
// Track totals
data.totalToken0Needed += data.token0Allocations[i];
data.totalToken1Needed += data.token1Allocations[i];
// Check if this is the current range
if (baseRanges[i].lowerTick <= data.currentTick && data.currentTick < baseRanges[i].upperTick) {
data.currentRangeIndex = i;
data.hasCurrentRange = true;
}
unchecked {
++i;
}
}
}
/**
* @notice Scale allocations proportionally to available tokens
* @dev Two modes:
* - Proportional weights (0,0): Scale independently, will redistribute later
* - Explicit weights: Use limiting token approach, leave excess
*/
function scaleAllocations(
AllocationData memory data,
uint256 available0,
uint256 available1,
bool useAssetWeights
) internal pure {
uint256 rangesLength = data.token0Allocations.length;
if (useAssetWeights) {
// Proportional mode: Scale each token independently to use 100%
// Excess will be redistributed in _fixCurrentRangeAndRedistribute
if (data.totalToken0Needed != 0) {
for (uint256 i = 0; i < rangesLength;) {
data.token0Allocations[i] =
FullMath.mulDiv(data.token0Allocations[i], available0, data.totalToken0Needed);
unchecked {
++i;
}
}
}
if (data.totalToken1Needed != 0) {
for (uint256 i = 0; i < rangesLength;) {
data.token1Allocations[i] =
FullMath.mulDiv(data.token1Allocations[i], available1, data.totalToken1Needed);
unchecked {
++i;
}
}
}
} else {
// Explicit weights mode: Use limiting token approach
// Calculate max liquidity from each token
uint256 maxLiquidityFromToken0 = data.totalToken0Needed != 0
? FullMath.mulDiv(available0, 1e18, data.totalToken0Needed)
: type(uint256).max;
uint256 maxLiquidityFromToken1 = data.totalToken1Needed != 0
? FullMath.mulDiv(available1, 1e18, data.totalToken1Needed)
: type(uint256).max;
// Use the limiting factor (smaller of the two)
uint256 scaleFactor =
maxLiquidityFromToken0 < maxLiquidityFromToken1 ? maxLiquidityFromToken0 : maxLiquidityFromToken1;
// Scale both allocations by the same factor
for (uint256 i = 0; i < rangesLength;) {
data.token0Allocations[i] = FullMath.mulDiv(data.token0Allocations[i], scaleFactor, 1e18);
data.token1Allocations[i] = FullMath.mulDiv(data.token1Allocations[i], scaleFactor, 1e18);
unchecked {
++i;
}
}
}
}
struct ExcessData {
uint256 excessToken0;
uint256 excessToken1;
uint256 actualToken0;
uint256 actualToken1;
}
/**
* @notice Fix current range allocation and redistribute excess
*/
function fixCurrentRangeAndRedistribute(
AllocationData memory data,
IMultiPositionManager.Range[] memory baseRanges,
uint160 sqrtPriceX96
) internal pure {
ExcessData memory excess = calculateCurrentRangeExcess(data, baseRanges[data.currentRangeIndex], sqrtPriceX96);
// Update current range to actual usage
data.token0Allocations[data.currentRangeIndex] = excess.actualToken0;
data.token1Allocations[data.currentRangeIndex] = excess.actualToken1;
// Redistribute excesses
if (excess.excessToken0 > 0) {
redistributeToken0(data, baseRanges, excess.excessToken0);
}
if (excess.excessToken1 > 0) {
redistributeToken1(data, baseRanges, excess.excessToken1);
}
}
/**
* @notice Calculate excess from current range allocation
*/
function calculateCurrentRangeExcess(
AllocationData memory data,
IMultiPositionManager.Range memory range,
uint160 sqrtPriceX96
) internal pure returns (ExcessData memory excess) {
uint256 idx = data.currentRangeIndex;
uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(range.lowerTick);
uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(range.upperTick);
// EXACT Python logic from mint_position function:
// if lower_price<pool_price<upper_price:
// Python: assume token y (token1) is in excess
// position_y=y
// position_liquidity=position_y/(np.sqrt(pool_price)-np.sqrt(lower_price))
uint128 liquidityFrom1 = 0;
if (sqrtPriceX96 > sqrtPriceLower) {
// Direct division as Python does: liquidity = amount1 / (sqrtPrice - sqrtPriceLower)
liquidityFrom1 =
uint128(FullMath.mulDiv(data.token1Allocations[idx], FixedPoint96.Q96, sqrtPriceX96 - sqrtPriceLower));
}
// Python: position_x=position_liquidity*(1/np.sqrt(pool_price)-1/np.sqrt(upper_price))
uint256 token0Needed = 0;
if (sqrtPriceX96 < sqrtPriceUpper && liquidityFrom1 > 0) {
// Calculate how much token0 would be needed with this liquidity
token0Needed = FullMath.mulDiv(
liquidityFrom1,
sqrtPriceUpper - sqrtPriceX96,
FullMath.mulDiv(sqrtPriceUpper, sqrtPriceX96, FixedPoint96.Q96)
);
}
// Python: if x<position_x: #if token y is actually in excess
uint128 actualLiquidity;
if (data.token0Allocations[idx] < token0Needed) {
// Token0 is actually limiting, recalculate
// position_x=x
// position_liquidity=position_x/(1/np.sqrt(pool_price)-1/np.sqrt(upper_price))
if (sqrtPriceX96 < sqrtPriceUpper) {
uint256 intermediate = FullMath.mulDiv(sqrtPriceUpper, sqrtPriceX96, FixedPoint96.Q96);
actualLiquidity =
uint128(FullMath.mulDiv(data.token0Allocations[idx], intermediate, sqrtPriceUpper - sqrtPriceX96));
} else {
actualLiquidity = 0;
}
} else {
// Token1 is limiting, use liquidityFrom1
actualLiquidity = liquidityFrom1;
}
// Calculate actual usage with the determined liquidity
(excess.actualToken0, excess.actualToken1) =
LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, actualLiquidity);
// Calculate excess
excess.excessToken0 =
data.token0Allocations[idx] > excess.actualToken0 ? data.token0Allocations[idx] - excess.actualToken0 : 0;
excess.excessToken1 =
data.token1Allocations[idx] > excess.actualToken1 ? data.token1Allocations[idx] - excess.actualToken1 : 0;
}
/**
* @notice Redistribute excess token0 to positions above current tick
*/
function redistributeToken0(
AllocationData memory data,
IMultiPositionManager.Range[] memory baseRanges,
uint256 excessToken0
) internal pure {
uint256 totalToken0Only;
uint256 rangesLength = data.token0Allocations.length;
// Find total weight of positions above current tick
for (uint256 i = 0; i < rangesLength;) {
if (baseRanges[i].lowerTick > data.currentTick) {
totalToken0Only += data.token0Allocations[i];
}
unchecked {
++i;
}
}
// Redistribute proportionally
if (totalToken0Only != 0) {
for (uint256 i = 0; i < rangesLength;) {
if (baseRanges[i].lowerTick > data.currentTick) {
data.token0Allocations[i] +=
FullMath.mulDiv(excessToken0, data.token0Allocations[i], totalToken0Only);
}
unchecked {
++i;
}
}
}
}
/**
* @notice Redistribute excess token1 to positions below current tick
*/
function redistributeToken1(
AllocationData memory data,
IMultiPositionManager.Range[] memory baseRanges,
uint256 excessToken1
) internal pure {
uint256 totalToken1Only;
uint256 rangesLength = data.token0Allocations.length;
// Find total weight of positions below current tick
for (uint256 i = 0; i < rangesLength;) {
if (baseRanges[i].upperTick <= data.currentTick) {
totalToken1Only += data.token1Allocations[i];
}
unchecked {
++i;
}
}
// Redistribute proportionally
if (totalToken1Only != 0) {
for (uint256 i = 0; i < rangesLength;) {
if (baseRanges[i].upperTick <= data.currentTick) {
data.token1Allocations[i] +=
FullMath.mulDiv(excessToken1, data.token1Allocations[i], totalToken1Only);
}
unchecked {
++i;
}
}
}
}
/**
* @notice Mint positions from corrected allocations
*/
function mintFromAllocations(
uint128[] memory liquidities,
AllocationData memory data,
IMultiPositionManager.Range[] memory baseRanges,
uint160 sqrtPriceX96
) internal pure {
uint256 rangesLength = baseRanges.length;
for (uint256 i = 0; i < rangesLength;) {
uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(baseRanges[i].lowerTick);
uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(baseRanges[i].upperTick);
// EXACT Python mint_position logic for each position type
if (baseRanges[i].upperTick <= data.currentTick) {
// Position entirely below current tick - only needs token1
// Python: position_liquidity=position_y/(np.sqrt(upper_price)-np.sqrt(lower_price))
if (sqrtPriceUpper > sqrtPriceLower && data.token1Allocations[i] > 0) {
liquidities[i] = uint128(
FullMath.mulDiv(data.token1Allocations[i], FixedPoint96.Q96, sqrtPriceUpper - sqrtPriceLower)
);
} else {
liquidities[i] = 0;
}
} else if (baseRanges[i].lowerTick > data.currentTick) {
// Position entirely above current tick - only needs token0
// Python: position_liquidity=position_x/(1/np.sqrt(lower_price)-1/np.sqrt(upper_price))
if (sqrtPriceUpper > sqrtPriceLower && data.token0Allocations[i] > 0) {
uint256 intermediate = FullMath.mulDiv(sqrtPriceUpper, sqrtPriceLower, FixedPoint96.Q96);
liquidities[i] = uint128(
FullMath.mulDiv(data.token0Allocations[i], intermediate, sqrtPriceUpper - sqrtPriceLower)
);
} else {
liquidities[i] = 0;
}
} else {
// Current range - use Python's exact logic
// First assume token1 is limiting
uint128 liquidityFrom1 = 0;
if (sqrtPriceX96 > sqrtPriceLower && data.token1Allocations[i] > 0) {
liquidityFrom1 = uint128(
FullMath.mulDiv(data.token1Allocations[i], FixedPoint96.Q96, sqrtPriceX96 - sqrtPriceLower)
);
}
// Calculate token0 needed with this liquidity
uint256 token0Needed = 0;
if (sqrtPriceX96 < sqrtPriceUpper && liquidityFrom1 > 0) {
token0Needed = FullMath.mulDiv(
liquidityFrom1,
sqrtPriceUpper - sqrtPriceX96,
FullMath.mulDiv(sqrtPriceUpper, sqrtPriceX96, FixedPoint96.Q96)
);
}
// Check if token0 is actually limiting
if (data.token0Allocations[i] < token0Needed && data.token0Allocations[i] > 0) {
// Token0 is limiting
if (sqrtPriceX96 < sqrtPriceUpper) {
uint256 intermediate = FullMath.mulDiv(sqrtPriceUpper, sqrtPriceX96, FixedPoint96.Q96);
liquidities[i] = uint128(
FullMath.mulDiv(data.token0Allocations[i], intermediate, sqrtPriceUpper - sqrtPriceX96)
);
} else {
liquidities[i] = 0;
}
} else {
// Token1 is limiting
liquidities[i] = liquidityFrom1;
}
}
unchecked {
++i;
}
}
}
function _validateCarpetLiquidity(
IMultiPositionManager.Range[] memory baseRanges,
uint128[] memory liquidities,
int24 tickSpacing
) internal pure {
int24 minUsable = TickMath.minUsableTick(tickSpacing);
int24 maxUsable = TickMath.maxUsableTick(tickSpacing);
if (baseRanges[0].lowerTick == minUsable && liquidities[0] == 0) {
revert InsufficientLiquidityForCarpet();
}
uint256 lastIdx = baseRanges.length - 1;
if (baseRanges[lastIdx].upperTick == maxUsable && liquidities[lastIdx] == 0) {
revert InsufficientLiquidityForCarpet();
}
}
/**
* @notice Get total available token amounts
* @dev Gets total amounts from all positions including fees and unused balances
*/
function _getTotalAvailable(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
internal
view
returns (uint256 total0, uint256 total1)
{
uint256 totalFee0;
uint256 totalFee1;
// Cache poolKey to avoid repeated SLOADs
PoolKey memory poolKey = s.poolKey;
// Get amounts from base positions including fees
for (uint256 i = 0; i < s.basePositionsLength;) {
(, uint256 amount0, uint256 amount1, uint256 feesOwed0, uint256 feesOwed1) =
PoolManagerUtils.getAmountsOf(poolManager, poolKey, s.basePositions[i]);
total0 += amount0;
total1 += amount1;
totalFee0 += feesOwed0;
totalFee1 += feesOwed1;
unchecked {
++i;
}
}
// Get amounts from limit positions including fees
for (uint256 i = 0; i < s.limitPositionsLength;) {
(, uint256 amount0, uint256 amount1, uint256 feesOwed0, uint256 feesOwed1) =
PoolManagerUtils.getAmountsOf(poolManager, poolKey, s.limitPositions[i]);
total0 += amount0;
total1 += amount1;
totalFee0 += feesOwed0;
totalFee1 += feesOwed1;
unchecked {
++i;
}
}
// Exclude protocol fee from the total fees
totalFee0 = totalFee0 - (totalFee0 / s.fee);
totalFee1 = totalFee1 - (totalFee1 / s.fee);
// Add fees net of protocol fees to the total amount
total0 += totalFee0;
total1 += totalFee1;
// Add unused balances
total0 += s.currency0.balanceOfSelf();
total1 += s.currency1.balanceOfSelf();
return (total0, total1);
}
/**
* @notice Process REBALANCE action in callback
* @dev Handles the complete rebalance flow including zeroBurn, burn old positions, and mint new ones
* @param s Storage struct
* @param poolManager Pool manager contract
* @param params Encoded rebalance parameters
* @param totalSupply Current total supply
* @return Empty bytes (no return value needed)
*/
function processRebalanceInCallback(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
bytes memory params,
uint256 totalSupply
) external returns (bytes memory) {
// Decode parameters
(
IMultiPositionManager.Range[] memory baseRanges,
uint128[] memory liquidities,
uint24 limitWidth,
uint256[2][] memory inMin,
uint256[2][] memory outMin,
IMultiPositionManager.RebalanceParams memory rebalanceParams
) = abi.decode(
params,
(
IMultiPositionManager.Range[],
uint128[],
uint24,
uint256[2][],
uint256[2][],
IMultiPositionManager.RebalanceParams
)
);
// Burn old positions and set up new ones
_burnAndSetupPositions(s, poolManager, baseRanges, limitWidth, outMin, totalSupply);
// Ensure inMin has correct length for slippage protection
// If empty array passed, create zero-filled array (no slippage protection)
if (inMin.length == 0) {
inMin = new uint256[2][](baseRanges.length);
} else if (inMin.length != baseRanges.length) {
revert InMinLengthMismatch(inMin.length, baseRanges.length);
}
// Mint new positions and capture position data
IMultiPositionManager.PositionData[] memory positionData =
PositionLogic.mintLiquidities(poolManager, s, liquidities, inMin);
// Build complete ranges array including base and limit positions
uint256 baseLength = s.basePositionsLength;
IMultiPositionManager.Range[] memory ranges = new IMultiPositionManager.Range[](baseLength + 2);
uint256 rangeCount = 0;
for (uint8 i = 0; i < baseLength;) {
ranges[rangeCount++] = s.basePositions[i];
unchecked {
++i;
}
}
if (s.limitPositions[0].lowerTick != s.limitPositions[0].upperTick) {
ranges[rangeCount++] = s.limitPositions[0];
}
if (s.limitPositions[1].lowerTick != s.limitPositions[1].upperTick) {
ranges[rangeCount++] = s.limitPositions[1];
}
// Resize ranges array to actual count
assembly {
mstore(ranges, rangeCount)
}
// Emit rebalance event
emit IMultiPositionManager.Rebalance(ranges, positionData, rebalanceParams);
return "";
}
/**
* @notice Perform zeroBurn if there are active positions
*/
function _performZeroBurnIfNeeded(SharedStructs.ManagerStorage storage s, IPoolManager poolManager) private {
uint256 baseLength = s.basePositionsLength;
// Check cheaper condition first for short-circuit optimization
if (baseLength != 0 || s.limitPositionsLength != 0) {
// Get ranges for zeroBurn
IMultiPositionManager.Range[] memory baseRangesArray = new IMultiPositionManager.Range[](baseLength);
for (uint8 i = 0; i < baseLength;) {
baseRangesArray[i] = s.basePositions[i];
unchecked {
++i;
}
}
IMultiPositionManager.Range[2] memory limitRangesArray = [s.limitPositions[0], s.limitPositions[1]];
PoolManagerUtils.zeroBurnAll(
poolManager, s.poolKey, baseRangesArray, limitRangesArray, s.currency0, s.currency1, s.fee
);
}
}
/**
* @notice Burn old positions and set up new ones
*/
function _burnAndSetupPositions(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
IMultiPositionManager.Range[] memory baseRanges,
uint24 limitWidth,
uint256[2][] memory outMin,
uint256 totalSupply
) private {
// Only burn if there are actual positions to burn
if (totalSupply > 0 && (s.basePositionsLength > 0 || s.limitPositionsLength > 0)) {
PositionLogic.burnLiquidities(poolManager, s, totalSupply, totalSupply, outMin);
}
// Set up new base positions
uint256 newBaseLength = baseRanges.length;
IMultiPositionManager.Range[] memory allRanges = new IMultiPositionManager.Range[](newBaseLength + 2);
s.basePositionsLength = newBaseLength;
for (uint8 i = 0; i < newBaseLength;) {
s.basePositions[i] = baseRanges[i];
allRanges[i] = baseRanges[i];
unchecked {
++i;
}
}
// Set limit ranges
(, int24 curTick,,) = poolManager.getSlot0(s.poolId);
PositionLogic.setLimitRanges(s, limitWidth, baseRanges, s.poolKey.tickSpacing, curTick);
allRanges[baseRanges.length] = s.limitPositions[0];
allRanges[baseRanges.length + 1] = s.limitPositions[1];
// Check ranges for duplicates
PositionLogic.checkRanges(allRanges);
}
/**
* @notice Process rebalance after a single token withdrawal
* @dev This function handles the rebalance logic when there are remaining tokens after withdrawal
* @param s Storage struct
* @param poolManager Pool manager contract
* @param remainingToken0 Amount of token0 remaining after withdrawal
* @param remainingToken1 Amount of token1 remaining after withdrawal
*/
function processRebalanceAfterWithdraw(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
uint256 remainingToken0,
uint256 remainingToken1
) external {
// Check if we need to rebalance - need remaining tokens and a strategy
if ((remainingToken0 == 0 && remainingToken1 == 0) || s.lastStrategyParams.strategy == address(0)) {
return;
}
// Create rebalance params from stored strategy
IMultiPositionManager.RebalanceParams memory rebalanceParams = IMultiPositionManager.RebalanceParams({
strategy: s.lastStrategyParams.strategy,
center: s.lastStrategyParams.centerTick,
tLeft: s.lastStrategyParams.ticksLeft,
tRight: s.lastStrategyParams.ticksRight,
limitWidth: s.lastStrategyParams.limitWidth,
weight0: uint256(s.lastStrategyParams.weight0),
weight1: uint256(s.lastStrategyParams.weight1),
useCarpet: s.lastStrategyParams.useCarpet
});
// Empty outMin for internal rebalance (no withdrawal happening)
uint256[2][] memory outMin = new uint256[2][](0);
// Rebalance using the remaining amounts
(IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities,) =
_processRebalance(s, poolManager, rebalanceParams, outMin, new uint256[2][](0));
// Set positions
uint256 newBaseLength = baseRanges.length;
for (uint256 i = 0; i < newBaseLength;) {
s.basePositions[i] = baseRanges[i];
unchecked {
++i;
}
}
s.basePositionsLength = newBaseLength;
// Create empty inMin for internal deposit (no slippage protection needed for internal calls)
uint256[2][] memory inMin = new uint256[2][](baseRanges.length);
// Mint positions and capture position data
IMultiPositionManager.PositionData[] memory positionData =
PositionLogic.mintLiquidities(poolManager, s, liquidities, inMin);
// Build ranges array including base and limit positions
uint256 baseLength = s.basePositionsLength;
IMultiPositionManager.Range[] memory ranges = new IMultiPositionManager.Range[](baseLength + 2);
uint256 rangeCount = 0;
for (uint8 i = 0; i < baseLength;) {
ranges[rangeCount++] = s.basePositions[i];
unchecked {
++i;
}
}
if (s.limitPositions[0].lowerTick != s.limitPositions[0].upperTick) {
ranges[rangeCount++] = s.limitPositions[0];
}
if (s.limitPositions[1].lowerTick != s.limitPositions[1].upperTick) {
ranges[rangeCount++] = s.limitPositions[1];
}
// Resize ranges array to actual count
assembly {
mstore(ranges, rangeCount)
}
// Emit rebalance event
emit IMultiPositionManager.Rebalance(ranges, positionData, rebalanceParams);
}
/**
* @notice Calculate weights based on current token amounts and price
* @param amount0 Current amount of token0
* @param amount1 Current amount of token1
* @param sqrtPriceX96 Current pool sqrt price
* @return weight0 Weight for token0 (in 1e18)
* @return weight1 Weight for token1 (in 1e18)
*/
function calculateWeightsFromAmounts(uint256 amount0, uint256 amount1, uint160 sqrtPriceX96)
internal
pure
returns (uint256 weight0, uint256 weight1)
{
// Calculate value0 in token1 terms using sqrtPriceX96 directly
uint256 value0InToken1 =
FullMath.mulDiv(FullMath.mulDiv(amount0, uint256(sqrtPriceX96), 1 << 96), uint256(sqrtPriceX96), 1 << 96);
uint256 totalValue = value0InToken1 + amount1;
if (totalValue == 0) {
return (0.5e18, 0.5e18);
}
weight0 = FullMath.mulDiv(value0InToken1, 1e18, totalValue);
weight1 = 1e18 - weight0;
}
/**
* @notice Get density weights from strategy
*/
function _getDensities(WeightCalculationParams memory params, int24[] memory lowerTicks, int24[] memory upperTicks)
private
view
returns (uint256[] memory)
{
return params.strategy.calculateDensities(
lowerTicks,
upperTicks,
params.currentTick,
params.center,
params.tLeft,
params.tRight,
0,
0,
params.useCarpet,
params.tickSpacing,
true
);
}
/**
* @notice Calculate weighted token amounts based on strategy densities
* @dev Helper function to avoid stack too deep in calculateWeightsFromStrategy
*/
function _calculateWeightedAmounts(
WeightCalculationParams memory params,
int24[] memory lowerTicks,
int24[] memory upperTicks
) private view returns (uint256 totalAmount0, uint256 totalAmount1) {
uint256[] memory densities = _getDensities(params, lowerTicks, upperTicks);
uint160 sqrtPrice = params.sqrtPriceX96;
uint256 length = lowerTicks.length;
for (uint256 i = 0; i < length;) {
uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(lowerTicks[i]);
uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(upperTicks[i]);
(uint256 amount0For1e18, uint256 amount1For1e18) =
LiquidityAmounts.getAmountsForLiquidity(sqrtPrice, sqrtPriceLower, sqrtPriceUpper, 1e18);
totalAmount0 += (amount0For1e18 * densities[i]) / 1e18;
totalAmount1 += (amount1For1e18 * densities[i]) / 1e18;
unchecked {
++i;
}
}
}
function calculateWeightsFromStrategy(
ILiquidityStrategy strategy,
int24 center,
uint24 tLeft,
uint24 tRight,
int24 tickSpacing,
bool useCarpet,
uint160 sqrtPriceX96,
int24 currentTick
) internal view returns (uint256 weight0, uint256 weight1) {
WeightCalculationParams memory params = WeightCalculationParams({
strategy: strategy,
center: center,
tLeft: tLeft,
tRight: tRight,
tickSpacing: tickSpacing,
useCarpet: useCarpet,
sqrtPriceX96: sqrtPriceX96,
currentTick: currentTick
});
(int24[] memory lowerTicks, int24[] memory upperTicks) =
strategy.generateRanges(center, tLeft, tRight, tickSpacing, useCarpet);
if (lowerTicks.length == 0) return (0.5e18, 0.5e18);
(uint256 totalAmount0, uint256 totalAmount1) = _calculateWeightedAmounts(params, lowerTicks, upperTicks);
if (totalAmount0 == 0 && totalAmount1 == 0) return (0.5e18, 0.5e18);
uint256 value0InToken1 = FullMath.mulDiv(
FullMath.mulDiv(totalAmount0, uint256(sqrtPriceX96), 1 << 96), uint256(sqrtPriceX96), 1 << 96
);
uint256 totalValue = value0InToken1 + totalAmount1;
if (totalValue == 0) return (0.5e18, 0.5e18);
weight0 = FullMath.mulDiv(value0InToken1, 1e18, totalValue);
weight1 = 1e18 - weight0;
}
/**
* @notice Calculate optimal swap amount to achieve target weight distribution
* @param amount0 Current amount of token0
* @param amount1 Current amount of token1
* @param sqrtPriceX96 Current pool sqrt price
* @param weight0 Target weight for token0 (in 1e18)
* @return swapToken0 True if swapping token0 to token1, false otherwise
* @return swapAmount Amount to swap
*/
function calculateOptimalSwap(
uint256 amount0,
uint256 amount1,
uint160 sqrtPriceX96,
uint256 weight0,
uint256 /* weight1 */
) public pure returns (bool swapToken0, uint256 swapAmount) {
// Calculate value0 in token1 terms using sqrtPriceX96 directly to avoid precision loss
uint256 value0InToken1 =
FullMath.mulDiv(FullMath.mulDiv(amount0, uint256(sqrtPriceX96), 1 << 96), uint256(sqrtPriceX96), 1 << 96);
// Total value in token1 terms
uint256 totalValue = value0InToken1 + amount1;
// Target token0 value in token1 terms
uint256 target0ValueInToken1 = FullMath.mulDiv(totalValue, weight0, 1e18);
// Convert target back to token0 amount
// target0Amount = target0ValueInToken1 / (sqrtPriceX96^2 / 2^192)
// = target0ValueInToken1 * 2^192 / sqrtPriceX96^2
// = (target0ValueInToken1 * 2^96 / sqrtPriceX96) * 2^96 / sqrtPriceX96
uint256 target0Amount = FullMath.mulDiv(
FullMath.mulDiv(target0ValueInToken1, 1 << 96, uint256(sqrtPriceX96)), 1 << 96, uint256(sqrtPriceX96)
);
if (amount0 > target0Amount) {
swapToken0 = true;
swapAmount = amount0 - target0Amount;
} else {
swapToken0 = false;
uint256 token0Deficit = target0Amount - amount0;
// Convert token0Deficit to token1 amount
swapAmount = FullMath.mulDiv(
FullMath.mulDiv(token0Deficit, uint256(sqrtPriceX96), 1 << 96), uint256(sqrtPriceX96), 1 << 96
);
}
}
/**
* @notice Rebalance with token swap through aggregator
* @param s Storage struct
* @param poolManager Pool manager contract
* @param params Rebalance parameters
* @param aggregator Aggregator contract address
* @param swapData Encoded swap calldata
* @param minAmountOut Minimum amount expected from swap
* @param outMin Minimum output amounts for withdrawals
* @param inMin Minimum input amounts for new positions (slippage protection)
* @param totalSupply Current total supply of shares
* @return baseRanges The base ranges to rebalance to
* @return liquidities The liquidity amounts for each range
* @return limitWidth The limit width for limit positions
*/
/**
* @notice Execute swap exactly as specified in swapParams
* @dev Trusts off-chain calculation from SimpleLens.calculateOptimalSwapForRebalance
* @param s Storage struct
* @param swapParams Complete swap parameters from JavaScript including aggregator and calldata
* @param amount0 Current amount of token0
* @param amount1 Current amount of token1
* @return Updated amount0 and amount1 after swap
*/
function _executeProvidedSwap(
SharedStructs.ManagerStorage storage s,
SwapParams calldata swapParams,
uint256 amount0,
uint256 amount1
) private returns (uint256, uint256) {
if (swapParams.swapData.length == 0) {
// No swap needed
return (amount0, amount1);
}
// Get token addresses for swap execution
address currency0 = Currency.unwrap(s.poolKey.currency0);
address currency1 = Currency.unwrap(s.poolKey.currency1);
// Execute aggregator swap with validation
uint256 amountOut = _executeAggregatorSwap(swapParams, amount0, amount1, currency0, currency1);
emit SwapExecuted(swapParams.aggregatorAddress, swapParams.swapAmount, amountOut, swapParams.swapToken0);
// Update amounts based on swap direction
if (swapParams.swapToken0) {
return (amount0 - swapParams.swapAmount, amount1 + amountOut);
}
return (amount0 + amountOut, amount1 - swapParams.swapAmount);
}
/**
* @notice Execute swap and calculate rebalance ranges in one call
* @dev Combines swap execution and range calculation for cleaner flow
* @param s Storage struct
* @param poolManager The pool manager
* @param params Rebalance parameters including swap details
* @return baseRanges The base ranges to rebalance to
* @return liquidities The liquidity amounts for each range
* @return limitWidth The limit width for limit positions
*/
function executeSwapAndCalculateRanges(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
IMultiPositionManager.RebalanceSwapParams calldata params
)
external
returns (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities, uint24 limitWidth)
{
// 1. Get current balances
uint256 amount0 = s.currency0.balanceOfSelf();
uint256 amount1 = s.currency1.balanceOfSelf();
// 2. Execute swap if needed
if (params.swapParams.swapData.length > 0) {
(amount0, amount1) = _executeProvidedSwap(s, params.swapParams, amount0, amount1);
}
// 3. Calculate ranges with updated amounts
return _calculateRebalanceRanges(s, poolManager, params.rebalanceParams, amount0, amount1);
}
/**
* @notice Execute swap for compound operation
* @dev Used by compoundSwap to execute validated swap between ZERO_BURN and COMPOUND
* @param s Storage struct
* @param params Swap parameters including aggregator details
* @return amount0 Updated amount of token0 after swap
* @return amount1 Updated amount of token1 after swap
*/
function executeCompoundSwap(SharedStructs.ManagerStorage storage s, SwapParams calldata params)
external
returns (uint256 amount0, uint256 amount1)
{
// Get current balances
amount0 = s.currency0.balanceOfSelf();
amount1 = s.currency1.balanceOfSelf();
// Execute swap if swap data provided
if (params.swapData.length > 0) {
(amount0, amount1) = _executeProvidedSwap(s, params, amount0, amount1);
}
return (amount0, amount1);
}
/**
* @notice Execute swap through aggregator with validation
* @dev JavaScript builds complete function call, Solidity just executes it
* @param params Swap parameters including aggregator type and encoded calldata
* @param amount0 Available amount of token0
* @param amount1 Available amount of token1
* @param currency0 Address of token0
* @param currency1 Address of token1
* @return amountOut Amount of output token received
*/
function _executeAggregatorSwap(
SwapParams calldata params,
uint256 amount0,
uint256 amount1,
address currency0,
address currency1
) private returns (uint256 amountOut) {
// Validate aggregator type (prevents arbitrary contract calls)
if (uint8(params.aggregator) > 3) revert InvalidAggregator();
// Validate we have sufficient tokens for the swap
if (params.swapToken0) {
if (amount0 < params.swapAmount) revert InsufficientTokensForSwap();
} else {
if (amount1 < params.swapAmount) revert InsufficientTokensForSwap();
}
// Determine input and output tokens
address inputToken = params.swapToken0 ? currency0 : currency1;
address outputToken = params.swapToken0 ? currency1 : currency0;
// Check if input token is native ETH (address(0))
bool isETHIn = inputToken == address(0);
// Approve aggregator to spend input tokens (skip if native ETH)
if (!isETHIn) {
IERC20(inputToken).forceApprove(params.aggregatorAddress, params.swapAmount);
}
// Record balance before swap
uint256 balanceBefore = _getBalance(outputToken);
// Determine ETH value to send with call
// If swapping native ETH, send the swap amount; otherwise send 0
uint256 ethValue = isETHIn ? params.swapAmount : 0;
// Execute the aggregator's function call
// swapData already contains the complete, ready-to-execute function call from JavaScript
(bool success,) = params.aggregatorAddress.call{value: ethValue}(params.swapData);
// Reset approval for security (skip if native ETH)
if (!isETHIn) {
IERC20(inputToken).forceApprove(params.aggregatorAddress, 0);
}
// Bubble up revert reason if swap failed
if (!success) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
// Calculate and validate output amount
amountOut = _getBalance(outputToken) - balanceBefore;
if (amountOut < params.minAmountOut) revert InsufficientOutput();
return amountOut;
}
/**
* @notice Get balance of a token (handles both ERC20 and native ETH)
* @param token Token address (address(0) for native ETH)
* @return balance Current balance
*/
function _getBalance(address token) private view returns (uint256) {
if (token == address(0)) {
return address(this).balance;
} else {
return IERC20(token).balanceOf(address(this));
}
}
/**
* @notice Process the rebalance result after swap
* @dev Helper to avoid stack too deep
*/
function _calculateRebalanceRanges(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
IMultiPositionManager.RebalanceParams calldata params,
uint256 amount0,
uint256 amount1
)
private
returns (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities, uint24 limitWidth)
{
(uint160 sqrtPriceX96, int24 currentTick,,) = poolManager.getSlot0(s.poolKey.toId());
StrategyContext memory ctx = _buildStrategyContext(s, params, amount0, amount1, sqrtPriceX96, currentTick);
(baseRanges, liquidities) = generateRangesAndLiquidities(s, poolManager, ctx, amount0, amount1);
_updateStrategyParams(s, ctx, true);
s.basePositionsLength = 0;
s.limitPositionsLength = 0;
return (baseRanges, liquidities, ctx.limitWidth);
}
/**
* @notice Build strategy context from params
*/
function _buildStrategyContext(
SharedStructs.ManagerStorage storage s,
IMultiPositionManager.RebalanceParams calldata params,
uint256 amount0,
uint256 amount1,
uint160 sqrtPriceX96,
int24 currentTick
) private view returns (StrategyContext memory ctx) {
ctx.useAssetWeights = (params.weight0 == 0 && params.weight1 == 0);
if (ctx.useAssetWeights) {
(ctx.weight0, ctx.weight1) = calculateWeightsFromAmounts(amount0, amount1, sqrtPriceX96);
} else {
ctx.weight0 = params.weight0;
ctx.weight1 = params.weight1;
}
ctx.resolvedStrategy = params.strategy != address(0) ? params.strategy : s.lastStrategyParams.strategy;
if (params.center == type(int24).max) {
// Always round down to ensure the range contains the current tick
int24 compressed = currentTick / s.poolKey.tickSpacing;
if (currentTick < 0 && currentTick % s.poolKey.tickSpacing != 0) {
compressed--; // Round down for negative ticks with remainder
}
ctx.center = compressed * s.poolKey.tickSpacing;
} else {
ctx.center = params.center;
}
ctx.tLeft = params.tLeft;
ctx.tRight = params.tRight;
ctx.useCarpet = params.useCarpet;
ctx.limitWidth = params.limitWidth;
if (ctx.resolvedStrategy == address(0)) revert NoStrategySpecified();
ctx.strategy = ILiquidityStrategy(ctx.resolvedStrategy);
}
/**
* @notice Generate ranges and calculate liquidities
*/
/**
* @notice Generate ranges and calculate liquidities for given amounts
* @dev Made public so SimpleLens can use the exact same logic for preview
*/
function generateRangesAndLiquidities(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
StrategyContext memory ctx,
uint256 amount0,
uint256 amount1
) public view returns (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities) {
return generateRangesAndLiquiditiesWithPoolKey(s.poolKey, poolManager, ctx, amount0, amount1);
}
/**
* @notice Generate ranges and calculate liquidities (pure version for SimpleLens)
* @dev Accepts poolKey as parameter instead of reading from storage
*/
function generateRangesAndLiquiditiesWithPoolKey(
PoolKey memory poolKey,
IPoolManager poolManager,
StrategyContext memory ctx,
uint256 amount0,
uint256 amount1
) public view returns (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities) {
// Generate tick ranges
(int24[] memory lowerTicks, int24[] memory upperTicks) =
ctx.strategy.generateRanges(ctx.center, ctx.tLeft, ctx.tRight, poolKey.tickSpacing, ctx.useCarpet);
// Convert to Range array
baseRanges = new IMultiPositionManager.Range[](lowerTicks.length);
for (uint256 i = 0; i < lowerTicks.length;) {
baseRanges[i] = IMultiPositionManager.Range(lowerTicks[i], upperTicks[i]);
unchecked {
++i;
}
}
// Calculate weights using pure version
uint256[] memory weights = calculateWeightsWithPoolKey(poolKey, poolManager, ctx, lowerTicks, upperTicks);
// Initialize liquidities array
liquidities = new uint128[](baseRanges.length);
// Get current sqrt price
(uint160 sqrtPriceX96Current,,,) = poolManager.getSlot0(poolKey.toId());
// Calculate liquidities using global limiting factor approach
_calculateLiquiditiesFromWeights(
liquidities, weights, baseRanges, amount0, amount1, sqrtPriceX96Current, ctx.useAssetWeights
);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
// - - - external deps - - -
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {ReentrancyGuard} from "solmate/src/utils/ReentrancyGuard.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
// - - - local deps - - -
import {Errors} from "../errors/Errors.sol";
import {TruncatedOracle} from "./TruncatedOracle.sol";
contract VolatilityOracle is ReentrancyGuard {
/* ========== paged ring – each "leaf" holds 512 observations ========== */
uint16 internal constant PAGE_SIZE = 512;
using TruncatedOracle for TruncatedOracle.Observation[PAGE_SIZE];
using PoolIdLibrary for PoolKey;
using SafeCast for int256;
/* -------------------------------------------------------------------------- */
/* Library constants */
/* -------------------------------------------------------------------------- */
/* seconds in one day (for readability) */
uint32 internal constant ONE_DAY_SEC = 86_400;
/* parts-per-million constant */
uint32 internal constant PPM = 1_000_000;
/* pre-computed ONE_DAY × PPM to avoid a mul on every cap event *
* 86_400 * 1_000_000 == 86 400 000 000 < 2¹²⁷ – safe for uint128 */
uint64 internal constant ONE_DAY_PPM = 86_400 * 1_000_000;
/* one add (ONE_DAY_PPM) short of uint64::max */
uint64 internal constant CAP_FREQ_MAX = type(uint64).max - ONE_DAY_PPM + 1;
/* minimum change required to emit MaxTicksPerBlockUpdated event */
uint24 internal constant EVENT_DIFF = 5;
// Custom errors
error NotAuthorizedHook();
error OnlyOwner();
error OnlyOwnerOrFactory();
error ObservationOverflow(uint16 cardinality);
error ObservationTooOld(uint32 time, uint32 target);
error TooManyObservationsRequested();
event TickCapParamChanged(PoolId indexed poolId, uint24 newMaxTicksPerBlock);
event MaxTicksPerBlockUpdated(
PoolId indexed poolId, uint24 oldMaxTicksPerBlock, uint24 newMaxTicksPerBlock, uint32 blockTimestamp
);
event PolicyCacheRefreshed(PoolId indexed poolId);
/// emitted once per pool when the oracle is first enabled
event OracleConfigured(PoolId indexed poolId, address indexed hook, address indexed owner, uint24 initialCap);
event HookAuthorized(address indexed hook);
event HookRevoked(address indexed hook);
event AuthorizedFactorySet(address indexed factory);
/* ─────────────────── IMMUTABLE STATE ────────────────────── */
IPoolManager public immutable poolManager;
address public immutable owner; // Governance address that can refresh policy cache
/* ─────────────────── MULTI-HOOK AUTHORIZATION ────────────────────── */
/// @notice Mapping of authorized hook addresses that can push observations
mapping(address => bool) public authorizedHooks;
/// @notice Factory address that can register new hooks
address public authorizedFactory;
/* ───────────────────── MUTABLE STATE ────────────────────── */
mapping(PoolId => uint24) public maxTicksPerBlock; // adaptive cap
/* ppm-seconds never exceeds 8.64 e10 per event or 7.45 e15 per year →
well inside uint64. Using uint64 halves slot gas / SLOAD cost. */
mapping(PoolId => uint64) private capFreq; // ***saturating*** counter
mapping(PoolId => uint48) private lastFreqTs; // last decay update
struct ObservationState {
uint16 index;
/**
* @notice total number of populated observations.
* Includes the bootstrap slot written by `enableOracleForPool`,
* so after N user pushes the value is **N + 1**.
*/
uint16 cardinality;
uint16 cardinalityNext;
}
/* ─────────────── cached policy parameters (baseFee logic removed) ─────────────── */
struct CachedPolicy {
uint24 minCap;
uint24 maxCap;
uint32 stepPpm;
uint32 budgetPpm;
uint32 decayWindow;
uint32 updateInterval;
}
mapping(PoolId => CachedPolicy) internal _policy;
/* ────────────────── CHUNKED OBSERVATION RING ──────────────────
Each pool owns *pages* (index ⇒ Observation[PAGE_SIZE]).
A page is allocated lazily the first time it is touched, so the
storage footprint grows with `grow()` instead of pre-allocating
65 k slots (≈ 4 MiB) per pool. */
/// pool ⇒ page# ⇒ 512-slot chunk (lazily created)
mapping(PoolId => mapping(uint16 => TruncatedOracle.Observation[PAGE_SIZE])) internal _pages;
function _leaf(PoolId poolId, uint16 globalIdx)
internal
view
returns (TruncatedOracle.Observation[PAGE_SIZE] storage)
{
return _pages[poolId][globalIdx / PAGE_SIZE];
}
mapping(PoolId => ObservationState) public states;
// Store last max tick update time for rate limiting governance changes
mapping(PoolId => uint32) private _lastMaxTickUpdate;
/* ────────────────────── CONSTRUCTOR ─────────────────────── */
/// -----------------------------------------------------------------------
/// @notice Deploy the oracle and wire the immutable dependencies.
/// @param _poolManager Canonical v4 `PoolManager` contract
/// @param _owner Governor address that can refresh the cached policy
/// -----------------------------------------------------------------------
constructor(IPoolManager _poolManager, address _owner) {
if (address(_poolManager) == address(0)) revert Errors.ZeroAddress();
if (_owner == address(0)) revert Errors.ZeroAddress();
poolManager = _poolManager;
owner = _owner;
}
/* ────────────────────── AUTHORIZATION MANAGEMENT ─────────────────────── */
/// @notice Sets the authorized factory that can register hooks
/// @param _factory The factory address to authorize
function setAuthorizedFactory(address _factory) external {
if (msg.sender != owner) revert OnlyOwner();
authorizedFactory = _factory;
emit AuthorizedFactorySet(_factory);
}
/// @notice Adds an authorized hook that can push observations
/// @dev Can be called by owner or the authorized factory
/// @param _hook The hook address to authorize
function addAuthorizedHook(address _hook) external {
if (msg.sender != owner && msg.sender != authorizedFactory) revert OnlyOwnerOrFactory();
if (_hook == address(0)) revert Errors.ZeroAddress();
authorizedHooks[_hook] = true;
emit HookAuthorized(_hook);
}
/// @notice Removes an authorized hook
/// @dev Can only be called by owner
/// @param _hook The hook address to revoke
function removeAuthorizedHook(address _hook) external {
if (msg.sender != owner) revert OnlyOwner();
authorizedHooks[_hook] = false;
emit HookRevoked(_hook);
}
/**
* @notice Refreshes the cached policy parameters for a pool.
* @dev Can only be called by the owner (governance).
* @param poolId The PoolId of the pool.
* @param minCap Minimum maxTicksPerBlock value
* @param maxCap Maximum maxTicksPerBlock value
* @param stepPpm Auto-tune step size in PPM
* @param budgetPpm Target CAP frequency in PPM
* @param decayWindow Frequency decay window in seconds
* @param updateInterval Minimum time between auto-tune adjustments
*/
function refreshPolicyCache(
PoolId poolId,
uint24 minCap,
uint24 maxCap,
uint32 stepPpm,
uint32 budgetPpm,
uint32 decayWindow,
uint32 updateInterval
) external {
if (msg.sender != owner) revert OnlyOwner();
if (states[poolId].cardinality == 0) {
revert Errors.OracleOperationFailed("refreshPolicyCache", "Pool not enabled");
}
CachedPolicy storage pc = _policy[poolId];
// Update all policy parameters
pc.minCap = minCap;
pc.maxCap = maxCap;
pc.stepPpm = stepPpm;
pc.budgetPpm = budgetPpm;
pc.decayWindow = decayWindow;
pc.updateInterval = updateInterval;
_validatePolicy(pc);
// Ensure current maxTicksPerBlock is within new min/max bounds
uint24 currentCap = maxTicksPerBlock[poolId];
if (currentCap < pc.minCap) {
maxTicksPerBlock[poolId] = pc.minCap;
emit MaxTicksPerBlockUpdated(poolId, currentCap, pc.minCap, uint32(block.timestamp));
} else if (currentCap > pc.maxCap) {
maxTicksPerBlock[poolId] = pc.maxCap;
emit MaxTicksPerBlockUpdated(poolId, currentCap, pc.maxCap, uint32(block.timestamp));
}
emit PolicyCacheRefreshed(poolId);
}
/**
* @notice Enables the oracle for a given pool, initializing its state.
* @dev Can only be called by the configured hook address.
* @param key The PoolKey of the pool to enable.
* @param initialMaxTicksPerBlock User-set initial CAP threshold
* @param minCap Minimum maxTicksPerBlock value
* @param maxCap Maximum maxTicksPerBlock value
* @param stepPpm Auto-tune step size in PPM
* @param budgetPpm Target CAP frequency in PPM
* @param decayWindow Frequency decay window in seconds
* @param updateInterval Minimum time between auto-tune adjustments
*/
function enableOracleForPool(
PoolKey calldata key,
uint24 initialMaxTicksPerBlock,
uint24 minCap,
uint24 maxCap,
uint32 stepPpm,
uint32 budgetPpm,
uint32 decayWindow,
uint32 updateInterval
) external {
if (!authorizedHooks[msg.sender]) revert NotAuthorizedHook();
PoolId poolId = key.toId();
if (states[poolId].cardinality > 0) {
revert Errors.OracleOperationFailed("enableOracleForPool", "Already enabled");
}
/* ------------------------------------------------------------------ *
* Set policy parameters and validate *
* ------------------------------------------------------------------ */
CachedPolicy storage pc = _policy[poolId];
pc.minCap = minCap;
pc.maxCap = maxCap;
pc.stepPpm = stepPpm;
pc.budgetPpm = budgetPpm;
pc.decayWindow = decayWindow;
pc.updateInterval = updateInterval;
_validatePolicy(pc);
// ---------- external read last (reduces griefing surface) ----------
(, int24 initialTick,,) = StateLibrary.getSlot0(poolManager, poolId);
TruncatedOracle.Observation[PAGE_SIZE] storage first = _pages[poolId][0];
first.initialize(uint32(block.timestamp), initialTick);
states[poolId] = ObservationState({index: 0, cardinality: 1, cardinalityNext: 1});
// Clamp initialMaxTicksPerBlock inside the validated range
uint24 cappedInitial = initialMaxTicksPerBlock;
if (cappedInitial < pc.minCap) cappedInitial = pc.minCap;
if (cappedInitial > pc.maxCap) cappedInitial = pc.maxCap;
maxTicksPerBlock[poolId] = cappedInitial;
// --- audit-aid event ----------------------------------------------------
emit OracleConfigured(poolId, msg.sender, owner, cappedInitial);
}
// Internal workhorse
function _recordObservation(PoolId poolId, int24 preSwapTick) internal returns (bool tickWasCapped) {
ObservationState storage state = states[poolId];
uint16 localIdx = state.index % PAGE_SIZE;
uint16 pageBase = state.index - localIdx;
int24 currentTick;
// Scope to drop temporary variables
{
(, int24 tick,,) = StateLibrary.getSlot0(poolManager, poolId);
currentTick = tick;
uint24 cap = maxTicksPerBlock[poolId];
int256 tickDelta256 = int256(currentTick) - int256(preSwapTick);
uint256 absDelta = tickDelta256 >= 0 ? uint256(tickDelta256) : uint256(-tickDelta256);
if (absDelta >= cap) {
int256 capped = tickDelta256 > 0
? int256(preSwapTick) + int256(uint256(cap))
: int256(preSwapTick) - int256(uint256(cap));
currentTick = _toInt24(capped);
tickWasCapped = true;
}
}
// Write observation
uint16 newLocalIdx;
uint16 newPageCard;
{
TruncatedOracle.Observation[PAGE_SIZE] storage obs = _leaf(poolId, state.index);
uint128 liquidity = StateLibrary.getLiquidity(poolManager, poolId);
uint16 pageCardinality = state.cardinality > pageBase ? state.cardinality - pageBase : 1;
uint16 pageCardinalityNext = pageCardinality < PAGE_SIZE ? pageCardinality + 1 : pageCardinality;
(newLocalIdx, newPageCard) =
obs.write(localIdx, uint32(block.timestamp), currentTick, liquidity, pageCardinality, pageCardinalityNext);
}
// Update state if new slot written
{
uint16 pageCard = state.cardinality > pageBase ? state.cardinality - pageBase : 1;
bool wroteNewSlot = (newLocalIdx != localIdx) || (newPageCard != pageCard);
if (wroteNewSlot) {
if (localIdx == PAGE_SIZE - 1 && newLocalIdx == 0) {
unchecked { state.index = pageBase + PAGE_SIZE; }
} else {
unchecked { state.index = pageBase + newLocalIdx; }
}
unchecked {
if (state.cardinality < TruncatedOracle.MAX_CARDINALITY_ALLOWED) {
state.cardinality += 1;
}
}
if (state.cardinalityNext < state.cardinality + 1
&& state.cardinalityNext < TruncatedOracle.MAX_CARDINALITY_ALLOWED) {
state.cardinalityNext = state.cardinality + 1;
}
}
}
_updateCapFrequency(poolId, tickWasCapped);
}
/// -----------------------------------------------------------------------
/// @notice Record a new observation using the actual pre-swap tick.
/// -----------------------------------------------------------------------
function pushObservationAndCheckCap(PoolId poolId, int24 preSwapTick)
external
nonReentrant
returns (bool tickWasCapped)
{
if (!authorizedHooks[msg.sender]) revert NotAuthorizedHook();
if (states[poolId].cardinality == 0) {
revert Errors.OracleOperationFailed("pushObservationAndCheckCap", "Pool not enabled");
}
return _recordObservation(poolId, preSwapTick);
}
/* ─────────────────── VIEW FUNCTIONS ──────────────────────── */
/**
* @notice Checks if the oracle is enabled for a given pool.
* @param poolId The PoolId to check.
* @return True if the oracle is enabled, false otherwise.
*/
function isOracleEnabled(PoolId poolId) external view returns (bool) {
return states[poolId].cardinality > 0;
}
/**
* @notice Gets the latest observation for a pool.
* @param poolId The PoolId of the pool.
* @return tick The tick from the latest observation.
* @return blockTimestamp The timestamp of the latest observation.
*/
function getLatestObservation(PoolId poolId) external view returns (int24 tick, uint32 blockTimestamp) {
if (states[poolId].cardinality == 0) {
revert Errors.OracleOperationFailed("getLatestObservation", "Pool not enabled");
}
ObservationState storage state = states[poolId];
TruncatedOracle.Observation storage o = _leaf(poolId, state.index)[state.index % PAGE_SIZE];
(, int24 liveTick,,) = StateLibrary.getSlot0(poolManager, poolId);
return (liveTick, o.blockTimestamp);
}
/// @notice View helper mirroring the public mapping but typed for tests.
function getMaxTicksPerBlock(PoolId poolId) external view returns (uint24) {
return maxTicksPerBlock[poolId];
}
/**
* @notice Returns the saturation threshold for the capFreq counter.
* @return The maximum value for the capFreq counter before it saturates.
*/
function getCapFreqMax() external pure returns (uint64) {
return CAP_FREQ_MAX;
}
/// @notice Calculates time-weighted means of tick and liquidity
/// @param key the key of the pool to consult
/// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means
/// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp
/// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp
function consult(PoolKey calldata key, uint32 secondsAgo)
external
view
returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)
{
require(secondsAgo != 0, "BP");
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = secondsAgo;
secondsAgos[1] = 0;
(int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =
observe(key, secondsAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
uint160 secondsPerLiquidityCumulativesDelta =
secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];
int56 secondsAgoI56 = int56(uint56(secondsAgo));
arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgoI56);
// Always round to negative infinity
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgoI56 != 0)) arithmeticMeanTick--;
// We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128
uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;
harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));
}
/**
* @notice Observe oracle values at specific secondsAgos from the current block timestamp
* @dev Reverts if observation at or before the desired observation timestamp does not exist
* @param key The pool key to observe
* @param secondsAgos The array of seconds ago to observe
* @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each secondsAgo
* @return secondsPerLiquidityCumulativeX128s The cumulative seconds / max(1, liquidity) since pool initialized
*/
function observe(PoolKey calldata key, uint32[] memory secondsAgos)
public
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)
{
PoolId poolId = key.toId();
if (states[poolId].cardinality == 0) {
revert Errors.OracleOperationFailed("observe", "Pool not enabled");
}
ObservationState storage state = states[poolId];
uint16 gIdx = state.index; // global index of newest obs
uint32 time = uint32(block.timestamp);
// Determine oldest timestamp the caller cares about (largest secondsAgo)
uint32 oldestWanted;
if (secondsAgos.length != 0) {
uint32 sa = secondsAgos[secondsAgos.length - 1];
// Same wrap-around logic used by TruncatedOracle.observeSingle
oldestWanted = time >= sa ? time - sa : time + (type(uint32).max - sa) + 1;
}
uint16 leafCursor = gIdx;
// Walk pages backwards until the first timestamp inside the leaf is <= oldestWanted
while (true) {
TruncatedOracle.Observation[PAGE_SIZE] storage page = _leaf(poolId, leafCursor);
uint16 localIdx = uint16(leafCursor % PAGE_SIZE);
uint16 pageBase = leafCursor - localIdx;
uint16 pageCardinality = state.cardinality > pageBase ? state.cardinality - pageBase : 1;
// slot 0 may be uninitialised if page not yet full; choose first initialised slot
uint16 firstSlot = pageCardinality == PAGE_SIZE ? (localIdx + 1) % PAGE_SIZE : 0;
uint32 firstTs = page[firstSlot].blockTimestamp;
if (oldestWanted >= firstTs || leafCursor < PAGE_SIZE) break;
leafCursor -= PAGE_SIZE;
}
// Fetch the resolved leaf *after* the loop to guarantee initialization
TruncatedOracle.Observation[PAGE_SIZE] storage obs = _leaf(poolId, leafCursor);
uint16 idx = uint16(leafCursor % PAGE_SIZE);
// Cardinality of *this* leaf (cannot exceed PAGE_SIZE)
uint16 card = state.cardinality > leafCursor - idx ? state.cardinality - (leafCursor - idx) : 1;
if (card == 0) revert("empty-page-card");
if (card > PAGE_SIZE) {
card = PAGE_SIZE;
}
(, int24 currentTick,,) = StateLibrary.getSlot0(poolManager, poolId);
uint128 liquidity = StateLibrary.getLiquidity(poolManager, poolId);
(tickCumulatives, secondsPerLiquidityCumulativeX128s) =
obs.observe(time, secondsAgos, currentTick, idx, liquidity, card);
return (tickCumulatives, secondsPerLiquidityCumulativeX128s);
}
/* ────────────────────── INTERNALS ──────────────────────── */
/**
* @notice Updates the CAP frequency counter and potentially triggers auto-tuning.
* @dev Decays the frequency counter based on time elapsed since the last update.
* Increments the counter if a CAP occurred.
* Triggers auto-tuning if the frequency exceeds the budget or is too low.
* @param poolId The PoolId of the pool.
* @param capOccurred True if a CAP event occurred in the current block.
*/
function _updateCapFrequency(PoolId poolId, bool capOccurred) internal {
uint32 lastTs = uint32(lastFreqTs[poolId]);
uint32 nowTs = uint32(block.timestamp);
uint32 timeElapsed = nowTs - lastTs;
/* FAST-PATH ────────────────────────────────────────────────────────
No tick was capped *and* we're still in the same second ⇒ every
state var is already correct, so we avoid **all** SSTOREs. */
if (!capOccurred && timeElapsed == 0) return;
lastFreqTs[poolId] = uint48(nowTs); // single SSTORE only when needed
uint64 currentFreq = capFreq[poolId];
// --------------------------------------------------------------------- //
// 1️⃣ Add this block's CAP contribution *first* and saturate. //
// --------------------------------------------------------------------- //
if (capOccurred) {
unchecked {
currentFreq += uint64(ONE_DAY_PPM);
}
if (currentFreq >= CAP_FREQ_MAX || currentFreq < ONE_DAY_PPM) {
currentFreq = CAP_FREQ_MAX; // clamp one-step-early
}
}
/* -------- cache policy once -------- */
CachedPolicy storage pc = _policy[poolId];
uint32 budgetPpm = pc.budgetPpm;
uint32 decayWindow = pc.decayWindow;
uint32 updateInterval = pc.updateInterval;
// 2️⃣ Apply linear decay *only when no CAP in this block*.
if (!capOccurred && timeElapsed > 0 && currentFreq > 0) {
// decay factor = (window - elapsed) / window = 1 - elapsed / window
if (timeElapsed >= decayWindow) {
currentFreq = 0; // Fully decayed
} else {
uint64 decayFactorPpm = PPM - uint64(timeElapsed) * PPM / decayWindow;
uint128 decayed = uint128(currentFreq) * decayFactorPpm / PPM;
// ----- overflow-safe down-cast -------------------------
if (decayed > type(uint64).max) {
currentFreq = CAP_FREQ_MAX;
} else {
uint64 d64 = uint64(decayed);
currentFreq = d64 > CAP_FREQ_MAX ? CAP_FREQ_MAX : d64;
}
}
}
capFreq[poolId] = currentFreq; // single SSTORE
// Only auto-tune if enough time has passed since last update
if (!_autoTunePaused[poolId] && block.timestamp >= _lastMaxTickUpdate[poolId] + updateInterval) {
uint64 targetFreq = uint64(budgetPpm) * ONE_DAY_SEC;
if (currentFreq > targetFreq) {
// Too frequent caps -> Increase maxTicksPerBlock (loosen cap)
_autoTuneMaxTicks(poolId, pc, true);
} else {
// Caps too rare -> Decrease maxTicksPerBlock (tighten cap)
_autoTuneMaxTicks(poolId, pc, false);
}
}
}
/**
* @notice Adjusts the maxTicksPerBlock based on CAP frequency.
* @dev Increases the cap if caps are too frequent, decreases otherwise.
* Clamps the adjustment based on policy step size and min/max bounds.
* @param poolId The PoolId of the pool.
* @param pc Cached policy struct
* @param increase True to increase the cap, false to decrease.
*/
function _autoTuneMaxTicks(PoolId poolId, CachedPolicy storage pc, bool increase) internal {
uint24 currentCap = maxTicksPerBlock[poolId];
uint32 stepPpm = pc.stepPpm;
uint24 minCap = pc.minCap;
uint24 maxCap = pc.maxCap;
uint24 change = uint24(uint256(currentCap) * stepPpm / PPM);
if (change == 0) change = 1; // Ensure minimum change of 1 tick
uint24 newCap;
if (increase) {
newCap = currentCap + change > maxCap ? maxCap : currentCap + change;
} else {
newCap = currentCap > change + minCap ? currentCap - change : minCap;
}
uint24 diff = currentCap > newCap ? currentCap - newCap : newCap - currentCap;
if (newCap != currentCap) {
maxTicksPerBlock[poolId] = newCap;
_lastMaxTickUpdate[poolId] = uint32(block.timestamp);
if (diff >= EVENT_DIFF) {
emit MaxTicksPerBlockUpdated(poolId, currentCap, newCap, uint32(block.timestamp));
}
}
}
/* ────────────────────── INTERNAL HELPERS ───────────────────────── */
/// @dev bounded cast; reverts on overflow instead of truncating.
function _toInt24(int256 v) internal pure returns (int24) {
require(v >= type(int24).min && v <= type(int24).max, "Tick overflow");
return int24(v);
}
/// @dev Validate policy parameters
function _validatePolicy(CachedPolicy storage pc) internal view {
require(pc.stepPpm != 0, "stepPpm cannot be 0");
require(pc.minCap != 0, "minCap cannot be 0");
require(pc.maxCap >= pc.minCap, "maxCap must be >= minCap");
require(pc.decayWindow != 0, "decayWindow cannot be 0");
require(pc.updateInterval != 0, "updateInterval cannot be 0");
}
/* ───────────────────── Emergency pause ────────────────────── */
/// @notice Emitted when the governor toggles the auto-tune circuit-breaker.
event AutoTunePaused(PoolId indexed poolId, bool paused, uint32 timestamp);
/// @dev circuit-breaker flag per pool (default: false = auto-tune active)
mapping(PoolId => bool) private _autoTunePaused;
/**
* @notice Pause or un-pause the adaptive cap algorithm for a pool.
* @param poolId Target PoolId.
* @param paused True to disable auto-tune, false to resume.
*/
function setAutoTunePaused(PoolId poolId, bool paused) external {
if (msg.sender != owner) revert OnlyOwner();
_autoTunePaused[poolId] = paused;
emit AutoTunePaused(poolId, paused, uint32(block.timestamp));
}
/* ─────────────────────── public cardinality grow ─────────────────────── */
/**
* @notice Requests the ring buffer to grow to `cardinalityNext` slots.
* @dev Mirrors Uniswap-V3 behaviour. Callable by anyone; growth is capped
* by the TruncatedOracle library's internal MAX_CARDINALITY_ALLOWED.
* @param key Encoded PoolKey.
* @param cardinalityNext Desired new cardinality.
* @return oldNext Previous next-size.
* @return newNext Updated next-size after grow.
*/
function increaseCardinalityNext(PoolKey calldata key, uint16 cardinalityNext)
external
returns (uint16 oldNext, uint16 newNext)
{
// Public function - anyone can grow the observation buffer (like Uniswap V3)
PoolId poolId = key.toId();
ObservationState storage state = states[poolId];
if (state.cardinality == 0) {
revert Errors.OracleOperationFailed("increaseCardinalityNext", "Pool not enabled");
}
oldNext = state.cardinalityNext;
if (cardinalityNext <= oldNext) {
return (oldNext, oldNext);
}
state.cardinalityNext = TruncatedOracle.grow(
_leaf(poolId, state.cardinalityNext), // leaf storage slot
oldNext,
cardinalityNext
);
newNext = state.cardinalityNext;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Owner balance of an id.
/// @param owner The address of the owner.
/// @param id The id of the token.
/// @return amount The balance of the token.
function balanceOf(address owner, uint256 id) external view returns (uint256 amount);
/// @notice Spender allowance of an id.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @return amount The allowance of the token.
function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);
/// @notice Checks if a spender is approved by an owner as an operator
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @return approved The approval status.
function isOperator(address owner, address spender) external view returns (bool approved);
/// @notice Transfers an amount of an id from the caller to a receiver.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Transfers an amount of an id from a sender to a receiver.
/// @param sender The address of the sender.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Approves an amount of an id to a spender.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always
function approve(address spender, uint256 id, uint256 amount) external returns (bool);
/// @notice Sets or removes an operator for the caller.
/// @param operator The address of the operator.
/// @param approved The approval status.
/// @return bool True, always
function setOperator(address operator, bool approved) external returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
/// @notice Thrown when protocol fee is set too high
error ProtocolFeeTooLarge(uint24 fee);
/// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
error InvalidCaller();
/// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
error ProtocolFeeCurrencySynced();
/// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
event ProtocolFeeControllerUpdated(address indexed protocolFeeController);
/// @notice Emitted when the protocol fee is updated for a pool.
event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);
/// @notice Given a currency address, returns the protocol fees accrued in that currency
/// @param currency The currency to check
/// @return amount The amount of protocol fees accrued in the currency
function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);
/// @notice Sets the protocol fee for the given pool
/// @param key The key of the pool to set a protocol fee for
/// @param newProtocolFee The fee to set
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;
/// @notice Sets the protocol fee controller
/// @param controller The new protocol fee controller
function setProtocolFeeController(address controller) external;
/// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
/// @dev This will revert if the contract is unlocked
/// @param recipient The address to receive the protocol fees
/// @param currency The currency to withdraw
/// @param amount The amount of currency to withdraw
/// @return amountCollected The amount of currency successfully withdrawn
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected);
/// @notice Returns the current protocol fee controller address
/// @return address The current protocol fee controller address
function protocolFeeController() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice A BalanceDelta of 0
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
/// @notice Called by external contracts to access granular pool state
/// @param slot Key of slot to sload
/// @return value The value of the slot as bytes32
function extsload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access granular pool state
/// @param startSlot Key of slot to start sloading from
/// @param nSlots Number of slots to load into return value
/// @return values List of loaded values.
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);
/// @notice Called by external contracts to access sparse pool state
/// @param slots List of slots to SLOAD from.
/// @return values List of loaded values.
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
/// @notice Called by external contracts to access transient storage of the contract
/// @param slot Key of slot to tload
/// @return value The value of the slot as bytes32
function exttload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse transient pool state
/// @param slots List of slots to tload
/// @return values List of loaded values
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
/// @notice Parameter struct for `ModifyLiquidity` pool operations
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Parameter struct for `Swap` pool operations
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020500060203020504000106050205030304010505030400000000))
}
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
// Isolate the least significant bit.
x := and(x, sub(0, x))
// For the upper 3 bits of the result, use a De Bruijn-like lookup.
// Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
// forgefmt: disable-next-item
r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
0x8040405543005266443200005020610674053026020000107506200176117077)))
// For the lower 5 bits of the result, use a De Bruijn lookup.
// forgefmt: disable-next-item
r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
/// @notice Returns an account's balance in the token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {BalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {PoolId} from "v4-core/types/PoolId.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {Currency} from "v4-core/types/Currency.sol";
interface ILimitOrderManager {
// =========== Structs ===========
struct PositionTickRange {
int24 bottomTick;
int24 topTick;
bool isToken0;
}
struct ClaimableTokens {
Currency token;
uint256 principal;
uint256 fees;
}
struct UserPosition {
uint128 liquidity;
BalanceDelta lastFeePerLiquidity;
BalanceDelta claimablePrincipal;
BalanceDelta fees;
}
struct PositionState {
BalanceDelta feePerLiquidity;
uint128 totalLiquidity;
bool isActive;
// bool isWaitingKeeper;
uint256 currentNonce;
}
struct PositionInfo {
uint128 liquidity;
BalanceDelta fees;
bytes32 positionKey;
}
struct PositionBalances {
uint256 principal0;
uint256 principal1;
uint256 fees0;
uint256 fees1;
}
struct CreateOrderResult {
uint256 usedAmount;
bool isToken0;
int24 bottomTick;
int24 topTick;
}
struct ScaleOrderParams {
bool isToken0;
int24 bottomTick;
int24 topTick;
uint256 totalAmount;
uint256 totalOrders;
uint256 sizeSkew;
}
struct OrderInfo {
int24 bottomTick;
int24 topTick;
uint256 amount;
uint128 liquidity;
}
struct CreateOrdersCallbackData {
PoolKey key;
OrderInfo[] orders;
bool isToken0;
address orderCreator;
}
struct CancelOrderCallbackData {
PoolKey key;
int24 bottomTick;
int24 topTick;
uint128 liquidity;
address user;
bool isToken0;
}
struct ClaimOrderCallbackData {
BalanceDelta principal;
BalanceDelta fees;
PoolKey key;
address user;
}
// struct KeeperExecuteCallbackData {
// PoolKey key;
// bytes32[] positions;
// }
struct UnlockCallbackData {
CallbackType callbackType;
bytes data;
}
enum CallbackType {
CREATE_ORDERS,
// CREATE_ORDER,
CLAIM_ORDER,
CANCEL_ORDER
// CREATE_SCALE_ORDERS,
// KEEPER_EXECUTE_ORDERS
}
// =========== Errors ===========
error FeePercentageTooHigh();
error AmountTooLow();
error AddressZero();
error NotAuthorized();
// error PositionIsWaitingForKeeper();
error ZeroLimit();
error NotWhitelistedPool();
// Removed MinimumAmountNotMet error
error MaxOrdersExceeded();
error UnknownCallbackType();
// =========== Events ===========
event OrderClaimed(address owner, PoolId indexed poolId, bytes32 positionKey, uint256 principal0, uint256 principal1, uint256 fees0, uint256 fees1, uint256 hookFeePercentage);
event OrderCreated(address user, PoolId indexed poolId, bytes32 positionKey);
event OrderCanceled(address orderOwner, PoolId indexed poolId, bytes32 positionKey);
event OrderExecuted(PoolId indexed poolId, bytes32 positionKey);
event PositionsLeftOver(PoolId indexed poolId, bytes32[] leftoverPositions);
// event KeeperWaitingStatusReset(bytes32 positionKey, int24 bottomTick, int24 topTick, int24 currentTick);
event HookFeePercentageUpdated (uint256 percentage);
// =========== Functions ===========
function createLimitOrder(
bool isToken0,
int24 targetTick,
uint256 amount,
PoolKey calldata key
) external payable returns (CreateOrderResult memory);
function createScaleOrders(
bool isToken0,
int24 bottomTick,
int24 topTick,
uint256 totalAmount,
uint256 totalOrders,
uint256 sizeSkew,
PoolKey calldata key
) external payable returns (CreateOrderResult[] memory results);
// function setHook(address _hook) external;
function enableHook(address _hook) external;
function disableHook(address _hook) external;
function setHookFeePercentage(uint256 _percentage) external;
function executeOrder(
PoolKey calldata key,
int24 tickBeforeSwap,
int24 tickAfterSwap,
bool zeroForOne
) external;
function cancelOrder(PoolKey calldata key, bytes32 positionKey) external;
function positionState(PoolId poolId, bytes32 positionKey)
external
view
returns (
BalanceDelta feePerLiquidity,
uint128 totalLiquidity,
bool isActive,
// bool isWaitingKeeper,
uint256 currentNonce
);
function cancelBatchOrders(
PoolKey calldata key,
uint256 offset,
uint256 limit
) external;
// /// @notice Emergency function for keepers to cancel orders on behalf of users
// /// @dev Only callable by keepers to handle emergency situations
// /// @param key The pool key identifying the specific Uniswap V4 pool
// /// @param positionKeys Array of position keys to cancel
// /// @param user The address of the user whose orders to cancel
// function emergencyCancelOrders(
// PoolKey calldata key,
// bytes32[] calldata positionKeys,
// address user
// ) external;
// /// @notice Keeper function to claim positions on behalf of users
// /// @dev Only callable by keepers to help users claim their executed positions
// /// @param key The pool key identifying the specific Uniswap V4 pool
// /// @param positionKeys Array of position keys to claim
// /// @param user The address of the user whose positions to claim
// function keeperClaimPositionKeys(
// PoolKey calldata key,
// bytes32[] calldata positionKeys,
// address user
// ) external;
function claimOrder(PoolKey calldata key, bytes32 positionKey) external;
/// @notice Claims multiple positions using direct position keys
/// @dev This is more robust than using indices as position keys don't shift when other positions are removed
/// @param key The pool key identifying the specific Uniswap V4 pool
/// @param positionKeys Array of position keys to claim
function claimPositionKeys(
PoolKey calldata key,
bytes32[] calldata positionKeys
) external;
/// @notice Cancels multiple positions using direct position keys
/// @dev This is more robust than using indices as position keys don't shift when other positions are removed
/// @param key The pool key identifying the specific Uniswap V4 pool
/// @param positionKeys Array of position keys to cancel
function cancelPositionKeys(
PoolKey calldata key,
bytes32[] calldata positionKeys
) external;
/// @notice Batch claims multiple orders that were executed or canceled
/// @dev Uses pagination to handle large numbers of orders
/// @param key The pool key identifying the specific Uniswap V4 pool
/// @param offset Starting position in the user's position array
/// @param limit Maximum number of positions to process in this call
function claimBatchOrders(
PoolKey calldata key,
uint256 offset,
uint256 limit
) external;
// function executeOrderByKeeper(PoolKey calldata key, bytes32[] memory waitingPositions) external;
// function setKeeper(address _keeper, bool _isKeeper) external;
// function setExecutablePositionsLimit(uint256 _limit) external;
// Removed setMinAmount and setMinAmounts functions
// View functions
function getUserPositions(address user, PoolId poolId, uint256 offset, uint256 limit) external view returns (PositionInfo[] memory positions);
// Additional view functions for state variables
function currentNonce(PoolId poolId, bytes32 baseKey) external view returns (uint256);
function treasury() external view returns (address);
// function executablePositionsLimit() external view returns (uint256);
// function isKeeper(address) external view returns (bool);
// function minAmount(Currency currency) external view returns (uint256);
function getUserPositionCount(address user, PoolId poolId) external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for the callback executed when an address unlocks the pool manager
interface IUnlockCallback {
/// @notice Called by the pool manager on `msg.sender` when the manager is unlocked
/// @param data The data that was passed to the call to unlock
/// @return Any data that you want to be returned from the unlock call
function unlockCallback(bytes calldata data) external returns (bytes memory);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolId} from "v4-core/types/PoolId.sol";
import {BalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {ILimitOrderManager} from "../interfaces/ILimitOrderManager.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {BalanceDeltaLibrary} from "v4-core/types/BalanceDelta.sol";
import {LiquidityAmounts} from "v4-periphery/lib/v4-core/test/utils/LiquidityAmounts.sol";
import {BalanceDelta, toBalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {TickBitmap} from "v4-core/libraries/TickBitmap.sol";
import {BitMath} from "v4-core/libraries/BitMath.sol";
import "forge-std/console.sol";
library PositionManagement {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.Bytes32Set;
using BalanceDeltaLibrary for BalanceDelta;
uint256 internal constant Q128 = 1 << 128;
// ==== Errors ====
error InvalidSizeSkew();
// Removed MinimumAmountNotMet error
error MaxOrdersExceeded();
error InvalidTickRange();
error MinimumTwoOrders();
error InvalidScaleParameters();
/// @notice Calculates distribution of amounts and corresponding liquidity across scale orders
/// @param orders Array of OrderInfo structs with tick ranges defined
/// @param isToken0 True if orders are for token0, false for token1
/// @param totalAmount Total amount of tokens to distribute across orders
/// @param totalOrders Number of orders to create
/// @param sizeSkew Factor determining the distribution of amounts (scaled by 1e18)
/// @return ILimitOrderManager.OrderInfo[] Updated orders array with amounts and liquidity calculated
function calculateOrderSizes(
ILimitOrderManager.OrderInfo[] memory orders,
bool isToken0,
uint256 totalAmount,
uint256 totalOrders,
uint256 sizeSkew
) public pure returns (ILimitOrderManager.OrderInfo[] memory) {
uint256 totalAmountUsed;
unchecked {
for (uint256 i = 0; i < totalOrders; i++) {
uint256 orderAmount;
if (i == totalOrders - 1) {
orderAmount = totalAmount - totalAmountUsed;
} else {
orderAmount = _calculateOrderSize(
totalAmount,
totalOrders,
sizeSkew,
i + 1
);
totalAmountUsed += orderAmount;
}
orders[i].amount = orderAmount;
// Calculate liquidity
uint160 sqrtPriceAX96 = TickMath.getSqrtPriceAtTick(orders[i].bottomTick);
uint160 sqrtPriceBX96 = TickMath.getSqrtPriceAtTick(orders[i].topTick);
orders[i].liquidity = isToken0
? LiquidityAmounts.getLiquidityForAmount0(sqrtPriceAX96, sqrtPriceBX96, orderAmount)
: LiquidityAmounts.getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceBX96, orderAmount);
}
}
return orders;
}
// Removed validateScaleOrderSizes function
/// @notice Internal function to calculate the size of a specific order in a scale order series
/// @param totalSize Total amount of tokens to distribute
/// @param numOrders Number of orders in the series
/// @param sizeSkew Skew factor (scaled by 1e18, where 1e18 = no skew)
/// @param orderIndex Position of order in series (1-based index)
/// @return uint256 Calculated size for the specified order
function _calculateOrderSize(
uint256 totalSize,
uint256 numOrders,
uint256 sizeSkew, // scaled by 1e18
uint256 orderIndex // 1-based index
) public pure returns (uint256) {
if (orderIndex == 0 || orderIndex > numOrders) revert InvalidScaleParameters();
uint256 numerator1 = 2 * totalSize;
uint256 denominator1 = numOrders * (1e18 + sizeSkew);
uint256 basePart = FullMath.mulDiv(numerator1, 1e18, denominator1);
uint256 kMinusOne = sizeSkew >= 1e18 ? sizeSkew - 1e18 : 1e18 - sizeSkew;
uint256 indexRatio = FullMath.mulDiv(orderIndex - 1, 1e18, numOrders - 1);
uint256 skewComponent = FullMath.mulDiv(kMinusOne, indexRatio, 1e18);
uint256 multiplier = sizeSkew >= 1e18 ?
1e18 + skewComponent :
1e18 - skewComponent;
return FullMath.mulDiv(basePart, multiplier, 1e18);
}
struct PositionParams {
ILimitOrderManager.UserPosition position;
ILimitOrderManager.PositionState posState;
IPoolManager poolManager;
PoolId poolId;
int24 bottomTick;
int24 topTick;
bool isToken0;
uint256 feeDenom;
uint256 hookFeePercentage;
}
/// @notice Calculates the token balances and fees for a limit order position
/// @param params See PositionParams above
/// @return balances
function getPositionBalances(
PositionParams memory params, address limitOrderManager
) public view returns (ILimitOrderManager.PositionBalances memory balances) {
uint160 sqrtPriceAX96 = TickMath.getSqrtPriceAtTick(params.bottomTick);
uint160 sqrtPriceBX96 = TickMath.getSqrtPriceAtTick(params.topTick);
// Calculate principals
if (!params.posState.isActive) {
if (params.isToken0) {
balances.principal1 = LiquidityAmounts.getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, params.position.liquidity );
} else {
balances.principal0 = LiquidityAmounts.getAmount0ForLiquidity( sqrtPriceAX96,sqrtPriceBX96, params.position.liquidity );
}
} else {
(uint160 sqrtPriceX96, , , ) = StateLibrary.getSlot0(params.poolManager, params.poolId);
(balances.principal0, balances.principal1) = LiquidityAmounts.getAmountsForLiquidity( sqrtPriceX96, sqrtPriceAX96, sqrtPriceBX96, params.position.liquidity );
}
BalanceDelta fees;
if(params.posState.isActive) {
(uint256 fee0Global, uint256 fee1Global) = calculatePositionFee(
params.poolId,
params.bottomTick,
params.topTick,
params.isToken0,
params.poolManager,
limitOrderManager
);
fees = getUserProportionateFees(params.position, params.posState, fee0Global, fee1Global);
} else {
fees = params.position.fees;
if (params.position.liquidity != 0) {
BalanceDelta feeDiff = params.posState.feePerLiquidity - params.position.lastFeePerLiquidity;
int128 liq = int128(params.position.liquidity);
fees = params.position.fees + toBalanceDelta(
feeDiff.amount0() >= 0
? int128(int256(FullMath.mulDiv(uint256(uint128(feeDiff.amount0())), uint256(uint128(liq)), 1e18)))
: -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDiff.amount0())), uint256(uint128(liq)), 1e18))),
feeDiff.amount1() >= 0
? int128(int256(FullMath.mulDiv(uint256(uint128(feeDiff.amount1())), uint256(uint128(liq)), 1e18)))
: -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDiff.amount1())), uint256(uint128(liq)), 1e18)))
);
}
}
int128 fees0 = fees.amount0();
int128 fees1 = fees.amount1();
if(fees0 > 0) {
balances.fees0 = (uint256(uint128(fees0)) * (params.feeDenom - params.hookFeePercentage)) / params.feeDenom;
}
if(fees1 > 0) {
balances.fees1 = (uint256(uint128(fees1)) * (params.feeDenom - params.hookFeePercentage)) / params.feeDenom;
}
}
/// @notice Calculates a user's proportionate share of accumulated fees
/// @param position User's position data
/// @param posState Position state
/// @param globalFees0 Global fees for token0
/// @param globalFees1 Global fees for token1
/// @return BalanceDelta User's proportionate share of accumulated fees
function getUserProportionateFees(
ILimitOrderManager.UserPosition memory position,
ILimitOrderManager.PositionState memory posState,
uint256 globalFees0,
uint256 globalFees1
) public pure returns (BalanceDelta) {
if (position.liquidity == 0) return position.fees;
if (posState.totalLiquidity == 0) return position.fees;
int128 feePerLiq0 = int128(int256(FullMath.mulDiv(uint256(globalFees0), uint256(1e18), uint256(posState.totalLiquidity))));
int128 feePerLiq1 = int128(int256(FullMath.mulDiv(uint256(globalFees1), uint256(1e18), uint256(posState.totalLiquidity))));
BalanceDelta newTotalFeePerLiquidity = posState.feePerLiquidity + toBalanceDelta(feePerLiq0, feePerLiq1);
BalanceDelta feeDiff = newTotalFeePerLiquidity - position.lastFeePerLiquidity;
int128 userFee0 = feeDiff.amount0() >= 0
? int128(int256(FullMath.mulDiv(uint256(uint128(feeDiff.amount0())), uint256(position.liquidity), uint256(1e18))))
: -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDiff.amount0())), uint256(position.liquidity), uint256(1e18))));
int128 userFee1 = feeDiff.amount1() >= 0
? int128(int256(FullMath.mulDiv(uint256(uint128(feeDiff.amount1())), uint256(position.liquidity), uint256(1e18))))
: -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDiff.amount1())), uint256(position.liquidity), uint256(1e18))));
return position.fees + toBalanceDelta(userFee0, userFee1);
}
// Add position to tick-based storage using TickBitmap library
function addPositionToTick(
mapping(PoolId => mapping(int24 => bytes32)) storage positionAtTick,
mapping(PoolId => mapping(int16 => uint256)) storage tickBitmap,
PoolKey memory key,
int24 executableTick,
bytes32 positionKey
) internal {
PoolId poolId = key.toId();
int24 compressedTick = TickBitmap.compress(executableTick, key.tickSpacing);
positionAtTick[poolId][executableTick] = positionKey;
(int16 wordPos, uint8 bitPos) = TickBitmap.position(compressedTick);
uint256 mask = 1 << bitPos;
tickBitmap[poolId][wordPos] |= mask;
}
function removePositionFromTick(
mapping(PoolId => mapping(int24 => bytes32)) storage positionAtTick,
mapping(PoolId => mapping(int16 => uint256)) storage tickBitmap,
PoolKey memory key,
int24 executableTick
) internal {
PoolId poolId = key.toId();
int24 compressedTick = TickBitmap.compress(executableTick, key.tickSpacing);
(int16 wordPos, uint8 bitPos) = TickBitmap.position(compressedTick);
uint256 mask = ~(1 << bitPos);
tickBitmap[poolId][wordPos] &= mask;
positionAtTick[poolId][executableTick] = bytes32(0);
}
function calculatePositionFee(
PoolId poolId,
int24 bottomTick,
int24 topTick,
bool isToken0,
IPoolManager poolManager,
address limitOrderManager
) public view returns (uint256 fee0, uint256 fee1) {
(uint128 liquidityBefore, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) =
StateLibrary.getPositionInfo(
poolManager,
poolId,
limitOrderManager,
bottomTick,
topTick,
bytes32(uint256(isToken0 ? 0 : 1)) // salt
);
(uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = StateLibrary.getFeeGrowthInside(
poolManager,
poolId,
bottomTick,
topTick
);
uint256 feeGrowthDelta0 = 0;
uint256 feeGrowthDelta1 = 0;
unchecked {
if (feeGrowthInside0X128 != feeGrowthInside0LastX128) {
feeGrowthDelta0 = feeGrowthInside0X128 - feeGrowthInside0LastX128;
}
if (feeGrowthInside1X128 != feeGrowthInside1LastX128) {
feeGrowthDelta1 = feeGrowthInside1X128 - feeGrowthInside1LastX128;
}
fee0 = FullMath.mulDiv(feeGrowthDelta0, liquidityBefore, Q128);
fee1 = FullMath.mulDiv(feeGrowthDelta1, liquidityBefore, Q128);
}
return (fee0, fee1);
}
/// @notice Decodes a position key into its component parts
/// @param positionKey The bytes32 key to decode
/// @return bottomTick The lower tick boundary
/// @return topTick The upper tick boundary
/// @return isToken0 Whether the position is for token0
/// @return nonce The nonce value used in the key
function decodePositionKey(
bytes32 positionKey
) public pure returns (
int24 bottomTick,
int24 topTick,
bool isToken0,
uint256 nonce
) {
bottomTick = int24(uint24(uint256(positionKey) >> 232));
topTick = int24(uint24(uint256(positionKey) >> 208));
nonce = uint256(positionKey >> 8) & ((1 << 200) - 1);
isToken0 = uint256(positionKey) & 1 == 1;
}
/// @notice Calculates the balance delta for a position based on its key
/// @param positionKey The unique identifier of the position
/// @param liquidity The position's liquidity amount
/// @return BalanceDelta The calculated balance delta
function getBalanceDelta(
bytes32 positionKey,
uint128 liquidity
) public pure returns (BalanceDelta) {
(int24 bottomTick, int24 topTick, bool isToken0,) = decodePositionKey(positionKey);
uint160 sqrtPriceAX96 = TickMath.getSqrtPriceAtTick(bottomTick);
uint160 sqrtPriceBX96 = TickMath.getSqrtPriceAtTick(topTick);
if (isToken0) {
// Position was in token0, executed at topTick, got token1
uint256 amount = LiquidityAmounts.getAmount1ForLiquidity(
sqrtPriceAX96,
sqrtPriceBX96,
liquidity
);
return toBalanceDelta(0, int128(int256(amount)));
} else {
// Position was in token1, executed at bottomTick, got token0
uint256 amount = LiquidityAmounts.getAmount0ForLiquidity(
sqrtPriceAX96,
sqrtPriceBX96,
liquidity
);
return toBalanceDelta(int128(int256(amount)), 0);
}
}
/// @notice Generates unique keys for position identification
/// @return baseKey Key without nonce for tracking position versions
/// @return positionKey Unique key including nonce for this specific position
function getPositionKeys(
mapping(PoolId => mapping(bytes32 => uint256)) storage currentNonce,
PoolId poolId,
int24 bottomTick,
int24 topTick,
bool isToken0
) internal view returns (bytes32 baseKey, bytes32 positionKey) {
// Generate base key combining bottomTick, topTick, and isToken0
baseKey = bytes32(
uint256(uint24(bottomTick)) << 232 |
uint256(uint24(topTick)) << 208 |
uint256(isToken0 ? 1 : 0)
);
// Generate full position key with nonce
positionKey = bytes32(
uint256(uint24(bottomTick)) << 232 |
uint256(uint24(topTick)) << 208 |
uint256(currentNonce[poolId][baseKey]) << 8 |
uint256(isToken0 ? 1 : 0)
);
}
function calculateScaledFeePerLiquidity(
BalanceDelta feeDelta,
uint128 liquidity
) public pure returns (BalanceDelta) {
if(feeDelta == BalanceDelta.wrap(0) || liquidity == 0) return BalanceDelta.wrap(0);
return toBalanceDelta(
feeDelta.amount0() >= 0
? int128(int256(FullMath.mulDiv(uint256(uint128(feeDelta.amount0())), 1e18, liquidity)))
: -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDelta.amount0())), 1e18, liquidity))),
feeDelta.amount1() >= 0
? int128(int256(FullMath.mulDiv(uint256(uint128(feeDelta.amount1())), 1e18, liquidity)))
: -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDelta.amount1())), 1e18, liquidity)))
);
}
function calculateScaledUserFee(
BalanceDelta feeDiff,
uint128 liquidity
) public pure returns (BalanceDelta) {
if(feeDiff == BalanceDelta.wrap(0) || liquidity == 0) return BalanceDelta.wrap(0);
return toBalanceDelta(
feeDiff.amount0() >= 0
? int128(int256(FullMath.mulDiv(uint256(uint128(feeDiff.amount0())), uint256(liquidity), 1e18)))
: -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDiff.amount0())), uint256(liquidity), 1e18))),
feeDiff.amount1() >= 0
? int128(int256(FullMath.mulDiv(uint256(uint128(feeDiff.amount1())), uint256(liquidity), 1e18)))
: -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDiff.amount1())), uint256(liquidity), 1e18)))
);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {FixedPoint96} from "v4-core/libraries/FixedPoint96.sol";
import {ILimitOrderManager} from "../interfaces/ILimitOrderManager.sol";
library TickLibrary {
error WrongTargetTick(int24 currentTick, int24 targetTick, bool isToken0);
error BottomTickMustBeGreaterThanCurrentTick(int24 currentTick, int24 bottomTick, bool isToken0);
error TopTickMustBeLessThanOrEqualToCurrentTick(int24 currentTick, int24 topTick, bool isToken0);
error RoundedTicksTooClose(int24 currentTick, int24 roundedCurrentTick, int24 targetTick, int24 roundedTargetTick, bool isToken0);
error RoundedTargetTickLessThanRoundedCurrentTick(int24 currentTick, int24 roundedCurrentTick, int24 targetTick, int24 roundedTargetTick);
error RoundedTargetTickGreaterThanRoundedCurrentTick(int24 currentTick, int24 roundedCurrentTick, int24 targetTick, int24 roundedTargetTick);
error WrongTickRange(int24 bottomTick, int24 topTick, int24 currentTick, int24 targetTick, bool isToken0, bool isRange);
error SingleTickWrongTickRange(int24 bottomTick, int24 topTick, int24 currentTick, int24 targetTick, bool isToken0);
error TickOutOfBounds(int24 tick);
error InvalidPrice(uint256 price);
error PriceMustBeGreaterThanZero();
error InvalidSizeSkew();
error MaxOrdersExceeded();
error InvalidTickRange();
error MinimumTwoOrders();
uint256 internal constant Q128 = 1 << 128;
// function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
// unchecked {
// return (TickMath.MAX_TICK / tickSpacing) * tickSpacing;
// }
// }
// function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
// unchecked {
// return (TickMath.MIN_TICK / tickSpacing) * tickSpacing;
// }
// }
function getRoundedTargetTick(
int24 targetTick,
bool isToken0,
int24 tickSpacing
) internal pure returns(int24 roundedTargetTick) {
if (isToken0) {
roundedTargetTick = targetTick >= 0 ?
(targetTick / tickSpacing) * tickSpacing :
((targetTick % tickSpacing == 0) ? targetTick : ((targetTick / tickSpacing) - 1) * tickSpacing);
} else {
roundedTargetTick = targetTick < 0 ?
(targetTick / tickSpacing) * tickSpacing :
((targetTick % tickSpacing == 0) ? targetTick : ((targetTick / tickSpacing) + 1) * tickSpacing);
}
}
function getRoundedCurrentTick(
int24 currentTick,
bool isToken0,
int24 tickSpacing
) internal pure returns(int24 roundedCurrentTick) {
if (isToken0) {
roundedCurrentTick = currentTick >= 0 ?
(currentTick / tickSpacing) * tickSpacing + tickSpacing :
((currentTick % tickSpacing == 0) ? currentTick + tickSpacing : (currentTick / tickSpacing) * tickSpacing);
} else {
roundedCurrentTick = currentTick >= 0 ?
(currentTick / tickSpacing) * tickSpacing :
((currentTick % tickSpacing == 0) ? currentTick : (currentTick / tickSpacing) * tickSpacing - tickSpacing);
}
}
/// @notice Validates and calculates the appropriate tick range for a single-tick limit order
/// @param currentTick The current market tick price
/// @param targetTick The target tick price for the order
/// @param tickSpacing The minimum tick spacing for the pool
/// @param isToken0 True if order is for token0, false for token1
/// @return bottomTick The calculated lower tick boundary
/// @return topTick The calculated upper tick boundary
function getValidTickRange(
int24 currentTick,
int24 targetTick,
int24 tickSpacing,
bool isToken0
) public pure returns (int24 bottomTick, int24 topTick) {
if(isToken0 && currentTick >= targetTick)
revert WrongTargetTick(currentTick, targetTick, true);
if(!isToken0 && currentTick <= targetTick)
revert WrongTargetTick(currentTick, targetTick, false);
int24 roundedTargetTick = getRoundedTargetTick(targetTick, isToken0, tickSpacing);
int24 roundedCurrentTick = getRoundedCurrentTick(currentTick, isToken0, tickSpacing);
int24 tickDiff = roundedCurrentTick > roundedTargetTick ?
roundedCurrentTick - roundedTargetTick :
roundedTargetTick - roundedCurrentTick;
if(tickDiff < tickSpacing)
revert RoundedTicksTooClose(currentTick, roundedCurrentTick, targetTick, roundedTargetTick, isToken0);
if(isToken0) {
if(roundedCurrentTick >= roundedTargetTick)
revert RoundedTargetTickLessThanRoundedCurrentTick(currentTick, roundedCurrentTick, targetTick, roundedTargetTick);
topTick = roundedTargetTick;
bottomTick = topTick - tickSpacing;
} else {
if(roundedCurrentTick <= roundedTargetTick)
revert RoundedTargetTickGreaterThanRoundedCurrentTick(currentTick, roundedCurrentTick, targetTick, roundedTargetTick);
bottomTick = roundedTargetTick;
topTick = bottomTick + tickSpacing;
}
if(bottomTick >= topTick)
revert SingleTickWrongTickRange(bottomTick, topTick, currentTick, targetTick, isToken0);
if (bottomTick < TickMath.minUsableTick(tickSpacing) || topTick > TickMath.maxUsableTick(tickSpacing))
revert TickOutOfBounds(targetTick);
}
function validateAndPrepareScaleOrders(
int24 bottomTick,
int24 topTick,
int24 currentTick,
bool isToken0,
uint256 totalOrders,
uint256 sizeSkew,
int24 tickSpacing
) public pure returns (ILimitOrderManager.OrderInfo[] memory orders) {
if (totalOrders < 2) revert MinimumTwoOrders();
if (bottomTick >= topTick) revert InvalidTickRange();
if (sizeSkew == 0) revert InvalidSizeSkew();
if(isToken0 && currentTick >= bottomTick)
revert BottomTickMustBeGreaterThanCurrentTick(currentTick, bottomTick, true);
if(!isToken0 && currentTick < topTick)
revert TopTickMustBeLessThanOrEqualToCurrentTick(currentTick, topTick, false);
// Validate and round ticks
if (isToken0) {
// Rounded bottom tick is always greater or equal to original bottom tick
bottomTick = bottomTick % tickSpacing == 0 ? bottomTick :
bottomTick > 0 ? (bottomTick / tickSpacing + 1) * tickSpacing :
(bottomTick / tickSpacing) * tickSpacing;
topTick = getRoundedTargetTick(topTick, isToken0, tickSpacing);
require(topTick > bottomTick, "Rounded top tick must be above rounded bottom tick for token0 orders");
} else {
// Rounded top tick is always less or equal to original top tick
topTick = topTick % tickSpacing == 0 ? topTick :
topTick > 0 ? (topTick / tickSpacing) * tickSpacing :
(topTick / tickSpacing - 1) * tickSpacing;
bottomTick = getRoundedTargetTick(bottomTick, isToken0, tickSpacing);
require(bottomTick < topTick, "Rounded bottom tick must be below rounded top tick for token1 orders");
}
if (bottomTick < TickMath.minUsableTick(tickSpacing) || topTick > TickMath.maxUsableTick(tickSpacing))
revert TickOutOfBounds(bottomTick < TickMath.minUsableTick(tickSpacing) ? bottomTick : topTick);
// Check if enough space for orders
// Handle uint256 to uint24 conversion safely for totalOrders
if (totalOrders > uint256(uint24((topTick - bottomTick) / tickSpacing)))
revert MaxOrdersExceeded();
// Initialize orders array
orders = new ILimitOrderManager.OrderInfo[](totalOrders);
// Calculate positions with improved distribution
int24 effectiveRange = topTick - bottomTick - tickSpacing;
if (isToken0) {
unchecked {
for (uint256 i = 0; i < totalOrders; i++) {
// Calculate position
int24 orderBottomTick;
if (i == totalOrders - 1) {
// Last order approaches max
orderBottomTick = topTick - tickSpacing;
} else {
// Proportionally distribute
orderBottomTick = bottomTick + int24(uint24((i * uint256(uint24(effectiveRange))) / (totalOrders - 1)));
orderBottomTick = orderBottomTick % tickSpacing == 0 ?
orderBottomTick :
orderBottomTick >= 0 ?
orderBottomTick / tickSpacing * tickSpacing + tickSpacing :
orderBottomTick / tickSpacing * tickSpacing;
}
orders[i] = ILimitOrderManager.OrderInfo({
bottomTick: orderBottomTick,
topTick: orderBottomTick + tickSpacing,
amount: 0,
liquidity: 0
});
}
}
} else {
unchecked {
for (uint256 i = 0; i < totalOrders; i++) {
// Calculate position
int24 orderBottomTick;
if (i == 0) {
// First order uses min
orderBottomTick = bottomTick;
} else {
// Proportionally distribute
orderBottomTick = bottomTick + int24(uint24((i * uint256(uint24(effectiveRange))) / (totalOrders - 1)));
orderBottomTick = orderBottomTick % tickSpacing == 0 ?
orderBottomTick :
orderBottomTick >= 0 ?
orderBottomTick / tickSpacing * tickSpacing + tickSpacing :
orderBottomTick / tickSpacing * tickSpacing;
}
int24 orderTopTick = orderBottomTick + tickSpacing;
orders[i] = ILimitOrderManager.OrderInfo({
bottomTick: orderBottomTick,
topTick: orderTopTick,
amount: 0,
liquidity: 0
});
}
}
}
return orders;
}
function getRoundedPrice(
uint256 price, //always expressed as token0/token1 price
PoolKey calldata key,
bool isToken0
) public pure returns (uint256 roundedPrice) {
// Convert price to sqrtPriceX96
uint160 targetSqrtPriceX96 = getSqrtPriceFromPrice(price);
// Get raw tick from sqrt price
int24 rawTargetTick = TickMath.getTickAtSqrtPrice(targetSqrtPriceX96);
// Round the tick according to token direction and spacing
int24 roundedTargetTick = getRoundedTargetTick(rawTargetTick, isToken0, key.tickSpacing);
// Validate the rounded tick is within bounds
if (roundedTargetTick < TickMath.minUsableTick(key.tickSpacing) ||
roundedTargetTick > TickMath.maxUsableTick(key.tickSpacing)) {
revert TickOutOfBounds(roundedTargetTick);
}
// Get the sqrtPriceX96 at the rounded tick
uint160 roundedSqrtPriceX96 = TickMath.getSqrtPriceAtTick(roundedTargetTick);
// Convert back to regular price
roundedPrice = getPriceFromSqrtPrice(roundedSqrtPriceX96);
return roundedPrice;
}
function getSqrtPriceFromPrice(uint256 price) public pure returns (uint160) {
if (price == 0) revert PriceMustBeGreaterThanZero();
// price = token1/token0
// Convert price to Q96 format first
uint256 priceQ96 = FullMath.mulDiv(price, FixedPoint96.Q96, 1 ether); // Since input price is in 1e18 format
// Take square root using our sqrt function
uint256 sqrtPriceX96 = sqrt(priceQ96) << 48;
if (sqrtPriceX96 > type(uint160).max) revert InvalidPrice(price);
return uint160(sqrtPriceX96);
}
function getPriceFromSqrtPrice(uint160 sqrtPriceX96) public pure returns (uint256) {
// Square the sqrt price to get the price in Q96 format
uint256 priceQ96 = FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96);
// Convert from Q96 to regular price (1e18 format)
return FullMath.mulDiv(priceQ96, 1 ether, FixedPoint96.Q96);
}
function sqrt(uint256 x) public pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {ModifyLiquidityParams} from "v4-core/types/PoolOperation.sol";
import {ILimitOrderManager} from "../interfaces/ILimitOrderManager.sol";
import {Currency, CurrencyLibrary} from "v4-core/types/Currency.sol";
import {CurrencySettler} from "./CurrencySettler.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "v4-core/types/BalanceDelta.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {TransientStateLibrary} from "v4-core/libraries/TransientStateLibrary.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
library CallbackHandler {
using CurrencySettler for Currency;
using BalanceDeltaLibrary for BalanceDelta;
using PoolIdLibrary for PoolKey;
using SafeERC20 for IERC20;
using TransientStateLibrary for IPoolManager;
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
event FailedTransferSentToTreasury(Currency currency, address originalRecipient, uint256 amount);
struct CallbackState {
IPoolManager poolManager;
address treasury;
uint256 hookFeePercentage;
uint256 feeDenominator;
}
/// @notice Handles the callback for claiming order proceeds and fees
/// @param state The callback state containing pool manager and fee settings
/// @param claimData Struct containing claim details including principal, fees, and user address
/// @return bytes Encoded return value (always 0 for claim callbacks)
function handleClaimOrderCallback(
CallbackState storage state,
ILimitOrderManager.ClaimOrderCallbackData memory claimData
) internal returns (bytes memory) {
_handleTokenTransfersAndFees(
state,
uint256(uint128(claimData.principal.amount0())),
uint256(uint128(claimData.fees.amount0())),
claimData.key.currency0,
claimData.user
);
_handleTokenTransfersAndFees(
state,
uint256(uint128(claimData.principal.amount1())),
uint256(uint128(claimData.fees.amount1())),
claimData.key.currency1,
claimData.user
);
_clearExactDelta(state, claimData.key.currency0);
_clearExactDelta(state, claimData.key.currency1);
return abi.encode(0);
}
/// @notice Handles the callback for canceling a limit order
/// @param state The callback state containing pool manager reference
/// @param cancelData Struct containing order details needed for cancellation (ticks, liquidity)
/// @return bytes ABI encoded balance deltas
function handleCancelOrderCallback(
CallbackState storage state,
ILimitOrderManager.CancelOrderCallbackData memory cancelData
) internal returns (bytes memory) {
(BalanceDelta callerDelta, BalanceDelta feeDelta) = _burnLimitOrder(
state,
cancelData.key,
cancelData.bottomTick,
cancelData.topTick,
cancelData.liquidity,
cancelData.isToken0
);
// Clear any remaining dust amounts
_clearExactDelta(state, cancelData.key.currency0);
_clearExactDelta(state, cancelData.key.currency1);
return abi.encode(callerDelta, feeDelta);
}
/// @notice Burns liquidity for a limit order and mints corresponding tokens to the LimitOrderManager
/// @param state The callback state containing pool manager reference
/// @param key The pool key identifying the specific Uniswap V4 pool
/// @param bottomTick The lower tick boundary of the position
/// @param topTick The upper tick boundary of the position
/// @param liquidity The amount of liquidity to burn
/// @param isToken0 Whether the position is for token0 or token1
/// @return callerDelta The net balance changes for the position owner
/// @return feeDelta The accumulated fees for the position
function _burnLimitOrder(
CallbackState storage state,
PoolKey memory key,
int24 bottomTick,
int24 topTick,
uint128 liquidity,
bool isToken0
) internal returns (BalanceDelta callerDelta, BalanceDelta feeDelta) {
(callerDelta, feeDelta) = state.poolManager.modifyLiquidity(
key,
ModifyLiquidityParams({
tickLower: bottomTick,
tickUpper: topTick,
liquidityDelta: -int128(liquidity),
salt: bytes32(uint256(isToken0 ? 0 : 1))
}),
""
);
int128 delta0 = callerDelta.amount0();
int128 delta1 = callerDelta.amount1();
if (delta0 > 0) {
state.poolManager.mint(
address(this),
uint256(uint160(Currency.unwrap(key.currency0))),
uint256(int256(delta0))
);
}
if (delta1 > 0) {
state.poolManager.mint(
address(this),
uint256(uint160(Currency.unwrap(key.currency1))),
uint256(int256(delta1))
);
}
}
/// @notice Handles the callback for creating one or more limit orders
/// @param state The callback state containing pool manager and fee settings
/// @param callbackData Struct containing order details
/// @return bytes ABI encoded arrays of balance deltas
function handleCreateOrdersCallback(
CallbackState storage state,
ILimitOrderManager.CreateOrdersCallbackData memory callbackData
) internal returns(bytes memory) {
// BalanceDelta[] memory deltas = new BalanceDelta[](callbackData.orders.length);
BalanceDelta[] memory feeDeltas = new BalanceDelta[](callbackData.orders.length);
BalanceDelta accumulatedMintFees;
unchecked {
for (uint256 i = 0; i < callbackData.orders.length; i++) {
ILimitOrderManager.OrderInfo memory order = callbackData.orders[i];
callbackData.isToken0 ?
callbackData.key.currency0.settle(state.poolManager, address(this), order.amount, false) :
callbackData.key.currency1.settle(state.poolManager, address(this), order.amount, false);
(, BalanceDelta feeDelta) = state.poolManager.modifyLiquidity(
callbackData.key,
ModifyLiquidityParams({
tickLower: order.bottomTick,
tickUpper: order.topTick,
liquidityDelta: int256(uint256(order.liquidity)),
salt: bytes32(uint256(callbackData.isToken0 ? 0 : 1))
}),
""
);
feeDeltas[i] = feeDelta;
if (feeDelta != ZERO_DELTA) {
accumulatedMintFees = accumulatedMintFees + feeDelta;
}
}
}
_mintFeesToHook(state, callbackData.key, accumulatedMintFees);
// Clear any remaining dust amounts
_clearExactDelta(state, callbackData.key.currency0);
_clearExactDelta(state, callbackData.key.currency1);
return abi.encode(feeDeltas);
}
// Internal helper functions
function _mintFeesToHook(
CallbackState storage state,
PoolKey memory key,
BalanceDelta feeDelta
) internal {
int128 fee0 = feeDelta.amount0();
int128 fee1 = feeDelta.amount1();
if (fee0 > 0) {
state.poolManager.mint(
address(this),
uint256(uint160(Currency.unwrap(key.currency0))),
uint256(int256(fee0))
);
}
if (fee1 > 0) {
state.poolManager.mint(
address(this),
uint256(uint160(Currency.unwrap(key.currency1))),
uint256(int256(fee1))
);
}
}
function _handleTokenTransfersAndFees(
CallbackState storage state,
uint256 principalAmount,
uint256 feeAmount,
Currency currency,
address user
) private {
if (principalAmount == 0 && feeAmount == 0) return;
uint256 currencyId = uint256(uint160(Currency.unwrap(currency)));
uint256 treasuryFee = FullMath.mulDiv(feeAmount, state.hookFeePercentage, state.feeDenominator);
uint256 userAmount = principalAmount + (feeAmount - treasuryFee);
if (userAmount > 0) {
state.poolManager.burn(address(this), currencyId, userAmount);
try state.poolManager.take(currency, user, userAmount) {
} catch {
state.poolManager.take(currency, state.treasury, userAmount);
emit FailedTransferSentToTreasury(currency, user, userAmount);
}
}
if (treasuryFee > 0) {
state.poolManager.burn(address(this), currencyId, treasuryFee);
state.poolManager.take(currency, state.treasury, treasuryFee);
}
}
function _clearExactDelta(CallbackState storage state, Currency currency) private {
int256 delta = state.poolManager.currencyDelta(address(this), currency);
if (delta > 0) {
state.poolManager.clear(currency, uint256(delta));
}
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS =
0x000000000000000000636F6e736F6c652e6c6f67;
function _sendLogPayloadImplementation(bytes memory payload) internal view {
address consoleAddress = CONSOLE_ADDRESS;
/// @solidity memory-safe-assembly
assembly {
pop(
staticcall(
gas(),
consoleAddress,
add(payload, 32),
mload(payload),
0,
0
)
)
}
}
function _castToPure(
function(bytes memory) internal view fnIn
) internal pure returns (function(bytes memory) pure fnOut) {
assembly {
fnOut := fnIn
}
}
function _sendLogPayload(bytes memory payload) internal pure {
_castToPure(_sendLogPayloadImplementation)(payload);
}
function log() internal pure {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int256 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(int256)", p0));
}
function logUint(uint256 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256)", p0));
}
function logString(string memory p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint256 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256)", p0));
}
function log(int256 p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(int256)", p0));
}
function log(string memory p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint256 p0, uint256 p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256)", p0, p1));
}
function log(uint256 p0, string memory p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string)", p0, p1));
}
function log(uint256 p0, bool p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool)", p0, p1));
}
function log(uint256 p0, address p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address)", p0, p1));
}
function log(string memory p0, uint256 p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256)", p0, p1));
}
function log(string memory p0, int256 p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,int256)", p0, p1));
}
function log(string memory p0, string memory p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint256 p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256)", p0, p1));
}
function log(bool p0, string memory p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint256 p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256)", p0, p1));
}
function log(address p0, string memory p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint256 p0, uint256 p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256)", p0, p1, p2));
}
function log(uint256 p0, uint256 p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string)", p0, p1, p2));
}
function log(uint256 p0, uint256 p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool)", p0, p1, p2));
}
function log(uint256 p0, uint256 p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address)", p0, p1, p2));
}
function log(uint256 p0, string memory p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256)", p0, p1, p2));
}
function log(uint256 p0, string memory p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,string)", p0, p1, p2));
}
function log(uint256 p0, string memory p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool)", p0, p1, p2));
}
function log(uint256 p0, string memory p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,address)", p0, p1, p2));
}
function log(uint256 p0, bool p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256)", p0, p1, p2));
}
function log(uint256 p0, bool p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string)", p0, p1, p2));
}
function log(uint256 p0, bool p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool)", p0, p1, p2));
}
function log(uint256 p0, bool p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address)", p0, p1, p2));
}
function log(uint256 p0, address p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256)", p0, p1, p2));
}
function log(uint256 p0, address p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,string)", p0, p1, p2));
}
function log(uint256 p0, address p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool)", p0, p1, p2));
}
function log(uint256 p0, address p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,address)", p0, p1, p2));
}
function log(string memory p0, uint256 p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256)", p0, p1, p2));
}
function log(string memory p0, uint256 p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,string)", p0, p1, p2));
}
function log(string memory p0, uint256 p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool)", p0, p1, p2));
}
function log(string memory p0, uint256 p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint256)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint256)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint256 p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256)", p0, p1, p2));
}
function log(bool p0, uint256 p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string)", p0, p1, p2));
}
function log(bool p0, uint256 p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool)", p0, p1, p2));
}
function log(bool p0, uint256 p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint256 p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256)", p0, p1, p2));
}
function log(address p0, uint256 p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,string)", p0, p1, p2));
}
function log(address p0, uint256 p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool)", p0, p1, p2));
}
function log(address p0, uint256 p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint256)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint256 p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint256)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint256 p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,string)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,address)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,string)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,address)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,string)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,address)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,string)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, uint256 p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,address)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,string)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,address)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,string)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,address)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,string)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,address)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,string)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, string memory p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,address)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,string)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,address)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,string)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,address)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,string)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, bool p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,address)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,string)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,address)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,string)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,address)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,string)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,address)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,uint256)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,string)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,bool)", p0, p1, p2, p3));
}
function log(uint256 p0, address p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint256 p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint256)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,uint256)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,string)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,address)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,uint256)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,uint256)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,uint256)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint256 p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,uint256)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint256)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint256)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint256)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,uint256)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint256)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint256)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint256)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,uint256)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint256)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint256)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint256)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,uint256)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,string)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,bool)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,address)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,uint256)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,uint256)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,uint256)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint256 p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,uint256)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint256)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint256)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint256)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,uint256)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint256)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint256)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint256)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint256 p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,uint256)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint256 p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint256 p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint256 p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint256)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint256)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint256 p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint256)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal pure {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BitMath} from "./BitMath.sol";
/// @title Packed tick initialized state library
/// @notice Stores a packed mapping of tick index to its initialized state
/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.
library TickBitmap {
/// @notice Thrown when the tick is not enumerated by the tick spacing
/// @param tick the invalid tick
/// @param tickSpacing The tick spacing of the pool
error TickMisaligned(int24 tick, int24 tickSpacing);
/// @dev round towards negative infinity
function compress(int24 tick, int24 tickSpacing) internal pure returns (int24 compressed) {
// compressed = tick / tickSpacing;
// if (tick < 0 && tick % tickSpacing != 0) compressed--;
assembly ("memory-safe") {
tick := signextend(2, tick)
tickSpacing := signextend(2, tickSpacing)
compressed :=
sub(
sdiv(tick, tickSpacing),
// if (tick < 0 && tick % tickSpacing != 0) then tick % tickSpacing < 0, vice versa
slt(smod(tick, tickSpacing), 0)
)
}
}
/// @notice Computes the position in the mapping where the initialized bit for a tick lives
/// @param tick The tick for which to compute the position
/// @return wordPos The key in the mapping containing the word in which the bit is stored
/// @return bitPos The bit position in the word where the flag is stored
function position(int24 tick) internal pure returns (int16 wordPos, uint8 bitPos) {
assembly ("memory-safe") {
// signed arithmetic shift right
wordPos := sar(8, signextend(2, tick))
bitPos := and(tick, 0xff)
}
}
/// @notice Flips the initialized state for a given tick from false to true, or vice versa
/// @param self The mapping in which to flip the tick
/// @param tick The tick to flip
/// @param tickSpacing The spacing between usable ticks
function flipTick(mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing) internal {
// Equivalent to the following Solidity:
// if (tick % tickSpacing != 0) revert TickMisaligned(tick, tickSpacing);
// (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing);
// uint256 mask = 1 << bitPos;
// self[wordPos] ^= mask;
assembly ("memory-safe") {
tick := signextend(2, tick)
tickSpacing := signextend(2, tickSpacing)
// ensure that the tick is spaced
if smod(tick, tickSpacing) {
let fmp := mload(0x40)
mstore(fmp, 0xd4d8f3e6) // selector for TickMisaligned(int24,int24)
mstore(add(fmp, 0x20), tick)
mstore(add(fmp, 0x40), tickSpacing)
revert(add(fmp, 0x1c), 0x44)
}
tick := sdiv(tick, tickSpacing)
// calculate the storage slot corresponding to the tick
// wordPos = tick >> 8
mstore(0, sar(8, tick))
mstore(0x20, self.slot)
// the slot of self[wordPos] is keccak256(abi.encode(wordPos, self.slot))
let slot := keccak256(0, 0x40)
// mask = 1 << bitPos = 1 << (tick % 256)
// self[wordPos] ^= mask
sstore(slot, xor(sload(slot), shl(and(tick, 0xff), 1)))
}
}
/// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either
/// to the left (less than or equal to) or right (greater than) of the given tick
/// @param self The mapping in which to compute the next initialized tick
/// @param tick The starting tick
/// @param tickSpacing The spacing between usable ticks
/// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)
/// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick
/// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks
function nextInitializedTickWithinOneWord(
mapping(int16 => uint256) storage self,
int24 tick,
int24 tickSpacing,
bool lte
) internal view returns (int24 next, bool initialized) {
unchecked {
int24 compressed = compress(tick, tickSpacing);
if (lte) {
(int16 wordPos, uint8 bitPos) = position(compressed);
// all the 1s at or to the right of the current bitPos
uint256 mask = type(uint256).max >> (uint256(type(uint8).max) - bitPos);
uint256 masked = self[wordPos] & mask;
// if there are no initialized ticks to the right of or at the current tick, return rightmost in the word
initialized = masked != 0;
// overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
next = initialized
? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing
: (compressed - int24(uint24(bitPos))) * tickSpacing;
} else {
// start from the word of the next tick, since the current tick state doesn't matter
(int16 wordPos, uint8 bitPos) = position(++compressed);
// all the 1s at or to the left of the bitPos
uint256 mask = ~((1 << bitPos) - 1);
uint256 masked = self[wordPos] & mask;
// if there are no initialized ticks to the left of the current tick, return leftmost in the word
initialized = masked != 0;
// overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
next = initialized
? (compressed + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing
: (compressed + int24(uint24(type(uint8).max - bitPos))) * tickSpacing;
}
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then 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 = a * b; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
assembly ("memory-safe") {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly ("memory-safe") {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (0 - denominator) & denominator;
// Divide denominator by power of two
assembly ("memory-safe") {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly ("memory-safe") {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly ("memory-safe") {
twos := add(div(sub(0, twos), twos), 1)
}
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
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use 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.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // 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 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) != 0) {
require(++result > 0);
}
}
}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
import "../../src/libraries/FullMath.sol";
import "../../src/libraries/FixedPoint96.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x, "liquidity overflow");
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount0)
internal
pure
returns (uint128 liquidity)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
uint256 intermediate = FullMath.mulDiv(sqrtPriceAX96, sqrtPriceBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtPriceBX96 - sqrtPriceAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount1)
internal
pure
returns (uint128 liquidity)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtPriceBX96 - sqrtPriceAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtPriceX96 A sqrt price representing the current pool prices
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtPriceX96,
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
if (sqrtPriceX96 <= sqrtPriceAX96) {
liquidity = getLiquidityForAmount0(sqrtPriceAX96, sqrtPriceBX96, amount0);
} else if (sqrtPriceX96 < sqrtPriceBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtPriceX96, sqrtPriceBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity)
internal
pure
returns (uint256 amount0)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtPriceBX96 - sqrtPriceAX96, sqrtPriceBX96
) / sqrtPriceAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity)
internal
pure
returns (uint256 amount1)
{
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtPriceX96 A sqrt price representing the current pool prices
/// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
/// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtPriceX96,
uint160 sqrtPriceAX96,
uint160 sqrtPriceBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
if (sqrtPriceX96 <= sqrtPriceAX96) {
amount0 = getAmount0ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
} else if (sqrtPriceX96 < sqrtPriceBX96) {
amount0 = getAmount0ForLiquidity(sqrtPriceX96, sqrtPriceBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable
struct OwnableStorage {
address _owner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;
function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
assembly {
$.slot := OwnableStorageLocation
}
}
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
function __Ownable_init(address initialOwner) internal onlyInitializing {
__Ownable_init_unchained(initialOwner);
}
function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
OwnableStorage storage $ = _getOwnableStorage();
return $._owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
OwnableStorage storage $ = _getOwnableStorage();
address oldOwner = $._owner;
$._owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
AccessControlStorage storage $ = _getAccessControlStorage();
bytes32 previousAdminRole = getRoleAdmin(role);
$._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
* See {_onlyProxy}.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {BeforeSwapDelta} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {ImmutableState} from "../base/ImmutableState.sol";
import {ModifyLiquidityParams, SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
/// @title Base Hook
/// @notice abstract contract for hook implementations
abstract contract BaseHook is IHooks, ImmutableState {
error HookNotImplemented();
constructor(IPoolManager _manager) ImmutableState(_manager) {
validateHookAddress(this);
}
/// @notice Returns a struct of permissions to signal which hook functions are to be implemented
/// @dev Used at deployment to validate the address correctly represents the expected permissions
/// @return Permissions struct
function getHookPermissions() public pure virtual returns (Hooks.Permissions memory);
/// @notice Validates the deployed hook address agrees with the expected permissions of the hook
/// @dev this function is virtual so that we can override it during testing,
/// which allows us to deploy an implementation to any address
/// and then etch the bytecode into the correct address
function validateHookAddress(BaseHook _this) internal pure virtual {
Hooks.validateHookPermissions(_this, getHookPermissions());
}
/// @inheritdoc IHooks
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96)
external
onlyPoolManager
returns (bytes4)
{
return _beforeInitialize(sender, key, sqrtPriceX96);
}
function _beforeInitialize(address, PoolKey calldata, uint160) internal virtual returns (bytes4) {
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
onlyPoolManager
returns (bytes4)
{
return _afterInitialize(sender, key, sqrtPriceX96, tick);
}
function _afterInitialize(address, PoolKey calldata, uint160, int24) internal virtual returns (bytes4) {
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external onlyPoolManager returns (bytes4) {
return _beforeAddLiquidity(sender, key, params, hookData);
}
function _beforeAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
internal
virtual
returns (bytes4)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external onlyPoolManager returns (bytes4) {
return _beforeRemoveLiquidity(sender, key, params, hookData);
}
function _beforeRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
internal
virtual
returns (bytes4)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external onlyPoolManager returns (bytes4, BalanceDelta) {
return _afterAddLiquidity(sender, key, params, delta, feesAccrued, hookData);
}
function _afterAddLiquidity(
address,
PoolKey calldata,
ModifyLiquidityParams calldata,
BalanceDelta,
BalanceDelta,
bytes calldata
) internal virtual returns (bytes4, BalanceDelta) {
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external onlyPoolManager returns (bytes4, BalanceDelta) {
return _afterRemoveLiquidity(sender, key, params, delta, feesAccrued, hookData);
}
function _afterRemoveLiquidity(
address,
PoolKey calldata,
ModifyLiquidityParams calldata,
BalanceDelta,
BalanceDelta,
bytes calldata
) internal virtual returns (bytes4, BalanceDelta) {
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
onlyPoolManager
returns (bytes4, BeforeSwapDelta, uint24)
{
return _beforeSwap(sender, key, params, hookData);
}
function _beforeSwap(address, PoolKey calldata, SwapParams calldata, bytes calldata)
internal
virtual
returns (bytes4, BeforeSwapDelta, uint24)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external onlyPoolManager returns (bytes4, int128) {
return _afterSwap(sender, key, params, delta, hookData);
}
function _afterSwap(address, PoolKey calldata, SwapParams calldata, BalanceDelta, bytes calldata)
internal
virtual
returns (bytes4, int128)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external onlyPoolManager returns (bytes4) {
return _beforeDonate(sender, key, amount0, amount1, hookData);
}
function _beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
internal
virtual
returns (bytes4)
{
revert HookNotImplemented();
}
/// @inheritdoc IHooks
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external onlyPoolManager returns (bytes4) {
return _afterDonate(sender, key, amount0, amount1, hookData);
}
function _afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
internal
virtual
returns (bytes4)
{
revert HookNotImplemented();
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice A BeforeSwapDelta of 0
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// returned by beforeSwap
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// returned by beforeSwap and afterSwap
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represent a slot holding a address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {Hooks} from "v4-core/libraries/Hooks.sol";
import {BaseHook} from "v4-periphery/src/utils/BaseHook.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {BalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {BeforeSwapDelta} from "v4-core/types/BeforeSwapDelta.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {SwapParams} from "v4-core/types/PoolOperation.sol";
import {TransientSlot} from "openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol";
import {ILimitOrderManager} from "../interfaces/ILimitOrderManager.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import {BeforeSwapDeltaLibrary} from "v4-core/types/BeforeSwapDelta.sol";
contract DynamicFeeLimitOrderHook is BaseHook, Ownable {
using PoolIdLibrary for PoolKey;
uint24 public constant MAX_LP_FEE = 20_000; // 2% max fee
ILimitOrderManager public immutable limitOrderManager;
address public immutable creator;
address public orderBookFactory;
// Track which pools this hook manages
mapping(PoolId => bool) public managedPools;
// Track if creator already created a pool with specific parameters
mapping(bytes32 => bool) public poolParametersUsed;
// Track trading enabled block per pool (1-block delay)
mapping(PoolId => uint256) public tradingEnabledBlock;
// Errors
error TradingNotYetEnabled(uint256 enabledBlock, uint256 currentBlock);
// Events
event DynamicLPFeeUpdated(PoolId indexed poolId, uint24 newFee);
/// @notice Get pool-specific transient storage slot for previous tick
/// @dev Each pool gets unique slot to avoid collisions in multi-pool transactions
function _getPreviousTickSlot(PoolId poolId) private pure returns (bytes32) {
return keccak256(abi.encodePacked("xyz.hooks.dynamicfee.previous-tick", poolId));
}
constructor(IPoolManager _poolManager, address _limitOrderManager, address _creator, address _orderBookFactory) BaseHook(_poolManager) Ownable(_creator) {
require(_limitOrderManager != address(0), "ZeroAddress");
require(_creator != address(0), "ZeroAddress");
require(_orderBookFactory != address(0), "ZeroAddress");
limitOrderManager = ILimitOrderManager(_limitOrderManager);
creator = _creator;
orderBookFactory = _orderBookFactory;
}
function getHookPermissions() public pure override returns (Hooks.Permissions memory) {
return Hooks.Permissions({
beforeInitialize: false,
afterInitialize: false,
beforeAddLiquidity: false,
afterAddLiquidity: false,
beforeRemoveLiquidity: false,
afterRemoveLiquidity: false,
beforeSwap: true,
afterSwap: true,
beforeDonate: false,
afterDonate: false,
beforeSwapReturnDelta: false,
afterSwapReturnDelta: false,
afterAddLiquidityReturnDelta: false,
afterRemoveLiquidityReturnDelta: false
});
}
function _beforeSwap(
address,
PoolKey calldata key,
SwapParams calldata params,
bytes calldata
) internal override returns (bytes4, BeforeSwapDelta, uint24) {
PoolId poolId = key.toId();
// Enforce 1-block delay before trading is enabled
uint256 enabledBlock = tradingEnabledBlock[poolId];
if (enabledBlock > 0) {
if (block.number < enabledBlock) {
revert TradingNotYetEnabled(enabledBlock, block.number);
}
// Delete storage slot after first successful trade to save gas on future swaps
delete tradingEnabledBlock[poolId];
}
(,int24 tickBeforeSwap,,) = StateLibrary.getSlot0(poolManager, poolId);
bytes32 slot = _getPreviousTickSlot(poolId);
assembly ("memory-safe") {
tstore(slot, tickBeforeSwap)
}
return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
}
function _afterSwap(
address,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta,
bytes calldata
) internal override returns (bytes4, int128) {
PoolId poolId = key.toId();
(,int24 tickAfterSwap,,) = StateLibrary.getSlot0(poolManager, poolId);
int24 tickBeforeSwap;
bytes32 slot = _getPreviousTickSlot(poolId);
assembly ("memory-safe") {
tickBeforeSwap := tload(slot)
}
limitOrderManager.executeOrder(key, tickBeforeSwap, tickAfterSwap, params.zeroForOne);
return (BaseHook.afterSwap.selector, 0);
}
function updateDynamicLPFee(PoolKey calldata key, uint24 newFee) external {
require(msg.sender == orderBookFactory || msg.sender == owner(), "NotAuthorized");
require(managedPools[key.toId()], "NotManagedPool");
require(newFee <= MAX_LP_FEE, "FeeExceedsMaximum");
poolManager.updateDynamicLPFee(key, newFee);
emit DynamicLPFeeUpdated(key.toId(), newFee);
}
function registerPool(PoolKey calldata key) external {
require(msg.sender == orderBookFactory, "OnlyOrderBookFactory");
PoolId poolId = key.toId();
// Create a unique identifier for the pool parameters
bytes32 parametersHash = keccak256(abi.encodePacked(
Currency.unwrap(key.currency0),
Currency.unwrap(key.currency1),
key.tickSpacing
));
require(!poolParametersUsed[parametersHash], "PoolParametersAlreadyUsed");
managedPools[poolId] = true;
poolParametersUsed[parametersHash] = true;
// Set trading enabled block (1-block delay)
tradingEnabledBlock[poolId] = block.number + 1;
}
function getDynamicLPFee(PoolKey calldata key) external view returns (uint24) {
(, , , uint24 lpFee) = StateLibrary.getSlot0(poolManager, key.toId());
return lpFee;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {Hooks} from "v4-core/libraries/Hooks.sol";
import {BaseHook} from "v4-periphery/src/utils/BaseHook.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {BalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {BeforeSwapDelta} from "v4-core/types/BeforeSwapDelta.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {SwapParams} from "v4-core/types/PoolOperation.sol";
import {TransientSlot} from "openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol";
import {ILimitOrderManager} from "../interfaces/ILimitOrderManager.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import {BeforeSwapDeltaLibrary, toBeforeSwapDelta} from "v4-core/types/BeforeSwapDelta.sol";
import {SafeCast} from "v4-core/libraries/SafeCast.sol";
import {FixedPointMathLib} from "solmate/src/utils/FixedPointMathLib.sol";
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {IOrderBookFactory} from "../interfaces/IOrderBookFactory.sol";
import {VolatilityOracle} from "../libraries/VolatilityOracle.sol";
/// @title VolatilityDynamicFeeLimitOrderHook
/// @notice Hook with fixed base fee + surge fee on CAP events + limit order execution
/// @dev Uses VolatilityOracle for CAP detection and limit order execution
contract VolatilityDynamicFeeLimitOrderHook is BaseHook, Ownable {
using PoolIdLibrary for PoolKey;
using TransientSlot for *;
using SafeCast for *;
using FixedPointMathLib for uint256;
uint256 private constant FEE_DENOMINATOR = 1_000_000; // For fee calculations
uint256 private constant BPS_DENOMINATOR = 10_000; // For surge multiplier
ILimitOrderManager public immutable limitOrderManager;
VolatilityOracle public immutable volatilityOracle;
address public immutable creator;
address public orderBookFactory;
// Track which pools this hook manages
mapping(PoolId => bool) public managedPools;
// Track if creator already created a pool with specific parameters
mapping(bytes32 => bool) public poolParametersUsed;
// Track trading enabled block per pool (1-block delay)
mapping(PoolId => uint256) public tradingEnabledBlock;
// Fee parameters per pool
struct FeeParams {
uint24 baseFee; // Fixed base fee set by user (never changes)
bool enabled; // Whether dynamic fees are active
}
mapping(PoolId => FeeParams) public feeParams;
// Surge fee state per pool
struct SurgeState {
uint24 surgeMultiplier; // bps (e.g., 30000 = 3x base fee)
uint32 surgeDuration; // decay window in seconds (e.g., 3600 = 1 hour)
uint32 capStartTime; // timestamp when CAP was triggered
bool isActive; // is surge mode active
}
mapping(PoolId => SurgeState) public surgeStates;
// System-wide default oracle policy parameters
// Applied to all new pools unless overridden via updateOraclePolicy()
uint24 public defaultMinCap = 10;
uint24 public defaultMaxCap = 1000;
uint32 public defaultStepPpm = 20000; // 2%
uint32 public defaultBudgetPpm = 1000000; // 100% = 1 CAP/day target
uint32 public defaultDecayWindow = 15552000; // 180 days
uint32 public defaultUpdateInterval = 86400; // 24 hours
// Errors
error TradingNotYetEnabled(uint256 enabledBlock, uint256 currentBlock);
error PoolReservedForOther();
// Events
event DynamicLPFeeUpdated(PoolId indexed poolId, uint24 newFee, uint24 surgeFee);
event FeeParamsUpdated(PoolId indexed poolId, uint24 baseFee);
event CAPDetected(PoolId indexed poolId, uint32 timestamp, int24 tickDelta);
event SurgeFeeApplied(PoolId indexed poolId, uint24 surgeFee, uint32 timeRemaining);
event SurgeDeactivated(PoolId indexed poolId, uint32 timestamp);
event PoolRegistered(
PoolId indexed poolId,
uint24 baseFee,
uint24 surgeMultiplier,
uint32 surgeDuration,
uint24 initialMaxTicksPerBlock
);
event DefaultOraclePolicyUpdated(
uint24 minCap,
uint24 maxCap,
uint32 stepPpm,
uint32 budgetPpm,
uint32 decayWindow,
uint32 updateInterval
);
/// @notice Get pool-specific transient storage slot for previous tick
/// @dev Each pool gets unique slot to avoid collisions in multi-pool transactions
function _getPreviousTickSlot(PoolId poolId) private pure returns (bytes32) {
return keccak256(abi.encodePacked("xyz.hooks.volatility.previous-tick", poolId));
}
constructor(
IPoolManager _poolManager,
address _limitOrderManager,
address _volatilityOracle,
address _creator,
address _orderBookFactory
) BaseHook(_poolManager) Ownable(_creator) {
if (_limitOrderManager == address(0)) revert("ZeroAddress");
if (_volatilityOracle == address(0)) revert("ZeroAddress");
if (_creator == address(0)) revert("ZeroAddress");
if (_orderBookFactory == address(0)) revert("ZeroAddress");
limitOrderManager = ILimitOrderManager(_limitOrderManager);
volatilityOracle = VolatilityOracle(_volatilityOracle);
creator = _creator;
orderBookFactory = _orderBookFactory;
}
function getHookPermissions() public pure override returns (Hooks.Permissions memory) {
return Hooks.Permissions({
beforeInitialize: true, // Check pool reservation for front-running protection
afterInitialize: false,
beforeAddLiquidity: false,
afterAddLiquidity: false,
beforeRemoveLiquidity: false,
afterRemoveLiquidity: false,
beforeSwap: true, // Calculate and apply surge fee
afterSwap: true, // Execute limit orders + detect CAPs
beforeDonate: false,
afterDonate: false,
beforeSwapReturnDelta: false,
afterSwapReturnDelta: false,
afterAddLiquidityReturnDelta: false,
afterRemoveLiquidityReturnDelta: false
});
}
/// @notice Validates pool initialization - enforces reservation system for front-running protection
/// @dev If a pool is reserved, only the reserved strategy or OrderBookFactory can initialize it.
/// Unreserved pools remain permissionless.
/// @param sender The address that called poolManager.initialize()
/// @param key The pool key being initialized
function _beforeInitialize(address sender, PoolKey calldata key, uint160)
internal
override
returns (bytes4)
{
bytes32 poolId = PoolId.unwrap(key.toId());
address reservedFor = IOrderBookFactory(orderBookFactory).reservedPools(poolId);
// If pool is reserved, only the reserved strategy or OrderBookFactory can initialize
if (reservedFor != address(0)) {
if (sender != reservedFor && sender != orderBookFactory) {
revert PoolReservedForOther();
}
}
// If not reserved, anyone can initialize (permissionless)
return this.beforeInitialize.selector;
}
function _beforeSwap(
address,
PoolKey calldata key,
SwapParams calldata params,
bytes calldata
) internal override returns (bytes4, BeforeSwapDelta, uint24) {
PoolId poolId = key.toId();
// Enforce 1-block delay before trading is enabled
uint256 enabledBlock = tradingEnabledBlock[poolId];
if (enabledBlock > 0) {
if (block.number < enabledBlock) {
revert TradingNotYetEnabled(enabledBlock, block.number);
}
// Delete storage slot after first successful trade to save gas on future swaps
delete tradingEnabledBlock[poolId];
}
uint24 lpFee;
{
(,int24 tickBeforeSwap,,uint24 fee) = StateLibrary.getSlot0(poolManager, poolId);
lpFee = fee;
bytes32 slot = _getPreviousTickSlot(poolId);
assembly ("memory-safe") {
tstore(slot, tickBeforeSwap)
}
}
FeeParams memory params_ = feeParams[poolId];
if (!params_.enabled) {
return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
}
uint24 totalFee;
{
SurgeState storage surge = surgeStates[poolId];
uint24 surgeFee = 0;
if (surge.isActive) {
uint32 elapsed = uint32(block.timestamp) - surge.capStartTime;
if (elapsed >= surge.surgeDuration) {
surge.isActive = false;
emit SurgeDeactivated(poolId, uint32(block.timestamp));
} else {
uint32 remaining = surge.surgeDuration - elapsed;
surgeFee = uint24(
(uint256(params_.baseFee) * surge.surgeMultiplier * remaining / surge.surgeDuration) / BPS_DENOMINATOR
);
emit SurgeFeeApplied(poolId, surgeFee, remaining);
}
}
totalFee = params_.baseFee + surgeFee;
if (totalFee != lpFee) {
poolManager.updateDynamicLPFee(key, totalFee);
emit DynamicLPFeeUpdated(poolId, totalFee, surgeFee);
}
}
return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
}
function _afterSwap(
address,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta,
bytes calldata
) internal override returns (bytes4, int128) {
PoolId poolId = key.toId();
(,int24 tickAfterSwap,,) = StateLibrary.getSlot0(poolManager, poolId);
int24 tickBeforeSwap;
{
bytes32 slot = _getPreviousTickSlot(poolId);
assembly ("memory-safe") {
tickBeforeSwap := tload(slot)
}
}
// Execute limit orders
limitOrderManager.executeOrder(key, tickBeforeSwap, tickAfterSwap, params.zeroForOne);
// Check for CAP event
bool wasCapped = volatilityOracle.pushObservationAndCheckCap(poolId, tickBeforeSwap);
if (wasCapped) {
// CAP detected - activate surge mode
surgeStates[poolId].isActive = true;
surgeStates[poolId].capStartTime = uint32(block.timestamp);
emit CAPDetected(poolId, uint32(block.timestamp), tickAfterSwap - tickBeforeSwap);
}
return (BaseHook.afterSwap.selector, 0);
}
/// @notice Register a pool with fixed base fee and surge parameters
/// @param key The pool key
/// @param baseFee Fixed base fee (user-set, e.g., 3000 = 0.3%)
/// @param surgeMultiplier Surge fee multiplier in bps (e.g., 30000 = 3x)
/// @param surgeDuration Surge decay duration in seconds (e.g., 3600 = 1 hour)
/// @param initialMaxTicksPerBlock Initial CAP threshold (e.g., 50)
function registerPool(
PoolKey calldata key,
uint24 baseFee,
uint24 surgeMultiplier,
uint32 surgeDuration,
uint24 initialMaxTicksPerBlock
) external {
if (msg.sender != orderBookFactory) revert("OnlyOrderBookFactory");
PoolId poolId = key.toId();
// Create a unique identifier for the pool parameters
bytes32 parametersHash = keccak256(abi.encodePacked(
Currency.unwrap(key.currency0),
Currency.unwrap(key.currency1),
key.tickSpacing
));
if (poolParametersUsed[parametersHash]) revert("PoolParametersAlreadyUsed");
managedPools[poolId] = true;
poolParametersUsed[parametersHash] = true;
// Set fixed base fee
feeParams[poolId] = FeeParams({
baseFee: baseFee,
enabled: true
});
// Set surge parameters
surgeStates[poolId] = SurgeState({
surgeMultiplier: surgeMultiplier,
surgeDuration: surgeDuration,
capStartTime: 0,
isActive: false
});
// Initialize oracle with system-wide default policy params
// (owner can update defaults via updateDefaultOraclePolicy() or override specific pools via updateOraclePolicy())
volatilityOracle.enableOracleForPool(
key,
initialMaxTicksPerBlock, // user-set initial maxTicksPerBlock
defaultMinCap, // system default
defaultMaxCap, // system default
defaultStepPpm, // system default
defaultBudgetPpm, // system default
defaultDecayWindow, // system default
defaultUpdateInterval // system default
);
// Set trading enabled block (1-block delay)
tradingEnabledBlock[poolId] = block.number + 1;
emit PoolRegistered(poolId, baseFee, surgeMultiplier, surgeDuration, initialMaxTicksPerBlock);
}
/// @notice Update base fee for a pool (owner only)
/// @param key The pool key
/// @param newBaseFee New fixed base fee
function updateBaseFee(PoolKey calldata key, uint24 newBaseFee) external onlyOwner {
PoolId poolId = key.toId();
if (!managedPools[poolId]) revert("NotManagedPool");
feeParams[poolId].baseFee = newBaseFee;
emit FeeParamsUpdated(poolId, newBaseFee);
}
/// @notice Update surge parameters for a pool (owner only)
/// @param key The pool key
/// @param multiplier New surge multiplier in bps
/// @param duration New surge duration in seconds
function updateSurgeParams(
PoolKey calldata key,
uint24 multiplier,
uint32 duration
) external onlyOwner {
PoolId poolId = key.toId();
if (!managedPools[poolId]) revert("NotManagedPool");
surgeStates[poolId].surgeMultiplier = multiplier;
surgeStates[poolId].surgeDuration = duration;
}
/// @notice Update oracle policy parameters (owner only)
/// @param key The pool key
/// @param minCap Minimum maxTicksPerBlock
/// @param maxCap Maximum maxTicksPerBlock
/// @param stepPpm Auto-tune step size in PPM
/// @param budgetPpm Target CAP frequency in PPM
/// @param decayWindow Frequency decay window in seconds
/// @param updateInterval Min time between auto-tune adjustments
function updateOraclePolicy(
PoolKey calldata key,
uint24 minCap,
uint24 maxCap,
uint32 stepPpm,
uint32 budgetPpm,
uint32 decayWindow,
uint32 updateInterval
) external onlyOwner {
PoolId poolId = key.toId();
if (!managedPools[poolId]) revert("NotManagedPool");
volatilityOracle.refreshPolicyCache(
poolId,
minCap,
maxCap,
stepPpm,
budgetPpm,
decayWindow,
updateInterval
);
}
/// @notice Update system-wide default oracle policy parameters (owner only)
/// @dev These defaults apply to all future pool registrations
/// @param minCap Minimum maxTicksPerBlock
/// @param maxCap Maximum maxTicksPerBlock
/// @param stepPpm Auto-tune step size in PPM
/// @param budgetPpm Target CAP frequency in PPM
/// @param decayWindow Frequency decay window in seconds
/// @param updateInterval Min time between auto-tune adjustments
function updateDefaultOraclePolicy(
uint24 minCap,
uint24 maxCap,
uint32 stepPpm,
uint32 budgetPpm,
uint32 decayWindow,
uint32 updateInterval
) external onlyOwner {
defaultMinCap = minCap;
defaultMaxCap = maxCap;
defaultStepPpm = stepPpm;
defaultBudgetPpm = budgetPpm;
defaultDecayWindow = decayWindow;
defaultUpdateInterval = updateInterval;
emit DefaultOraclePolicyUpdated(minCap, maxCap, stepPpm, budgetPpm, decayWindow, updateInterval);
}
/// @notice Pause/unpause auto-tuning for a pool (owner only)
/// @param key The pool key
/// @param paused True to pause, false to unpause
function pauseAutoTune(PoolKey calldata key, bool paused) external onlyOwner {
PoolId poolId = key.toId();
if (!managedPools[poolId]) revert("NotManagedPool");
volatilityOracle.setAutoTunePaused(poolId, paused);
}
/// @notice Observe TWAP ticks at specified times (forwards to oracle)
/// @param key The pool key
/// @param secondsAgo0 First time point
/// @param secondsAgo1 Second time point
/// @return tickCumulative0 First tick cumulative
/// @return tickCumulative1 Second tick cumulative
function observe(PoolKey calldata key, uint32 secondsAgo0, uint32 secondsAgo1)
external
view
returns (int56 tickCumulative0, int56 tickCumulative1)
{
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = secondsAgo0;
secondsAgos[1] = secondsAgo1;
(int56[] memory tickCumulatives,) = volatilityOracle.observe(key, secondsAgos);
return (tickCumulatives[0], tickCumulatives[1]);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {Hooks} from "v4-core/libraries/Hooks.sol";
import {BaseHook} from "v4-periphery/src/utils/BaseHook.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {BeforeSwapDelta} from "v4-core/types/BeforeSwapDelta.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {SwapParams} from "v4-core/types/PoolOperation.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import {BeforeSwapDeltaLibrary} from "v4-core/types/BeforeSwapDelta.sol";
/// @title DynamicFeeHook
/// @notice Hook with dynamic fee updates only (no limit order functionality)
/// @dev Does not integrate with LimitOrderManager - purely for fee management
contract DynamicFeeHook is BaseHook, Ownable {
using PoolIdLibrary for PoolKey;
uint24 public constant MAX_LP_FEE = 20_000; // 2% max fee
address public immutable creator;
address public orderBookFactory;
// Track which pools this hook manages
mapping(PoolId => bool) public managedPools;
// Track if creator already created a pool with specific parameters
mapping(bytes32 => bool) public poolParametersUsed;
// Track trading enabled block per pool (1-block delay)
mapping(PoolId => uint256) public tradingEnabledBlock;
// Errors
error TradingNotYetEnabled(uint256 enabledBlock, uint256 currentBlock);
// Events
event DynamicLPFeeUpdated(PoolId indexed poolId, uint24 newFee);
constructor(
IPoolManager _poolManager,
address _creator,
address _orderBookFactory
) BaseHook(_poolManager) Ownable(_creator) {
require(_creator != address(0), "ZeroAddress");
require(_orderBookFactory != address(0), "ZeroAddress");
creator = _creator;
orderBookFactory = _orderBookFactory;
}
function getHookPermissions() public pure override returns (Hooks.Permissions memory) {
return Hooks.Permissions({
beforeInitialize: false,
afterInitialize: false,
beforeAddLiquidity: false,
afterAddLiquidity: false,
beforeRemoveLiquidity: false,
afterRemoveLiquidity: false,
beforeSwap: true,
afterSwap: false, // No afterSwap - no limit order execution
beforeDonate: false,
afterDonate: false,
beforeSwapReturnDelta: false,
afterSwapReturnDelta: false,
afterAddLiquidityReturnDelta: false,
afterRemoveLiquidityReturnDelta: false
});
}
function _beforeSwap(
address,
PoolKey calldata key,
SwapParams calldata,
bytes calldata
) internal override returns (bytes4, BeforeSwapDelta, uint24) {
PoolId poolId = key.toId();
// Enforce 1-block delay before trading is enabled
uint256 enabledBlock = tradingEnabledBlock[poolId];
if (enabledBlock > 0) {
if (block.number < enabledBlock) {
revert TradingNotYetEnabled(enabledBlock, block.number);
}
// Delete storage slot after first successful trade to save gas on future swaps
delete tradingEnabledBlock[poolId];
}
return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
}
function updateDynamicLPFee(PoolKey calldata key, uint24 newFee) external {
require(msg.sender == orderBookFactory || msg.sender == owner(), "NotAuthorized");
require(managedPools[key.toId()], "NotManagedPool");
require(newFee <= MAX_LP_FEE, "FeeExceedsMaximum");
poolManager.updateDynamicLPFee(key, newFee);
emit DynamicLPFeeUpdated(key.toId(), newFee);
}
function registerPool(PoolKey calldata key) external {
require(msg.sender == orderBookFactory, "OnlyOrderBookFactory");
PoolId poolId = key.toId();
// Create a unique identifier for the pool parameters
bytes32 parametersHash = keccak256(abi.encodePacked(
Currency.unwrap(key.currency0),
Currency.unwrap(key.currency1),
key.tickSpacing
));
require(!poolParametersUsed[parametersHash], "PoolParametersAlreadyUsed");
managedPools[poolId] = true;
poolParametersUsed[parametersHash] = true;
// Set trading enabled block (1-block delay)
tradingEnabledBlock[poolId] = block.number + 1;
}
function getDynamicLPFee(PoolKey calldata key) external view returns (uint24) {
(, , , uint24 lpFee) = StateLibrary.getSlot0(poolManager, key.toId());
return lpFee;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {Hooks} from "v4-core/libraries/Hooks.sol";
import {BaseHook} from "v4-periphery/src/utils/BaseHook.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {BalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {BeforeSwapDelta} from "v4-core/types/BeforeSwapDelta.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {SwapParams} from "v4-core/types/PoolOperation.sol";
import {TransientSlot} from "openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import {BeforeSwapDeltaLibrary} from "v4-core/types/BeforeSwapDelta.sol";
import {SafeCast} from "v4-core/libraries/SafeCast.sol";
import {FixedPointMathLib} from "solmate/src/utils/FixedPointMathLib.sol";
import {VolatilityOracle} from "../libraries/VolatilityOracle.sol";
/// @title VolatilityDynamicFeeHook
/// @notice Hook with fixed base fee + surge fee on CAP events (no limit order functionality)
/// @dev Uses VolatilityOracle for CAP detection but does not execute limit orders
contract VolatilityDynamicFeeHook is BaseHook, Ownable {
using PoolIdLibrary for PoolKey;
using TransientSlot for *;
using SafeCast for *;
using FixedPointMathLib for uint256;
uint256 private constant BPS_DENOMINATOR = 10_000; // For surge multiplier
VolatilityOracle public immutable volatilityOracle;
address public immutable creator;
address public orderBookFactory;
// Track which pools this hook manages
mapping(PoolId => bool) public managedPools;
// Track if creator already created a pool with specific parameters
mapping(bytes32 => bool) public poolParametersUsed;
// Track trading enabled block per pool (1-block delay)
mapping(PoolId => uint256) public tradingEnabledBlock;
// Fee parameters per pool
struct FeeParams {
uint24 baseFee; // Fixed base fee set by user (never changes)
bool enabled; // Whether dynamic fees are active
}
mapping(PoolId => FeeParams) public feeParams;
// Surge fee state per pool
struct SurgeState {
uint24 surgeMultiplier; // bps (e.g., 30000 = 3x base fee)
uint32 surgeDuration; // decay window in seconds (e.g., 3600 = 1 hour)
uint32 capStartTime; // timestamp when CAP was triggered
bool isActive; // is surge mode active
}
mapping(PoolId => SurgeState) public surgeStates;
// System-wide default oracle policy parameters
uint24 public defaultMinCap = 10;
uint24 public defaultMaxCap = 1000;
uint32 public defaultStepPpm = 20000; // 2%
uint32 public defaultBudgetPpm = 1000000; // 100% = 1 CAP/day target
uint32 public defaultDecayWindow = 15552000; // 180 days
uint32 public defaultUpdateInterval = 86400; // 24 hours
// Errors
error TradingNotYetEnabled(uint256 enabledBlock, uint256 currentBlock);
// Events
event DynamicLPFeeUpdated(PoolId indexed poolId, uint24 newFee, uint24 surgeFee);
event FeeParamsUpdated(PoolId indexed poolId, uint24 baseFee);
event CAPDetected(PoolId indexed poolId, uint32 timestamp, int24 tickDelta);
event SurgeFeeApplied(PoolId indexed poolId, uint24 surgeFee, uint32 timeRemaining);
event SurgeDeactivated(PoolId indexed poolId, uint32 timestamp);
event PoolRegistered(
PoolId indexed poolId,
uint24 baseFee,
uint24 surgeMultiplier,
uint32 surgeDuration,
uint24 initialMaxTicksPerBlock
);
event DefaultOraclePolicyUpdated(
uint24 minCap,
uint24 maxCap,
uint32 stepPpm,
uint32 budgetPpm,
uint32 decayWindow,
uint32 updateInterval
);
/// @notice Get pool-specific transient storage slot for previous tick
/// @dev Each pool gets unique slot to avoid collisions in multi-pool transactions
function _getPreviousTickSlot(PoolId poolId) private pure returns (bytes32) {
return keccak256(abi.encodePacked("xyz.hooks.volatility.fee.previous-tick", poolId));
}
constructor(
IPoolManager _poolManager,
address _volatilityOracle,
address _creator,
address _orderBookFactory
) BaseHook(_poolManager) Ownable(_creator) {
if (_volatilityOracle == address(0)) revert("ZeroAddress");
if (_creator == address(0)) revert("ZeroAddress");
if (_orderBookFactory == address(0)) revert("ZeroAddress");
volatilityOracle = VolatilityOracle(_volatilityOracle);
creator = _creator;
orderBookFactory = _orderBookFactory;
}
function getHookPermissions() public pure override returns (Hooks.Permissions memory) {
return Hooks.Permissions({
beforeInitialize: false, // No pool reservation for fee-only hook
afterInitialize: false,
beforeAddLiquidity: false,
afterAddLiquidity: false,
beforeRemoveLiquidity: false,
afterRemoveLiquidity: false,
beforeSwap: true, // Calculate and apply surge fee
afterSwap: true, // Detect CAPs (no limit order execution)
beforeDonate: false,
afterDonate: false,
beforeSwapReturnDelta: false,
afterSwapReturnDelta: false,
afterAddLiquidityReturnDelta: false,
afterRemoveLiquidityReturnDelta: false
});
}
function _beforeSwap(
address,
PoolKey calldata key,
SwapParams calldata,
bytes calldata
) internal override returns (bytes4, BeforeSwapDelta, uint24) {
PoolId poolId = key.toId();
// Enforce 1-block delay before trading is enabled
uint256 enabledBlock = tradingEnabledBlock[poolId];
if (enabledBlock > 0) {
if (block.number < enabledBlock) {
revert TradingNotYetEnabled(enabledBlock, block.number);
}
// Delete storage slot after first successful trade to save gas on future swaps
delete tradingEnabledBlock[poolId];
}
uint24 lpFee;
{
(,int24 tickBeforeSwap,,uint24 fee) = StateLibrary.getSlot0(poolManager, poolId);
lpFee = fee;
bytes32 slot = _getPreviousTickSlot(poolId);
// Store tick for CAP detection in afterSwap
// Equivalent Solidity: previousTick[poolId] = tickBeforeSwap
assembly ("memory-safe") {
tstore(slot, tickBeforeSwap)
}
}
FeeParams memory params_ = feeParams[poolId];
if (!params_.enabled) {
return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
}
uint24 totalFee;
{
SurgeState storage surge = surgeStates[poolId];
uint24 surgeFee = 0;
if (surge.isActive) {
uint32 elapsed = uint32(block.timestamp) - surge.capStartTime;
if (elapsed >= surge.surgeDuration) {
surge.isActive = false;
emit SurgeDeactivated(poolId, uint32(block.timestamp));
} else {
uint32 remaining = surge.surgeDuration - elapsed;
surgeFee = uint24(
(uint256(params_.baseFee) * surge.surgeMultiplier * remaining / surge.surgeDuration) / BPS_DENOMINATOR
);
emit SurgeFeeApplied(poolId, surgeFee, remaining);
}
}
totalFee = params_.baseFee + surgeFee;
if (totalFee != lpFee) {
poolManager.updateDynamicLPFee(key, totalFee);
emit DynamicLPFeeUpdated(poolId, totalFee, surgeFee);
}
}
return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
}
function _afterSwap(
address,
PoolKey calldata key,
SwapParams calldata,
BalanceDelta,
bytes calldata
) internal override returns (bytes4, int128) {
PoolId poolId = key.toId();
(,int24 tickAfterSwap,,) = StateLibrary.getSlot0(poolManager, poolId);
int24 tickBeforeSwap;
{
bytes32 slot = _getPreviousTickSlot(poolId);
// Load previous tick for CAP detection
// Equivalent Solidity: tickBeforeSwap = previousTick[poolId]
assembly ("memory-safe") {
tickBeforeSwap := tload(slot)
}
}
// Check for CAP event (no limit order execution)
bool wasCapped = volatilityOracle.pushObservationAndCheckCap(poolId, tickBeforeSwap);
if (wasCapped) {
// CAP detected - activate surge mode
surgeStates[poolId].isActive = true;
surgeStates[poolId].capStartTime = uint32(block.timestamp);
emit CAPDetected(poolId, uint32(block.timestamp), tickAfterSwap - tickBeforeSwap);
}
return (BaseHook.afterSwap.selector, 0);
}
/// @notice Register a pool with fixed base fee and surge parameters
/// @param key The pool key
/// @param baseFee Fixed base fee (user-set, e.g., 3000 = 0.3%)
/// @param surgeMultiplier Surge fee multiplier in bps (e.g., 30000 = 3x)
/// @param surgeDuration Surge decay duration in seconds (e.g., 3600 = 1 hour)
/// @param initialMaxTicksPerBlock Initial CAP threshold (e.g., 50)
function registerPool(
PoolKey calldata key,
uint24 baseFee,
uint24 surgeMultiplier,
uint32 surgeDuration,
uint24 initialMaxTicksPerBlock
) external {
if (msg.sender != orderBookFactory) revert("OnlyOrderBookFactory");
PoolId poolId = key.toId();
// Create a unique identifier for the pool parameters
bytes32 parametersHash = keccak256(abi.encodePacked(
Currency.unwrap(key.currency0),
Currency.unwrap(key.currency1),
key.tickSpacing
));
if (poolParametersUsed[parametersHash]) revert("PoolParametersAlreadyUsed");
managedPools[poolId] = true;
poolParametersUsed[parametersHash] = true;
// Set fixed base fee
feeParams[poolId] = FeeParams({
baseFee: baseFee,
enabled: true
});
// Set surge parameters
surgeStates[poolId] = SurgeState({
surgeMultiplier: surgeMultiplier,
surgeDuration: surgeDuration,
capStartTime: 0,
isActive: false
});
// Initialize oracle with system-wide default policy params
volatilityOracle.enableOracleForPool(
key,
initialMaxTicksPerBlock,
defaultMinCap,
defaultMaxCap,
defaultStepPpm,
defaultBudgetPpm,
defaultDecayWindow,
defaultUpdateInterval
);
// Set trading enabled block (1-block delay)
tradingEnabledBlock[poolId] = block.number + 1;
emit PoolRegistered(poolId, baseFee, surgeMultiplier, surgeDuration, initialMaxTicksPerBlock);
}
/// @notice Update base fee for a pool (owner only)
function updateBaseFee(PoolKey calldata key, uint24 newBaseFee) external onlyOwner {
PoolId poolId = key.toId();
if (!managedPools[poolId]) revert("NotManagedPool");
feeParams[poolId].baseFee = newBaseFee;
emit FeeParamsUpdated(poolId, newBaseFee);
}
/// @notice Update surge parameters for a pool (owner only)
function updateSurgeParams(
PoolKey calldata key,
uint24 multiplier,
uint32 duration
) external onlyOwner {
PoolId poolId = key.toId();
if (!managedPools[poolId]) revert("NotManagedPool");
surgeStates[poolId].surgeMultiplier = multiplier;
surgeStates[poolId].surgeDuration = duration;
}
/// @notice Update oracle policy parameters (owner only)
function updateOraclePolicy(
PoolKey calldata key,
uint24 minCap,
uint24 maxCap,
uint32 stepPpm,
uint32 budgetPpm,
uint32 decayWindow,
uint32 updateInterval
) external onlyOwner {
PoolId poolId = key.toId();
if (!managedPools[poolId]) revert("NotManagedPool");
volatilityOracle.refreshPolicyCache(
poolId,
minCap,
maxCap,
stepPpm,
budgetPpm,
decayWindow,
updateInterval
);
}
/// @notice Update system-wide default oracle policy parameters (owner only)
function updateDefaultOraclePolicy(
uint24 minCap,
uint24 maxCap,
uint32 stepPpm,
uint32 budgetPpm,
uint32 decayWindow,
uint32 updateInterval
) external onlyOwner {
defaultMinCap = minCap;
defaultMaxCap = maxCap;
defaultStepPpm = stepPpm;
defaultBudgetPpm = budgetPpm;
defaultDecayWindow = decayWindow;
defaultUpdateInterval = updateInterval;
emit DefaultOraclePolicyUpdated(minCap, maxCap, stepPpm, budgetPpm, decayWindow, updateInterval);
}
/// @notice Pause/unpause auto-tuning for a pool (owner only)
function pauseAutoTune(PoolKey calldata key, bool paused) external onlyOwner {
PoolId poolId = key.toId();
if (!managedPools[poolId]) revert("NotManagedPool");
volatilityOracle.setAutoTunePaused(poolId, paused);
}
/// @notice Observe TWAP ticks at specified times (forwards to oracle)
function observe(PoolKey calldata key, uint32 secondsAgo0, uint32 secondsAgo1)
external
view
returns (int56 tickCumulative0, int56 tickCumulative1)
{
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = secondsAgo0;
secondsAgos[1] = secondsAgo1;
(int56[] memory tickCumulatives,) = volatilityOracle.observe(key, secondsAgos);
return (tickCumulatives[0], tickCumulatives[1]);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {Currency} from "../types/Currency.sol";
import {CustomRevert} from "./CustomRevert.sol";
library CurrencyReserves {
using CustomRevert for bytes4;
/// bytes32(uint256(keccak256("ReservesOf")) - 1)
bytes32 constant RESERVES_OF_SLOT = 0x1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd95;
/// bytes32(uint256(keccak256("Currency")) - 1)
bytes32 constant CURRENCY_SLOT = 0x27e098c505d44ec3574004bca052aabf76bd35004c182099d8c575fb238593b9;
function getSyncedCurrency() internal view returns (Currency currency) {
assembly ("memory-safe") {
currency := tload(CURRENCY_SLOT)
}
}
function resetCurrency() internal {
assembly ("memory-safe") {
tstore(CURRENCY_SLOT, 0)
}
}
function syncCurrencyAndReserves(Currency currency, uint256 value) internal {
assembly ("memory-safe") {
tstore(CURRENCY_SLOT, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
tstore(RESERVES_OF_SLOT, value)
}
}
function getSyncedReserves() internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(RESERVES_OF_SLOT)
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// for the nonzero delta count.
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library NonzeroDeltaCount {
// The slot holding the number of nonzero deltas. bytes32(uint256(keccak256("NonzeroDeltaCount")) - 1)
bytes32 internal constant NONZERO_DELTA_COUNT_SLOT =
0x7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b;
function read() internal view returns (uint256 count) {
assembly ("memory-safe") {
count := tload(NONZERO_DELTA_COUNT_SLOT)
}
}
function increment() internal {
assembly ("memory-safe") {
let count := tload(NONZERO_DELTA_COUNT_SLOT)
count := add(count, 1)
tstore(NONZERO_DELTA_COUNT_SLOT, count)
}
}
/// @notice Potential to underflow. Ensure checks are performed by integrating contracts to ensure this does not happen.
/// Current usage ensures this will not happen because we call decrement with known boundaries (only up to the number of times we call increment).
function decrement() internal {
assembly ("memory-safe") {
let count := tload(NONZERO_DELTA_COUNT_SLOT)
count := sub(count, 1)
tstore(NONZERO_DELTA_COUNT_SLOT, count)
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library Lock {
// The slot holding the unlocked state, transiently. bytes32(uint256(keccak256("Unlocked")) - 1)
bytes32 internal constant IS_UNLOCKED_SLOT = 0xc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab23;
function unlock() internal {
assembly ("memory-safe") {
// unlock
tstore(IS_UNLOCKED_SLOT, true)
}
}
function lock() internal {
assembly ("memory-safe") {
tstore(IS_UNLOCKED_SLOT, false)
}
}
function isUnlocked() internal view returns (bool unlocked) {
assembly ("memory-safe") {
unlocked := tload(IS_UNLOCKED_SLOT)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.
/// @dev parseSelector also is used to parse the expected selector
/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).
library ParseBytes {
function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {
// equivalent: (selector,) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
selector := mload(add(result, 0x20))
}
}
function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {
// equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));
assembly ("memory-safe") {
lpFee := mload(add(result, 0x60))
}
}
function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {
// equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));
assembly ("memory-safe") {
hookReturn := mload(add(result, 0x40))
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import {FullMath} from "./FullMath.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {LiquidityMath} from "./LiquidityMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Position
/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary
/// @dev Positions store additional state for tracking fees owed to the position
library Position {
using CustomRevert for bytes4;
/// @notice Cannot update a position with no liquidity
error CannotUpdateEmptyPosition();
// info stored for each user's position
struct State {
// the amount of liquidity owned by this position
uint128 liquidity;
// fee growth per unit of liquidity as of the last update to liquidity or fees owed
uint256 feeGrowthInside0LastX128;
uint256 feeGrowthInside1LastX128;
}
/// @notice Returns the State struct of a position, given an owner and position boundaries
/// @param self The mapping containing all user positions
/// @param owner The address of the position owner
/// @param tickLower The lower tick boundary of the position
/// @param tickUpper The upper tick boundary of the position
/// @param salt A unique value to differentiate between multiple positions in the same range
/// @return position The position info struct of the given owners' position
function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
internal
view
returns (State storage position)
{
bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);
position = self[positionKey];
}
/// @notice A helper function to calculate the position key
/// @param owner The address of the position owner
/// @param tickLower the lower tick boundary of the position
/// @param tickUpper the upper tick boundary of the position
/// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.
function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
internal
pure
returns (bytes32 positionKey)
{
// positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(add(fmp, 0x26), salt) // [0x26, 0x46)
mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)
mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)
mstore(fmp, owner) // [0x0c, 0x20)
positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes
// now clean the memory we used
mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt
mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt
mstore(fmp, 0) // fmp held owner
}
}
/// @notice Credits accumulated fees to a user's position
/// @param self The individual position to update
/// @param liquidityDelta The change in pool liquidity as a result of the position update
/// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries
/// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries
/// @return feesOwed0 The amount of currency0 owed to the position owner
/// @return feesOwed1 The amount of currency1 owed to the position owner
function update(
State storage self,
int128 liquidityDelta,
uint256 feeGrowthInside0X128,
uint256 feeGrowthInside1X128
) internal returns (uint256 feesOwed0, uint256 feesOwed1) {
uint128 liquidity = self.liquidity;
if (liquidityDelta == 0) {
// disallow pokes for 0 liquidity positions
if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();
} else {
self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);
}
// calculate accumulated fees. overflow in the subtraction of fee growth is expected
unchecked {
feesOwed0 =
FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);
feesOwed1 =
FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);
}
// update the position
self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
interface IMultiPositionFactory {
// Manager info struct
struct ManagerInfo {
address managerAddress; // Note: only used when returning from getters
address managerOwner;
PoolKey poolKey;
string name;
}
// Token pair info struct
struct TokenPairInfo {
address currency0;
address currency1;
uint256 managerCount;
}
// Roles
function CLAIM_MANAGER() external view returns (bytes32);
function FEE_MANAGER() external pure returns (bytes32);
// Access control
function hasRoleOrOwner(bytes32 role, address account) external view returns (bool);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function hasRole(bytes32 role, address account) external view returns (bool);
// Factory
function feeRecipient() external view returns (address);
function setFeeRecipient(address _feeRecipient) external;
function protocolFee() external view returns (uint16);
function setProtocolFee(uint16 _fee) external;
function deployMultiPositionManager(PoolKey memory poolKey, address owner, string memory name)
external
returns (address);
function computeAddress(PoolKey memory poolKey, address managerOwner, string memory name)
external
view
returns (address);
function getManagersByOwner(address managerOwner) external view returns (ManagerInfo[] memory);
function getAllManagersPaginated(uint256 offset, uint256 limit)
external
view
returns (ManagerInfo[] memory managersInfo, uint256 totalCount);
function getTotalManagersCount() external view returns (uint256);
function getAllTokenPairsPaginated(uint256 offset, uint256 limit)
external
view
returns (TokenPairInfo[] memory pairsInfo, uint256 totalCount);
function getAllManagersByTokenPair(address currency0, address currency1, uint256 offset, uint256 limit)
external
view
returns (ManagerInfo[] memory managersInfo, uint256 totalCount);
// Events
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
event MultiPositionManagerDeployed(address indexed multiPositionManager, address indexed owner, PoolKey poolKey);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {MultiPositionManager} from "./MultiPositionManager.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
/**
* @title MultiPositionDeployer
* @notice Deploys MultiPositionManager contracts with CREATE2
* @dev Separated from factory to reduce factory contract size
*/
contract MultiPositionDeployer {
/**
* @notice Deploys a new MultiPositionManager contract
* @param poolManager The Uniswap V4 pool manager
* @param poolKey The pool key for the Uniswap V4 pool
* @param owner The owner of the new MultiPositionManager
* @param factory The factory contract address
* @param name The name of the LP token
* @param symbol The symbol of the LP token
* @param fee The protocol fee
* @param salt The salt for CREATE2 deployment
* @return The address of the deployed MultiPositionManager
*/
function deploy(
IPoolManager poolManager,
PoolKey memory poolKey,
address owner,
address factory,
string memory name,
string memory symbol,
uint16 fee,
bytes32 salt
) external returns (address) {
return address(new MultiPositionManager{salt: salt}(poolManager, poolKey, owner, factory, name, symbol, fee));
}
/**
* @notice Computes the address where a MultiPositionManager will be deployed
* @param poolManager The Uniswap V4 pool manager
* @param poolKey The pool key for the Uniswap V4 pool
* @param owner The owner of the new MultiPositionManager
* @param factory The factory contract address
* @param name The name of the LP token
* @param symbol The symbol of the LP token
* @param fee The protocol fee
* @param salt The salt for CREATE2 deployment
* @return predicted The address where the MultiPositionManager will be deployed
*/
function computeAddress(
IPoolManager poolManager,
PoolKey memory poolKey,
address owner,
address factory,
string memory name,
string memory symbol,
uint16 fee,
bytes32 salt
) external view returns (address predicted) {
bytes32 hash = keccak256(
abi.encodePacked(
type(MultiPositionManager).creationCode,
abi.encode(poolManager, poolKey, owner, factory, name, symbol, fee)
)
);
/// @solidity memory-safe-assembly
assembly {
// Load free memory pointer
let ptr := mload(0x40)
// Store 0xff at the correct position (byte 0 of our 85-byte data)
mstore(ptr, 0xff00000000000000000000000000000000000000000000000000000000000000)
// Store address at byte 1 (shift right by 96 bits = 12 bytes to right-align in 20 bytes)
mstore(add(ptr, 0x01), shl(96, address()))
// Store salt at byte 21
mstore(add(ptr, 0x15), salt)
// Store hash at byte 53
mstore(add(ptr, 0x35), hash)
// Hash 85 bytes starting from ptr
predicted := keccak256(ptr, 0x55)
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {SafeCallback} from "v4-periphery/src/base/SafeCallback.sol";
import {IMultiPositionManager} from "./interfaces/IMultiPositionManager.sol";
import {IMultiPositionFactory} from "./interfaces/IMultiPositionFactory.sol";
import {PoolManagerUtils} from "./libraries/PoolManagerUtils.sol";
import {Multicall} from "./base/Multicall.sol";
import {SharedStructs} from "./base/SharedStructs.sol";
import {RebalanceLogic} from "./libraries/RebalanceLogic.sol";
import {WithdrawLogic} from "./libraries/WithdrawLogic.sol";
import {DepositLogic} from "./libraries/DepositLogic.sol";
import {PositionLogic} from "./libraries/PositionLogic.sol";
contract MultiPositionManager is IMultiPositionManager, ERC20, ReentrancyGuard, Ownable, SafeCallback, Multicall {
using SafeERC20 for IERC20;
using StateLibrary for IPoolManager;
using PoolIdLibrary for PoolKey;
uint256 public constant PRECISION = 1e36;
int24 public constant CENTER_AT_CURRENT_TICK = type(int24).max;
event RelayerGranted(address indexed account);
event RelayerRevoked(address indexed account);
SharedStructs.ManagerStorage internal s;
error UnauthorizedCaller();
error InvalidAction();
event Withdraw(address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 shares, uint256 totalSupply, uint256 amount0, uint256 amount1);
event WithdrawCustom(
address indexed sender, address indexed to, uint256 shares, uint256 amount0Out, uint256 amount1Out
);
event FeeChanged(uint16 newFee);
/**
* @notice Constructor for MultiPositionManager
* @dev Sets all immutable values and initializes the contract
* @param _poolManager The Uniswap V4 pool manager
* @param _poolKey The pool key defining the pool
* @param _owner The owner address
* @param _factory The factory address
* @param _name Token name
* @param _symbol Token symbol
* @param _fee The protocol fee denominator
*/
constructor(
IPoolManager _poolManager,
PoolKey memory _poolKey,
address _owner,
address _factory,
string memory _name,
string memory _symbol,
uint16 _fee
) ERC20(_name, _symbol) Ownable(_owner) SafeCallback(_poolManager) {
s.poolKey = _poolKey;
s.poolId = _poolKey.toId();
s.currency0 = _poolKey.currency0;
s.currency1 = _poolKey.currency1;
s.factory = _factory;
s.fee = _fee;
}
function poolKey() external view returns (PoolKey memory) {
return s.poolKey;
}
function fee() external view returns (uint16) {
return s.fee;
}
function factory() external view returns (address) {
return s.factory;
}
function basePositionsLength() external view returns (uint256) {
return s.basePositionsLength;
}
function limitPositions(uint256 index) external view returns (Range memory) {
return s.limitPositions[index];
}
function limitPositionsLength() external view returns (uint256) {
return s.limitPositionsLength;
}
function lastStrategyParams()
external
view
returns (
address strategy,
int24 centerTick,
uint24 ticksLeft,
uint24 ticksRight,
uint24 limitWidth,
uint120 weight0,
uint120 weight1,
bool useCarpet,
bool useSwap,
bool useAssetWeights
)
{
SharedStructs.StrategyParams memory params = s.lastStrategyParams;
return (
params.strategy,
params.centerTick,
params.ticksLeft,
params.ticksRight,
params.limitWidth,
params.weight0,
params.weight1,
params.useCarpet,
params.useSwap,
params.useAssetWeights
);
}
function isRelayer(address account) public view returns (bool) {
return s.relayers[account];
}
modifier onlyOwnerOrFactory() {
require(msg.sender == owner() || msg.sender == s.factory);
_;
}
modifier onlyOwnerOrRelayerOrFactory() {
require(msg.sender == owner() || s.relayers[msg.sender] || msg.sender == s.factory);
_;
}
receive() external payable {}
/**
* @notice Deposit tokens to vault (idle balance). Use compound() to add to positions.
* @param deposit0Desired Maximum amount of token0 to deposit
* @param deposit1Desired Maximum amount of token1 to deposit
* @param to Address to receive shares
* @param from Address to pull tokens from
* @return shares Number of shares minted
* @return deposit0 Actual amount of token0 deposited
* @return deposit1 Actual amount of token1 deposited
* @dev Tokens are pulled from 'from' and shares are minted to 'to'
*/
function deposit(uint256 deposit0Desired, uint256 deposit1Desired, address to, address from)
external
payable
onlyOwnerOrFactory
returns (uint256 shares, uint256 deposit0, uint256 deposit1)
{
(shares, deposit0, deposit1) = DepositLogic.processDeposit(
s,
poolManager,
deposit0Desired,
deposit1Desired,
to, // shares minted to 'to'
from, // tokens pulled from 'from'
totalSupply(),
msg.value
);
_mint(to, shares);
_transferIn(from, s.currency0, deposit0);
_transferIn(from, s.currency1, deposit1);
}
/**
* @notice Compound idle vault balance + fees into existing positions
* @dev Collects fees via zeroBurn, then adds all idle balance to positions
* Marked payable for multicall compatibility - msg.value persists across delegatecalls.
* Does not consume msg.value; it just needs to accept it to prevent multicall reverts.
* @param inMin Minimum amounts for each position (slippage protection)
*/
function compound(uint256[2][] calldata inMin) external payable onlyOwnerOrRelayerOrFactory {
// First call ZERO_BURN to collect fees without unlock
if (s.basePositionsLength > 0) {
poolManager.unlock(abi.encode(IMultiPositionManager.Action.ZERO_BURN, ""));
}
// Then call COMPOUND to redeposit collected fees
poolManager.unlock(abi.encode(IMultiPositionManager.Action.COMPOUND, abi.encode(inMin)));
}
/**
* @notice Compound with swap: collect fees, swap to target ratio, then add to positions
* @param swapParams Swap parameters for DEX aggregator execution
* @param inMin Minimum amounts per position for slippage protection
*/
function compoundSwap(RebalanceLogic.SwapParams calldata swapParams, uint256[2][] calldata inMin)
external
payable
onlyOwnerOrRelayerOrFactory
{
if (s.basePositionsLength > 0) {
poolManager.unlock(abi.encode(IMultiPositionManager.Action.ZERO_BURN, ""));
}
RebalanceLogic.executeCompoundSwap(s, swapParams);
poolManager.unlock(abi.encode(IMultiPositionManager.Action.COMPOUND, abi.encode(inMin)));
}
/**
* @notice Withdraw shares from the vault
* @param shares Number of liquidity tokens to redeem as pool assets
* @param outMin min amount returned for shares of liq
* @param withdrawToWallet If true, transfers tokens to owner and burns shares. If false, keeps tokens in contract and preserves shares.
* @return amount0 Amount of token0 redeemed by the submitted liquidity tokens
* @return amount1 Amount of token1 redeemed by the submitted liquidity tokens
* @dev Tokens are always sent to owner
*/
function withdraw(uint256 shares, uint256[2][] memory outMin, bool withdrawToWallet)
external
nonReentrant
onlyOwnerOrRelayerOrFactory
returns (uint256 amount0, uint256 amount1)
{
(amount0, amount1) = WithdrawLogic.processWithdraw(
s,
poolManager,
shares,
owner(), // tokens always go to owner
outMin,
totalSupply(),
msg.sender,
withdrawToWallet
);
if (withdrawToWallet) {
_burn(owner(), shares);
}
}
/**
* @notice Withdraw custom amounts of both tokens
* @param amount0Desired Amount of token0 to withdraw
* @param amount1Desired Amount of token1 to withdraw
* @param outMin Minimum amounts per position for slippage protection
* @return amount0Out Amount of token0 withdrawn
* @return amount1Out Amount of token1 withdrawn
* @return sharesBurned Number of shares burned
* @dev Tokens are always sent to owner
*/
function withdrawCustom(uint256 amount0Desired, uint256 amount1Desired, uint256[2][] memory outMin)
external
nonReentrant
onlyOwnerOrRelayerOrFactory
returns (uint256 amount0Out, uint256 amount1Out, uint256 sharesBurned)
{
WithdrawLogic.CustomWithdrawParams memory params = WithdrawLogic.CustomWithdrawParams({
amount0Desired: amount0Desired,
amount1Desired: amount1Desired,
to: owner(), // tokens always go to owner
outMin: outMin,
totalSupply: totalSupply(),
senderBalance: balanceOf(owner()),
sender: owner()
});
(amount0Out, amount1Out, sharesBurned) = WithdrawLogic.processWithdrawCustom(s, poolManager, params);
_burn(owner(), sharesBurned);
}
/**
* @notice Unified rebalance function with optional weighted token distribution
* @param params Rebalance parameters including optional weights
* @param outMin Minimum output amounts for withdrawals
* @param inMin Minimum input amounts for new positions (slippage protection)
* @dev If weights are not specified or are both 0, defaults to 50/50 distribution
* Marked payable for multicall compatibility - msg.value persists across delegatecalls.
* Does not consume msg.value; it just needs to accept it to prevent multicall reverts.
*/
function rebalance(
IMultiPositionManager.RebalanceParams calldata params,
uint256[2][] memory outMin,
uint256[2][] memory inMin
) public payable onlyOwnerOrRelayerOrFactory {
// First call ZERO_BURN to collect fees (like compound does)
if (s.basePositionsLength > 0) {
poolManager.unlock(abi.encode(IMultiPositionManager.Action.ZERO_BURN, ""));
}
// Now fees are in balanceOfSelf(), so liquidities will be calculated correctly
(IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities, uint24 limitWidth) =
RebalanceLogic.rebalance(s, poolManager, params, outMin, inMin);
bytes memory encodedParams = abi.encode(baseRanges, liquidities, limitWidth, inMin, outMin, params);
poolManager.unlock(abi.encode(IMultiPositionManager.Action.REBALANCE, encodedParams));
}
/**
* @notice Rebalances positions with an external DEX swap to achieve target weights
* @param params Swap and rebalance parameters including aggregator address and swap data
* @param outMin Minimum output amounts for burning current positions
* @param inMin Minimum input amounts for new positions (slippage protection)
* @dev Burns all positions first, then swaps to target ratio, then rebalances with new amounts
*/
function rebalanceSwap(
IMultiPositionManager.RebalanceSwapParams calldata params,
uint256[2][] memory outMin,
uint256[2][] memory inMin
) public payable onlyOwnerOrRelayerOrFactory {
if (totalSupply() > 0 && (s.basePositionsLength > 0 || s.limitPositionsLength > 0)) {
poolManager.unlock(abi.encode(IMultiPositionManager.Action.BURN_ALL, abi.encode(outMin)));
}
(IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities, uint24 limitWidth) =
RebalanceLogic.executeSwapAndCalculateRanges(s, poolManager, params);
bytes memory encodedParams =
abi.encode(baseRanges, liquidities, limitWidth, inMin, outMin, params.rebalanceParams);
poolManager.unlock(abi.encode(IMultiPositionManager.Action.REBALANCE, encodedParams));
}
/**
* @notice Claims fees
* @dev If called by owner or relayer, performs zeroBurn and claims fees (owner fees go to owner)
* @dev If called by factory owner or CLAIM_MANAGER, only claims existing protocol fees
*/
function claimFee() external {
if (msg.sender == owner() || s.relayers[msg.sender]) {
// Owner or relayer calling - collect fees and transfer owner portion to owner
poolManager.unlock(abi.encode(IMultiPositionManager.Action.CLAIM_FEE, abi.encode(owner())));
} else if (
IMultiPositionFactory(s.factory).hasRoleOrOwner(
IMultiPositionFactory(s.factory).CLAIM_MANAGER(), msg.sender
)
) {
// CLAIM_MANAGER calling - only claim protocol fees
poolManager.unlock(abi.encode(IMultiPositionManager.Action.CLAIM_FEE, abi.encode(address(0))));
} else {
revert UnauthorizedCaller();
}
}
function setFee(uint16 newFee) external {
IMultiPositionFactory factoryContract = IMultiPositionFactory(s.factory);
require(factoryContract.hasRole(factoryContract.FEE_MANAGER(), msg.sender));
s.fee = newFee;
emit FeeChanged(newFee);
}
/**
* @notice Grant relayer role to an address
* @param account The address to grant the role to
*/
function grantRelayerRole(address account) external onlyOwner {
require(account != address(0));
if (!s.relayers[account]) {
s.relayers[account] = true;
emit RelayerGranted(account);
}
}
/**
* @notice Revoke relayer role from an address
* @param account The address to revoke the role from
*/
function revokeRelayerRole(address account) external onlyOwner {
if (s.relayers[account]) {
s.relayers[account] = false;
emit RelayerRevoked(account);
}
}
function getBasePositions() public view returns (Range[] memory, PositionData[] memory) {
return PositionLogic.getBasePositions(s, poolManager);
}
function getPositions() public view returns (Range[] memory, PositionData[] memory) {
return PositionLogic.getPositions(s, poolManager);
}
function getTotalAmounts()
external
view
returns (uint256 total0, uint256 total1, uint256 totalFee0, uint256 totalFee1)
{
return WithdrawLogic.getTotalAmounts(s, poolManager);
}
function getTotalValuesInOneToken()
external
view
returns (uint256 totalValueInToken0, uint256 totalValueInToken1)
{
return PositionLogic.getTotalValuesInOneToken(s, poolManager);
}
function currentTick() public view returns (int24 tick) {
(, tick,,) = poolManager.getSlot0(s.poolKey.toId());
}
function getRatios()
external
view
returns (
uint256 pool0Ratio,
uint256 pool1Ratio,
uint256 total0Ratio,
uint256 total1Ratio,
uint256 inPositionRatio,
uint256 outOfPositionRatio,
uint256 baseRatio,
uint256 limitRatio,
uint256 base0Ratio,
uint256 base1Ratio,
uint256 limit0Ratio,
uint256 limit1Ratio
)
{
PositionLogic.Ratios memory ratios = PositionLogic.getRatios(s, poolManager);
return (
ratios.pool0Ratio,
ratios.pool1Ratio,
ratios.total0Ratio,
ratios.total1Ratio,
ratios.inPositionRatio,
ratios.outOfPositionRatio,
ratios.baseRatio,
ratios.limitRatio,
ratios.base0Ratio,
ratios.base1Ratio,
ratios.limit0Ratio,
ratios.limit1Ratio
);
}
function _unlockCallback(bytes calldata data) internal override returns (bytes memory) {
(Action selector, bytes memory params) = abi.decode(data, (Action, bytes));
bytes memory result = _executeActionWithoutUnlock(selector, params);
_closePair();
return result;
}
function _executeActionWithoutUnlock(Action selector, bytes memory params) internal returns (bytes memory result) {
if (selector == IMultiPositionManager.Action.WITHDRAW) {
WithdrawLogic.zeroBurnAllWithoutUnlock(s, poolManager);
(uint256 shares, uint256[2][] memory outMin) = abi.decode(params, (uint256, uint256[2][]));
(uint256 amountOut0, uint256 amountOut1) =
PositionLogic.burnLiquidities(poolManager, s, shares, totalSupply(), outMin);
return abi.encode(amountOut0, amountOut1);
} else if (selector == IMultiPositionManager.Action.REBALANCE) {
return RebalanceLogic.processRebalanceInCallback(s, poolManager, params, totalSupply());
} else if (selector == IMultiPositionManager.Action.ZERO_BURN) {
WithdrawLogic.zeroBurnAllWithoutUnlock(s, poolManager);
return "";
} else if (selector == IMultiPositionManager.Action.CLAIM_FEE) {
address caller = abi.decode(params, (address));
WithdrawLogic.processClaimFee(s, poolManager, caller, owner());
return "";
} else if (selector == IMultiPositionManager.Action.BURN_ALL) {
return WithdrawLogic.processBurnAllInCallback(s, poolManager, totalSupply(), params);
} else if (selector == IMultiPositionManager.Action.COMPOUND) {
uint256[2][] memory inMin = abi.decode(params, (uint256[2][]));
DepositLogic.processCompound(s, poolManager, inMin);
return "";
} else {
revert InvalidAction();
}
}
function _closePair() internal {
PoolManagerUtils.close(poolManager, s.currency1);
PoolManagerUtils.close(poolManager, s.currency0);
}
function _transferIn(address from, Currency currency, uint256 amount) internal {
if (currency.isAddressZero()) {
require(msg.value >= amount);
if (msg.value > amount) {
payable(msg.sender).transfer(msg.value - amount);
}
} else if (amount != 0) {
IERC20(Currency.unwrap(currency)).safeTransferFrom(from, address(this), amount);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import "../interfaces/IMulticall.sol";
/**
* @title Multicall
* @notice Enables calling multiple methods in a single transaction
* @dev Provides a function to batch together multiple calls in a single external call
*/
abstract contract Multicall is IMulticall {
error MulticallFailed(uint256 index, bytes reason);
/**
* @notice Execute multiple calls in a single transaction
* @param data Array of encoded function calls
* @return results Array of return data from each call
*/
function multicall(bytes[] calldata data) public payable virtual override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Decode revert reason if possible
if (result.length > 0) {
// Bubble up the revert reason
assembly {
revert(add(32, result), mload(result))
}
} else {
revert MulticallFailed(i, result);
}
}
results[i] = result;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
/// @title IImmutableState
/// @notice Interface for the ImmutableState contract
interface IImmutableState {
/// @notice The Uniswap v4 PoolManager contract
function poolManager() external view returns (IPoolManager);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
/**
* @title ILiquidityStrategy
* @notice Interface for liquidity distribution strategies matching Python shapes
* @dev Each strategy implements a different distribution pattern (uniform, triangle, gaussian, etc.)
*/
interface ILiquidityStrategy {
/**
* @notice Generate tick ranges with optional carpet positions
* @param centerTick The center tick for the strategy
* @param ticksLeft Number of ticks to the left of center for the distribution
* @param ticksRight Number of ticks to the right of center for the distribution
* @param tickSpacing The tick spacing of the pool
* @param useCarpet Whether to add carpet positions at extreme ticks for TWAP support
* @return lowerTicks Array of lower ticks for each position
* @return upperTicks Array of upper ticks for each position
*/
function generateRanges(int24 centerTick, uint24 ticksLeft, uint24 ticksRight, int24 tickSpacing, bool useCarpet)
external
pure
returns (int24[] memory lowerTicks, int24[] memory upperTicks);
/**
* @notice Get the strategy type identifier
* @return strategyType String identifier for the strategy (e.g., "uniform", "triangle", "gaussian")
*/
function getStrategyType() external pure returns (string memory strategyType);
/**
* @notice Get a description of the strategy
* @return description Human-readable description of the distribution pattern
*/
function getDescription() external pure returns (string memory description);
/**
* @notice Check if this strategy supports weighted distribution
* @return supported True if the strategy implements calculateDensitiesWithWeights
*/
function supportsWeights() external pure returns (bool supported);
/**
* @notice Calculate density weights with token weights and carpet options
* @dev Comprehensive function that supports both token weights and carpet liquidity
* @param lowerTicks Array of lower ticks for each position
* @param upperTicks Array of upper ticks for each position
* @param currentTick Current tick of the pool
* @param centerTick Center tick for the distribution
* @param ticksLeft Number of ticks to the left of center for the shape
* @param ticksRight Number of ticks to the right of center for the shape
* @param weight0 Weight preference for token0 (scaled to 1e18, e.g., 0.8e18 for 80%)
* @param weight1 Weight preference for token1 (scaled to 1e18, e.g., 0.2e18 for 20%)
* @param useCarpet Whether to add carpet liquidity at extremes (0.01% each)
* @param tickSpacing The tick spacing of the pool
* @param useAssetWeights True if weights were auto-calculated from available tokens (should not filter ranges)
* @return weights Array of weights for each position (scaled to 1e18, sum = 1e18)
*/
function calculateDensities(
int24[] memory lowerTicks,
int24[] memory upperTicks,
int24 currentTick,
int24 centerTick,
uint24 ticksLeft,
uint24 ticksRight,
uint256 weight0,
uint256 weight1,
bool useCarpet,
int24 tickSpacing,
bool useAssetWeights
) external pure returns (uint256[] memory weights);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {Currency} from "v4-core/types/Currency.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId} from "v4-core/types/PoolId.sol";
import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.sol";
/// @title SharedStructs
/// @notice Contains structs shared between the main contract and libraries
library SharedStructs {
/// @notice The complete storage of MultiPositionManager
/// @dev Consolidated into a single struct following Bunni's pattern
struct ManagerStorage {
// Pool configuration
PoolKey poolKey;
PoolId poolId;
Currency currency0;
Currency currency1;
// Positions
mapping(uint256 => IMultiPositionManager.Range) basePositions;
uint256 basePositionsLength;
IMultiPositionManager.Range[2] limitPositions;
uint256 limitPositionsLength;
// External contracts
address factory;
// Fees
uint16 fee;
// Role management
mapping(address => bool) relayers;
// Strategy parameters - efficiently packed
StrategyParams lastStrategyParams;
}
/// @notice Last used strategy parameters
/// @dev Efficiently packed into 2 storage slots
struct StrategyParams {
address strategy; // 20 bytes
int24 centerTick; // 3 bytes
uint24 ticksLeft; // 3 bytes
uint24 ticksRight; // 3 bytes
uint24 limitWidth; // 3 bytes
// Total: 32 bytes - fills slot 1
uint120 weight0; // 15 bytes (enough for 1e18 precision)
uint120 weight1; // 15 bytes
bool useCarpet; // 1 byte
bool useSwap; // 1 byte
bool useAssetWeights; // 1 byte
// Total: 32 bytes - fills slot 2 efficiently
}
/// @notice Environment variables passed to libraries
/// @dev Contains immutable values and frequently accessed contracts
struct Env {
address poolManager;
uint16 protocolFee;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {BalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "v4-core/types/PoolOperation.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {TransientStateLibrary} from "v4-core/libraries/TransientStateLibrary.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {CurrencySettler} from "./CurrencySettler.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {FixedPoint128} from "v4-core/libraries/FixedPoint128.sol";
import {LiquidityAmounts} from "v4-periphery/lib/v4-core/test/utils/LiquidityAmounts.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {SafeCast} from "v4-core/libraries/SafeCast.sol";
import {SignedMath} from "@openzeppelin/contracts/utils/math/SignedMath.sol";
import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.sol";
library PoolManagerUtils {
using PoolIdLibrary for PoolKey;
using StateLibrary for IPoolManager;
using TransientStateLibrary for IPoolManager;
using CurrencySettler for Currency;
using SignedMath for int256;
using SafeCast for *;
bytes32 constant POSITION_ID = bytes32(uint256(1));
bytes constant HOOK_DATA = "";
event ZeroBurn(int24 tickLower, int24 tickUpper, uint256 amount0, uint256 amount1);
error SlippageExceeded();
error InvalidPositionData(IMultiPositionManager.Position position);
error PoolNotInitialized(PoolKey poolKey);
function mintLiquidities(
IPoolManager poolManager,
PoolKey memory poolKey,
IMultiPositionManager.Range[] memory baseRanges,
IMultiPositionManager.Range[2] memory limitRanges,
uint128[] memory liquidities,
uint256[2][] memory inMin
) external returns (IMultiPositionManager.PositionData[] memory) {
// Allocate array for all positions (base + max 2 limit positions)
IMultiPositionManager.PositionData[] memory positionData =
new IMultiPositionManager.PositionData[](baseRanges.length + 2);
uint256 positionCount = 0;
for (uint8 i = 0; i < baseRanges.length;) {
(uint256 currencyDelta0, uint256 currencyDelta1) =
_getCurrencyDeltas(poolManager, poolKey.currency0, poolKey.currency1);
(uint256 amount0, uint256 amount1) =
getAmountsForLiquidity(poolManager, poolKey, baseRanges[i], liquidities[i]);
if (amount0 > currencyDelta0) {
amount0 = currencyDelta0;
}
if (amount1 > currencyDelta1) {
amount1 = currencyDelta1;
}
IMultiPositionManager.PositionData memory data =
_mintLiquidityForAmounts(poolManager, poolKey, baseRanges[i], amount0, amount1, inMin[i]);
positionData[positionCount] = data;
unchecked {
++positionCount;
++i;
}
}
// mint limit positions if they are defined (checked inside the function)
positionCount = _mintLimitPositions(poolManager, poolKey, limitRanges, positionData, positionCount);
// Resize array to actual count (remove empty slots)
assembly {
mstore(positionData, positionCount)
}
return positionData;
}
// if there's still remaining tokens, create a limit position(single-sided position)
function _mintLimitPositions(
IPoolManager poolManager,
PoolKey memory poolKey,
IMultiPositionManager.Range[2] memory limitRanges,
IMultiPositionManager.PositionData[] memory positionData,
uint256 positionCount
) internal returns (uint256) {
if (limitRanges[0].lowerTick != limitRanges[0].upperTick) {
uint256 currencyDelta1 = _getCurrencyDelta(poolManager, poolKey.currency1);
if (currencyDelta1 != 0) {
IMultiPositionManager.PositionData memory data = _mintLiquidityForAmounts(
poolManager, poolKey, limitRanges[0], 0, currencyDelta1, [uint256(0), uint256(0)]
);
positionData[positionCount] = data;
unchecked {
++positionCount;
}
}
}
if (limitRanges[1].lowerTick != limitRanges[1].upperTick) {
uint256 currencyDelta0 = _getCurrencyDelta(poolManager, poolKey.currency0);
if (currencyDelta0 != 0) {
IMultiPositionManager.PositionData memory data = _mintLiquidityForAmounts(
poolManager, poolKey, limitRanges[1], currencyDelta0, 0, [uint256(0), uint256(0)]
);
positionData[positionCount] = data;
unchecked {
++positionCount;
}
}
}
return positionCount;
}
function _mintLiquidityForAmounts(
IPoolManager poolManager,
PoolKey memory poolKey,
IMultiPositionManager.Range memory range,
uint256 amount0,
uint256 amount1,
uint256[2] memory inMin
) internal returns (IMultiPositionManager.PositionData memory) {
(uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolKey.toId());
if (sqrtPriceX96 == 0) {
revert PoolNotInitialized(poolKey);
}
if (
range.lowerTick >= range.upperTick || range.lowerTick % poolKey.tickSpacing != 0
|| range.upperTick % poolKey.tickSpacing != 0
) {
IMultiPositionManager.Position memory pos = IMultiPositionManager.Position({
poolKey: poolKey,
lowerTick: range.lowerTick,
upperTick: range.upperTick
});
revert InvalidPositionData(pos);
}
uint128 liquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtPriceX96,
TickMath.getSqrtPriceAtTick(range.lowerTick),
TickMath.getSqrtPriceAtTick(range.upperTick),
amount0,
amount1
);
uint256 actualAmount0;
uint256 actualAmount1;
if (liquidity != 0) {
(BalanceDelta callerDelta,) = poolManager.modifyLiquidity(
poolKey,
ModifyLiquidityParams({
tickLower: range.lowerTick,
tickUpper: range.upperTick,
liquidityDelta: liquidity.toInt128(),
salt: POSITION_ID
}),
HOOK_DATA
);
/// callerDelta.amount0() and callerDelta.amount0() are all negative
actualAmount0 = int256(callerDelta.amount0()).abs();
actualAmount1 = int256(callerDelta.amount1()).abs();
if (actualAmount0 < inMin[0] || actualAmount1 < inMin[1]) {
revert SlippageExceeded();
}
}
return
IMultiPositionManager.PositionData({liquidity: liquidity, amount0: actualAmount0, amount1: actualAmount1});
}
function burnLiquidities(
IPoolManager poolManager,
PoolKey memory poolKey,
IMultiPositionManager.Range[] memory baseRanges,
IMultiPositionManager.Range[2] memory limitRanges,
uint256 shares,
uint256 totalSupply,
uint256[2][] memory outMin
) external returns (uint256 amount0, uint256 amount1) {
if (shares == 0) return (amount0, amount1);
uint256 baseRangesLength = baseRanges.length;
uint256 amountOut0;
uint256 amountOut1;
// Burn base positions
for (uint8 i = 0; i < baseRangesLength;) {
(amountOut0, amountOut1) =
burnLiquidityForShare(poolManager, poolKey, baseRanges[i], shares, totalSupply, outMin[i]);
unchecked {
amount0 = amount0 + amountOut0;
amount1 = amount1 + amountOut1;
++i;
}
}
// Burn limit positions with their specific outMin
(amountOut0, amountOut1) =
_burnLimitPositions(poolManager, poolKey, limitRanges, shares, totalSupply, outMin, baseRangesLength);
unchecked {
amount0 = amount0 + amountOut0;
amount1 = amount1 + amountOut1;
}
}
function _burnLimitPositions(
IPoolManager poolManager,
PoolKey memory poolKey,
IMultiPositionManager.Range[2] memory limitRanges,
uint256 shares,
uint256 totalSupply,
uint256[2][] memory outMin,
uint256 baseRangesLength
) internal returns (uint256 amount0, uint256 amount1) {
if (shares == 0) return (0, 0);
for (uint8 i = 0; i < 2;) {
// Skip empty limit positions
if (limitRanges[i].lowerTick != limitRanges[i].upperTick) {
uint256 outMinIndex = baseRangesLength + i;
// Use provided outMin if available, otherwise use [0, 0] for backward compatibility
uint256[2] memory positionOutMin =
outMinIndex < outMin.length ? outMin[outMinIndex] : [uint256(0), uint256(0)];
(uint256 amountOut0, uint256 amountOut1) =
burnLiquidityForShare(poolManager, poolKey, limitRanges[i], shares, totalSupply, positionOutMin);
unchecked {
amount0 = amount0 + amountOut0;
amount1 = amount1 + amountOut1;
}
}
unchecked {
++i;
}
}
}
function burnLiquidityForShare(
IPoolManager poolManager,
PoolKey memory poolKey,
IMultiPositionManager.Range memory range,
uint256 shares,
uint256 totalSupply,
uint256[2] memory outMin
) public returns (uint256 amountOut0, uint256 amountOut1) {
if (range.lowerTick == range.upperTick) {
return (0, 0);
}
(uint128 liquidity,,) =
poolManager.getPositionInfo(poolKey.toId(), address(this), range.lowerTick, range.upperTick, POSITION_ID);
uint256 liquidityForShares = FullMath.mulDiv(liquidity, shares, totalSupply);
if (liquidityForShares != 0) {
(BalanceDelta callerDelta,) = poolManager.modifyLiquidity(
poolKey,
ModifyLiquidityParams({
tickLower: range.lowerTick,
tickUpper: range.upperTick,
liquidityDelta: -(liquidityForShares).toInt128(),
salt: POSITION_ID
}),
HOOK_DATA
);
// when withdrawing liquidity or collecting fee (collecting fee is same as withdrawing liquidity 0 ),
// callerDelta is always positive
// when adding liquidity, most of time callerDelta is negative but could be positive
// when fee is larger than liquidity itself (but fee already settled in `zeroBurn`)
amountOut0 = callerDelta.amount0().toUint128();
amountOut1 = callerDelta.amount1().toUint128();
if (amountOut0 < outMin[0] || amountOut1 < outMin[1]) {
revert SlippageExceeded();
}
}
}
function zeroBurnAll(
IPoolManager poolManager,
PoolKey memory poolKey,
IMultiPositionManager.Range[] memory baseRanges,
IMultiPositionManager.Range[2] memory limitRanges,
Currency currency0,
Currency currency1,
uint16 fee
) external returns (uint256 totalFee0, uint256 totalFee1) {
uint256 baseRangesLength = baseRanges.length;
uint256 fee0;
uint256 fee1;
for (uint8 i = 0; i < baseRangesLength;) {
(fee0, fee1) = _zeroBurnWithoutUnlock(poolManager, poolKey, baseRanges[i]);
unchecked {
totalFee0 = totalFee0 + fee0;
totalFee1 = totalFee1 + fee1;
++i;
}
}
(fee0, fee1) = _zeroBurnWithoutUnlock(poolManager, poolKey, limitRanges[0]);
unchecked {
totalFee0 = totalFee0 + fee0;
totalFee1 = totalFee1 + fee1;
}
(fee0, fee1) = _zeroBurnWithoutUnlock(poolManager, poolKey, limitRanges[1]);
unchecked {
totalFee0 = totalFee0 + fee0;
totalFee1 = totalFee1 + fee1;
}
// Calculate fees by dividing by fee denominator
uint256 treasuryFee0 = totalFee0 / fee;
uint256 treasuryFee1 = totalFee1 / fee;
if (treasuryFee0 != 0) {
poolManager.mint(address(this), uint256(uint160(Currency.unwrap(currency0))), treasuryFee0);
}
if (treasuryFee1 != 0) {
poolManager.mint(address(this), uint256(uint160(Currency.unwrap(currency1))), treasuryFee1);
}
}
function _zeroBurnWithoutUnlock(
IPoolManager poolManager,
PoolKey memory poolKey,
IMultiPositionManager.Range memory range
) internal returns (uint256 fee0, uint256 fee1) {
if (range.lowerTick == range.upperTick) {
return (0, 0);
}
(uint128 liquidity,,) =
poolManager.getPositionInfo(poolKey.toId(), address(this), range.lowerTick, range.upperTick, POSITION_ID);
if (liquidity != 0) {
// Check fees first
(uint256 feesOwed0, uint256 feesOwed1) = _getFeesOwed(poolManager, poolKey, range);
// Only proceed with modifyLiquidity if either fee is non-zero
if (feesOwed0 != 0 || feesOwed1 != 0) {
(, BalanceDelta feesAccrued) = poolManager.modifyLiquidity(
poolKey,
ModifyLiquidityParams({
tickLower: range.lowerTick,
tickUpper: range.upperTick,
liquidityDelta: 0,
salt: POSITION_ID
}),
HOOK_DATA
);
fee0 = uint128(feesAccrued.amount0());
fee1 = uint128(feesAccrued.amount1());
emit ZeroBurn(range.lowerTick, range.upperTick, fee0, fee1);
}
}
}
function close(IPoolManager poolManager, Currency currency) internal {
int256 currencyDelta = poolManager.currencyDelta(address(this), currency);
if (currencyDelta == 0) {
return;
} else if (currencyDelta < 0) {
currency.settle(poolManager, address(this), uint256(-currencyDelta), false);
} else {
currency.take(poolManager, address(this), uint256(currencyDelta), false);
}
}
function _getCurrencyDelta(IPoolManager poolManager, Currency currency) internal view returns (uint256 delta) {
int256 currencyDelta = poolManager.currencyDelta(address(this), currency);
if (currencyDelta > 0) {
delta = currency.balanceOfSelf() + uint256(currencyDelta);
} else {
delta = currency.balanceOfSelf() - uint256(-currencyDelta);
}
return delta;
}
function _getCurrencyDeltas(IPoolManager poolManager, Currency currency0, Currency currency1)
internal
view
returns (uint256 delta0, uint256 delta1)
{
int256 currencyDelta0 = poolManager.currencyDelta(address(this), currency0);
int256 currencyDelta1 = poolManager.currencyDelta(address(this), currency1);
if (currencyDelta0 > 0) {
delta0 = currency0.balanceOfSelf() + uint256(currencyDelta0);
} else {
delta0 = currency0.balanceOfSelf() - uint256(-currencyDelta0);
}
if (currencyDelta1 > 0) {
delta1 = currency1.balanceOfSelf() + uint256(currencyDelta1);
} else {
delta1 = currency1.balanceOfSelf() - uint256(-currencyDelta1);
}
return (delta0, delta1);
}
function getAmountsForLiquidity(
IPoolManager poolManager,
PoolKey memory poolKey,
IMultiPositionManager.Range memory range,
uint128 liquidity
) internal view returns (uint256 amount0, uint256 amount1) {
(uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolKey.toId());
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96,
TickMath.getSqrtPriceAtTick(range.lowerTick),
TickMath.getSqrtPriceAtTick(range.upperTick),
liquidity
);
}
function getAmountsOf(IPoolManager poolManager, PoolKey memory poolKey, IMultiPositionManager.Range memory range)
external
view
returns (uint128 liquidity, uint256 amount0, uint256 amount1, uint256 feesOwed0, uint256 feesOwed1)
{
if (range.lowerTick == range.upperTick) {
return (0, 0, 0, 0, 0);
}
PoolId poolId = poolKey.toId();
(liquidity,,) =
poolManager.getPositionInfo(poolId, address(this), range.lowerTick, range.upperTick, POSITION_ID);
(uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolId);
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96,
TickMath.getSqrtPriceAtTick(range.lowerTick),
TickMath.getSqrtPriceAtTick(range.upperTick),
liquidity
);
(feesOwed0, feesOwed1) = _getFeesOwed(poolManager, poolKey, range);
}
function _getFeesOwed(IPoolManager poolManager, PoolKey memory poolKey, IMultiPositionManager.Range memory range)
internal
view
returns (uint256 feesOwed0, uint256 feesOwed1)
{
(uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) =
poolManager.getFeeGrowthInside(poolKey.toId(), range.lowerTick, range.upperTick);
(uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) =
poolManager.getPositionInfo(poolKey.toId(), address(this), range.lowerTick, range.upperTick, POSITION_ID);
unchecked {
feesOwed0 = FullMath.mulDiv(feeGrowthInside0X128 - feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);
feesOwed1 = FullMath.mulDiv(feeGrowthInside1X128 - feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);
}
}
/**
* @notice Calculate outMin for rebalance with slippage protection
* @param poolManager The pool manager
* @param poolKey The pool key
* @param ranges Array of position ranges
* @param positionData Array of position data (liquidity values)
* @param maxSlippage Maximum slippage in basis points (10000 = 100%)
* @return outMin Array of minimum amounts [token0, token1] for each position
*/
function calculateOutMinForRebalance(
IPoolManager poolManager,
PoolKey memory poolKey,
IMultiPositionManager.Range[] memory ranges,
IMultiPositionManager.PositionData[] memory positionData,
uint256 maxSlippage
) internal view returns (uint256[2][] memory outMin) {
uint256 totalPositionsLength = ranges.length;
if (totalPositionsLength == 0) {
return outMin;
}
outMin = new uint256[2][](totalPositionsLength);
uint256 slippageMultiplier = 10000 - maxSlippage;
for (uint256 i = 0; i < totalPositionsLength;) {
(uint256 amount0, uint256 amount1) =
getAmountsForLiquidity(poolManager, poolKey, ranges[i], uint128(positionData[i].liquidity));
unchecked {
outMin[i] = [amount0 * slippageMultiplier / 10000, amount1 * slippageMultiplier / 10000];
++i;
}
}
return outMin;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.sol";
import {SharedStructs} from "../base/SharedStructs.sol";
import {PoolManagerUtils} from "./PoolManagerUtils.sol";
import {WithdrawLogic} from "./WithdrawLogic.sol";
/**
* @title PositionLogic
* @notice Library containing position management logic for MultiPositionManager
*/
library PositionLogic {
using PoolIdLibrary for PoolKey;
using StateLibrary for IPoolManager;
// Constants
uint256 constant PRECISION = 1e36;
uint256 constant RATIO_PRECISION = 1e18;
// Structs
struct Ratios {
uint256 pool0Ratio;
uint256 pool1Ratio;
uint256 total0Ratio;
uint256 total1Ratio;
uint256 inPositionRatio;
uint256 outOfPositionRatio;
uint256 baseRatio;
uint256 limitRatio;
uint256 base0Ratio;
uint256 base1Ratio;
uint256 limit0Ratio;
uint256 limit1Ratio;
}
// Custom errors
error DuplicatedRange(IMultiPositionManager.Range range);
/**
* @notice Set limit ranges based on limit width and base ranges
* @param s Storage struct
* @param limitWidth Width of limit positions
* @param baseRanges Base position ranges
* @param tickSpacing Tick spacing of the pool
* @param currentTick Current tick of the pool
*/
function setLimitRanges(
SharedStructs.ManagerStorage storage s,
uint24 limitWidth,
IMultiPositionManager.Range[] memory baseRanges,
int24 tickSpacing,
int24 currentTick
) external {
if (limitWidth == 0) {
delete s.limitPositions;
s.limitPositionsLength = 0;
return;
}
if (int24(limitWidth) % tickSpacing != 0) {
// increase `limitWidth` to round up multiple of tickSpacing
limitWidth = uint24((int24(limitWidth) / tickSpacing + 1) * tickSpacing);
}
// Check against NEW base ranges (not historical ones)
uint256 baseRangesLength = baseRanges.length;
for (uint256 i = 0; i < baseRangesLength;) {
int24 rangeWidth = baseRanges[i].upperTick - baseRanges[i].lowerTick;
if (rangeWidth == int24(limitWidth)) {
limitWidth = uint24(int24(limitWidth) + tickSpacing);
break;
}
unchecked {
++i;
}
}
int24 baseTick;
if (currentTick % tickSpacing == 0) {
baseTick = currentTick;
} else if (currentTick % tickSpacing > 0) {
baseTick = (currentTick / tickSpacing) * tickSpacing;
} else {
baseTick = (currentTick / tickSpacing - 1) * tickSpacing;
}
(s.limitPositions[0].lowerTick, s.limitPositions[0].upperTick) =
roundUp(baseTick - int24(limitWidth), baseTick, tickSpacing);
(s.limitPositions[1].lowerTick, s.limitPositions[1].upperTick) =
roundUp(baseTick + tickSpacing, baseTick + tickSpacing + int24(limitWidth), tickSpacing);
// Update limitPositionsLength based on non-empty positions
s.limitPositionsLength = 0;
if (s.limitPositions[0].lowerTick != s.limitPositions[0].upperTick) {
unchecked {
++s.limitPositionsLength;
}
}
if (s.limitPositions[1].lowerTick != s.limitPositions[1].upperTick) {
unchecked {
++s.limitPositionsLength;
}
}
}
/**
* @notice Calculate limit ranges without modifying storage (for SimpleLens preview)
* @param limitWidth Width of limit positions
* @param baseRanges Base position ranges
* @param tickSpacing Tick spacing of the pool
* @param currentTick Current tick of the pool
* @return lowerLimit Lower limit range
* @return upperLimit Upper limit range
*/
function calculateLimitRanges(
uint24 limitWidth,
IMultiPositionManager.Range[] memory baseRanges,
int24 tickSpacing,
int24 currentTick
)
public
pure
returns (IMultiPositionManager.Range memory lowerLimit, IMultiPositionManager.Range memory upperLimit)
{
if (limitWidth == 0) {
return (
IMultiPositionManager.Range({lowerTick: 0, upperTick: 0}),
IMultiPositionManager.Range({lowerTick: 0, upperTick: 0})
);
}
if (int24(limitWidth) % tickSpacing != 0) {
// increase `limitWidth` to round up multiple of tickSpacing
limitWidth = uint24((int24(limitWidth) / tickSpacing + 1) * tickSpacing);
}
// Check against NEW base ranges (not historical ones)
uint256 baseRangesLength = baseRanges.length;
for (uint256 i = 0; i < baseRangesLength;) {
int24 rangeWidth = baseRanges[i].upperTick - baseRanges[i].lowerTick;
if (rangeWidth == int24(limitWidth)) {
limitWidth = uint24(int24(limitWidth) + tickSpacing);
break;
}
unchecked {
++i;
}
}
int24 baseTick;
if (currentTick % tickSpacing == 0) {
baseTick = currentTick;
} else if (currentTick % tickSpacing > 0) {
baseTick = (currentTick / tickSpacing) * tickSpacing;
} else {
baseTick = (currentTick / tickSpacing - 1) * tickSpacing;
}
(lowerLimit.lowerTick, lowerLimit.upperTick) = roundUp(baseTick - int24(limitWidth), baseTick, tickSpacing);
(upperLimit.lowerTick, upperLimit.upperTick) =
roundUp(baseTick + tickSpacing, baseTick + tickSpacing + int24(limitWidth), tickSpacing);
}
/**
* @notice Round up tick values to valid range
* @param tickLower Lower tick
* @param tickUpper Upper tick
* @param tickSpacing Tick spacing of the pool
* @return Rounded lower and upper ticks
*/
function roundUp(int24 tickLower, int24 tickUpper, int24 tickSpacing) public pure returns (int24, int24) {
// Get min/max usable ticks that are aligned with tick spacing
int24 minUsableTick = TickMath.minUsableTick(tickSpacing);
int24 maxUsableTick = TickMath.maxUsableTick(tickSpacing);
// Ensure lower tick is at least the min usable tick
if (tickLower < minUsableTick) {
tickLower = minUsableTick;
}
// Ensure upper tick is at most the max usable tick
if (tickUpper > maxUsableTick) {
tickUpper = maxUsableTick;
}
// Handle invalid ranges
if (tickLower >= tickUpper) {
return (0, 0);
}
return (tickLower, tickUpper);
}
/**
* @notice Check for duplicate ranges
* @param allRanges All ranges to check
*/
function checkRanges(IMultiPositionManager.Range[] memory allRanges) external pure {
uint256 rangesLength = allRanges.length;
for (uint256 i = 0; i < rangesLength;) {
for (uint256 j = i + 1; j < rangesLength;) {
// Skip empty ranges
if (allRanges[j].lowerTick == allRanges[j].upperTick) {
unchecked {
++j;
}
continue;
}
if (
allRanges[i].lowerTick == allRanges[j].lowerTick && allRanges[i].upperTick == allRanges[j].upperTick
) {
revert DuplicatedRange(allRanges[j]);
}
unchecked {
++j;
}
}
unchecked {
++i;
}
}
}
/**
* @notice Get base positions as array
* @param s Storage struct
* @return ranges Array of base positions
*/
function getBasePositionsArray(SharedStructs.ManagerStorage storage s)
public
view
returns (IMultiPositionManager.Range[] memory ranges)
{
uint256 baseLength = s.basePositionsLength;
ranges = new IMultiPositionManager.Range[](baseLength);
for (uint8 i = 0; i < baseLength;) {
ranges[i] = s.basePositions[i];
unchecked {
++i;
}
}
}
/**
* @notice Get limit positions as array
* @param s Storage struct
* @return ranges Array of limit positions (always size 2)
*/
function getLimitPositionsArray(SharedStructs.ManagerStorage storage s)
public
view
returns (IMultiPositionManager.Range[2] memory ranges)
{
ranges[0] = s.limitPositions[0];
ranges[1] = s.limitPositions[1];
}
/**
* @notice Mint liquidity to positions
* @param poolManager Pool manager contract
* @param s Storage struct
* @param liquidities Liquidity amounts for each position
* @param inMin Minimum input amounts per position
*/
function mintLiquidities(
IPoolManager poolManager,
SharedStructs.ManagerStorage storage s,
uint128[] memory liquidities,
uint256[2][] memory inMin
) external returns (IMultiPositionManager.PositionData[] memory) {
IMultiPositionManager.Range[] memory baseRangesArray = getBasePositionsArray(s);
IMultiPositionManager.Range[2] memory limitRangesArray = getLimitPositionsArray(s);
return PoolManagerUtils.mintLiquidities(
poolManager, s.poolKey, baseRangesArray, limitRangesArray, liquidities, inMin
);
}
/**
* @notice Burn liquidity from positions
* @param poolManager Pool manager contract
* @param s Storage struct
* @param shares Number of shares to burn
* @param totalSupply Total supply of shares
* @param outMin Minimum output amounts per position
* @return amount0 Amount of token0 returned
* @return amount1 Amount of token1 returned
*/
function burnLiquidities(
IPoolManager poolManager,
SharedStructs.ManagerStorage storage s,
uint256 shares,
uint256 totalSupply,
uint256[2][] memory outMin
) external returns (uint256 amount0, uint256 amount1) {
if (shares == 0) return (amount0, amount1);
IMultiPositionManager.Range[] memory baseRangesArray = getBasePositionsArray(s);
IMultiPositionManager.Range[2] memory limitRangesArray = getLimitPositionsArray(s);
(amount0, amount1) = PoolManagerUtils.burnLiquidities(
poolManager, s.poolKey, baseRangesArray, limitRangesArray, shares, totalSupply, outMin
);
}
/**
* @notice Get base positions with their data
* @param s Storage struct
* @param poolManager Pool manager contract
* @return ranges Array of base position ranges
* @return positionData Array of position data for each base position
*/
function getBasePositions(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
external
view
returns (IMultiPositionManager.Range[] memory ranges, IMultiPositionManager.PositionData[] memory positionData)
{
ranges = new IMultiPositionManager.Range[](s.basePositionsLength);
positionData = new IMultiPositionManager.PositionData[](s.basePositionsLength);
for (uint8 i = 0; i < s.basePositionsLength;) {
ranges[i] = s.basePositions[i];
(uint128 liquidity, uint256 amount0, uint256 amount1,,) =
PoolManagerUtils.getAmountsOf(poolManager, s.poolKey, ranges[i]);
positionData[i] =
IMultiPositionManager.PositionData({liquidity: liquidity, amount0: amount0, amount1: amount1});
unchecked {
++i;
}
}
}
/**
* @notice Get all positions (base + non-empty limit) with their data
* @param s Storage struct
* @param poolManager Pool manager contract
* @return ranges Array of all position ranges
* @return positionData Array of position data for each position
*/
function getPositions(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
external
view
returns (IMultiPositionManager.Range[] memory ranges, IMultiPositionManager.PositionData[] memory positionData)
{
// Count non-empty limit positions
uint8 nonEmptyLimitPositions = 0;
if (s.limitPositions[0].lowerTick != s.limitPositions[0].upperTick) {
unchecked {
++nonEmptyLimitPositions;
}
}
if (s.limitPositions[1].lowerTick != s.limitPositions[1].upperTick) {
unchecked {
++nonEmptyLimitPositions;
}
}
ranges = new IMultiPositionManager.Range[](s.basePositionsLength + nonEmptyLimitPositions);
positionData = new IMultiPositionManager.PositionData[](s.basePositionsLength + nonEmptyLimitPositions);
// Include base positions
for (uint8 i = 0; i < s.basePositionsLength;) {
ranges[i] = s.basePositions[i];
(uint128 liquidity, uint256 amount0, uint256 amount1,,) =
PoolManagerUtils.getAmountsOf(poolManager, s.poolKey, ranges[i]);
positionData[i] =
IMultiPositionManager.PositionData({liquidity: liquidity, amount0: amount0, amount1: amount1});
unchecked {
++i;
}
}
// Include limit positions only if they are non-empty
uint8 limitIndex = 0;
for (uint8 i = 0; i < 2;) {
if (s.limitPositions[i].lowerTick != s.limitPositions[i].upperTick) {
ranges[s.basePositionsLength + limitIndex] = s.limitPositions[i];
(uint128 liquidity, uint256 amount0, uint256 amount1,,) =
PoolManagerUtils.getAmountsOf(poolManager, s.poolKey, ranges[s.basePositionsLength + limitIndex]);
positionData[s.basePositionsLength + limitIndex] =
IMultiPositionManager.PositionData({liquidity: liquidity, amount0: amount0, amount1: amount1});
unchecked {
++limitIndex;
}
}
unchecked {
++i;
}
}
}
/**
* @notice Calculate token ratios given amounts and price
* @dev Converts token0 to token1 terms and calculates distribution ratios
* @param token0Amount Amount of token0
* @param token1Amount Amount of token1
* @param sqrtPriceX96 Square root price in Q96 format
* @return token0Ratio Ratio of token0 value (1e18 = 100%)
* @return token1Ratio Ratio of token1 value (1e18 = 100%)
*/
function _getTokenRatios(uint256 token0Amount, uint256 token1Amount, uint160 sqrtPriceX96)
internal
pure
returns (uint256 token0Ratio, uint256 token1Ratio)
{
// Handle edge case: no tokens
if (token0Amount == 0 && token1Amount == 0) {
return (0, 0);
}
// Calculate price of token0 in terms of token1 with PRECISION
uint256 price =
FullMath.mulDiv(FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96);
// Convert token0 to token1 terms
uint256 token0InToken1 = FullMath.mulDiv(token0Amount, price, PRECISION);
uint256 totalValueInToken1 = token0InToken1 + token1Amount;
// Calculate ratios (1e18 precision)
token1Ratio = FullMath.mulDiv(token1Amount, RATIO_PRECISION, totalValueInToken1);
token0Ratio = RATIO_PRECISION - token1Ratio;
}
/**
* @notice Sum base position amounts
*/
function _sumBasePositions(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
internal
view
returns (uint256 base0, uint256 base1)
{
uint256 baseLength = s.basePositionsLength;
for (uint8 i = 0; i < baseLength;) {
if (s.basePositions[i].lowerTick != s.basePositions[i].upperTick) {
(, uint256 amt0, uint256 amt1,,) =
PoolManagerUtils.getAmountsOf(poolManager, s.poolKey, s.basePositions[i]);
unchecked {
base0 += amt0;
base1 += amt1;
}
}
unchecked {
++i;
}
}
}
/**
* @notice Sum limit position amounts
*/
function _sumLimitPositions(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
internal
view
returns (uint256 limit0, uint256 limit1)
{
for (uint8 i = 0; i < 2;) {
if (s.limitPositions[i].lowerTick != s.limitPositions[i].upperTick) {
(, uint256 amt0, uint256 amt1,,) =
PoolManagerUtils.getAmountsOf(poolManager, s.poolKey, s.limitPositions[i]);
unchecked {
limit0 += amt0;
limit1 += amt1;
}
}
unchecked {
++i;
}
}
}
/**
* @notice Calculate in-position and base/limit ratios
*/
function _calculateDeploymentRatios(
uint256 total0,
uint256 total1,
uint256 position0,
uint256 position1,
uint256 base0,
uint256 base1,
uint160 sqrtPriceX96
)
internal
pure
returns (uint256 inPositionRatio, uint256 outOfPositionRatio, uint256 baseRatio, uint256 limitRatio)
{
// In-position ratios
if (total0 == 0 && total1 == 0) {
inPositionRatio = 0;
outOfPositionRatio = 0;
} else {
uint256 price = FullMath.mulDiv(
FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96
);
uint256 totalVal = FullMath.mulDiv(total0, price, PRECISION) + total1;
uint256 posVal = FullMath.mulDiv(position0, price, PRECISION) + position1;
inPositionRatio = FullMath.mulDiv(posVal, RATIO_PRECISION, totalVal);
outOfPositionRatio = RATIO_PRECISION - inPositionRatio;
}
// Base/limit ratios
if (position0 == 0 && position1 == 0) {
baseRatio = 0;
limitRatio = 0;
} else {
uint256 price = FullMath.mulDiv(
FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96
);
uint256 baseVal = FullMath.mulDiv(base0, price, PRECISION) + base1;
uint256 posVal = FullMath.mulDiv(position0, price, PRECISION) + position1;
baseRatio = FullMath.mulDiv(baseVal, RATIO_PRECISION, posVal);
limitRatio = RATIO_PRECISION - baseRatio;
}
}
/**
* @notice Get total portfolio value denominated in each token
* @dev Converts entire portfolio value to both token0 and token1 terms
* @param s Storage struct
* @param poolManager The pool manager instance
* @return totalValueInToken0 Total value in token0 terms
* @return totalValueInToken1 Total value in token1 terms
*/
function getTotalValuesInOneToken(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
external
view
returns (uint256 totalValueInToken0, uint256 totalValueInToken1)
{
// Get current price
uint160 sqrtPriceX96;
(sqrtPriceX96,,,) = poolManager.getSlot0(s.poolKey.toId());
// Get total amounts (positions + fees + idle)
uint256 total0;
uint256 total1;
(total0, total1,,) = WithdrawLogic.getTotalAmounts(s, poolManager);
// Handle edge case: no tokens
if (total0 == 0 && total1 == 0) {
return (0, 0);
}
// Calculate price of token0 in terms of token1 with PRECISION
// price = (sqrtPriceX96)² / 2^192
uint256 price =
FullMath.mulDiv(FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96);
// Convert token0 to token1 terms
uint256 token0InToken1 = FullMath.mulDiv(total0, price, PRECISION);
totalValueInToken1 = token0InToken1 + total1;
// Convert token1 to token0 terms
// token1InToken0 = token1 / price = token1 * PRECISION / price
uint256 token1InToken0 = FullMath.mulDiv(total1, PRECISION, price);
totalValueInToken0 = total0 + token1InToken0;
}
/**
* @notice Get comprehensive ratios for token distribution and position deployment
* @dev Returns 8 ratios that provide complete picture of vault state
* @param s Storage struct
* @param poolManager The pool manager instance
* @return ratios Struct containing all ratio values (1e18 = 100%)
*/
function getRatios(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
external
view
returns (Ratios memory ratios)
{
uint160 sqrtPriceX96;
(sqrtPriceX96,,,) = poolManager.getSlot0(s.poolKey.toId());
// Get all amounts once (avoid duplicate calls)
uint256 total0;
uint256 total1;
(total0, total1,,) = WithdrawLogic.getTotalAmounts(s, poolManager);
uint256 base0;
uint256 base1;
(base0, base1) = _sumBasePositions(s, poolManager);
uint256 limit0;
uint256 limit1;
(limit0, limit1) = _sumLimitPositions(s, poolManager);
uint256 position0;
uint256 position1;
unchecked {
position0 = base0 + limit0;
position1 = base1 + limit1;
}
// Calculate all token ratios
(ratios.pool0Ratio, ratios.pool1Ratio) = _getTokenRatios(position0, position1, sqrtPriceX96);
(ratios.total0Ratio, ratios.total1Ratio) = _getTokenRatios(total0, total1, sqrtPriceX96);
(ratios.base0Ratio, ratios.base1Ratio) = _getTokenRatios(base0, base1, sqrtPriceX96);
(ratios.limit0Ratio, ratios.limit1Ratio) = _getTokenRatios(limit0, limit1, sqrtPriceX96);
// Calculate deployment ratios in scoped block
{
// In-position ratios
if (total0 == 0 && total1 == 0) {
ratios.inPositionRatio = 0;
ratios.outOfPositionRatio = 0;
} else {
uint256 price = FullMath.mulDiv(
FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96
);
uint256 totalVal = FullMath.mulDiv(total0, price, PRECISION) + total1;
uint256 posVal = FullMath.mulDiv(position0, price, PRECISION) + position1;
ratios.inPositionRatio = FullMath.mulDiv(posVal, RATIO_PRECISION, totalVal);
ratios.outOfPositionRatio = RATIO_PRECISION - ratios.inPositionRatio;
}
// Base/limit ratios
if (position0 == 0 && position1 == 0) {
ratios.baseRatio = 0;
ratios.limitRatio = 0;
} else {
uint256 price = FullMath.mulDiv(
FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96
);
uint256 baseVal = FullMath.mulDiv(base0, price, PRECISION) + base1;
uint256 posVal = FullMath.mulDiv(position0, price, PRECISION) + position1;
ratios.baseRatio = FullMath.mulDiv(baseVal, RATIO_PRECISION, posVal);
ratios.limitRatio = RATIO_PRECISION - ratios.baseRatio;
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Gas optimized reentrancy protection for smart contracts.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ReentrancyGuard.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
uint256 private locked = 1;
modifier nonReentrant() virtual {
require(locked == 1, "REENTRANCY");
locked = 2;
_;
locked = 1;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
library Errors {
error ZeroAddress();
error UnauthorizedCaller(address caller);
error NotInitialized();
error OracleOperationFailed(string operation, string reason);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
/// @title TruncatedOracle
/// @notice Provides observation storage and TWAP queries for paged oracle architecture
/// @dev Designed to work with 512-slot pages, supporting lazy allocation
library TruncatedOracle {
/// @notice Maximum number of observations across all pages
/// @dev With PAGE_SIZE=512, this allows 16 full pages (8192 / 512 = 16)
uint16 public constant MAX_CARDINALITY_ALLOWED = 8192;
/// @notice Thrown when trying to observe a price that is older than the oldest recorded price
error TargetPredatesOldestObservation(uint32 oldestTimestamp, uint32 targetTimestamp);
struct Observation {
// the block timestamp of the observation
uint32 blockTimestamp;
// the tick accumulator, i.e. tick * time elapsed since the pool was first initialized
int56 tickCumulative;
// the seconds per liquidity accumulator, i.e. seconds elapsed / max(1, liquidity) since the pool was first initialized
uint160 secondsPerLiquidityCumulativeX128;
// whether or not the observation is initialized
bool initialized;
}
/// @notice Initialize the first observation in a page
/// @param self The storage array (512 slots)
/// @param time The time of the observation
function initialize(Observation[512] storage self, uint32 time, int24) internal {
self[0] = Observation({
blockTimestamp: time,
tickCumulative: 0,
secondsPerLiquidityCumulativeX128: 0,
initialized: true
});
}
/// @notice Transforms a previous observation into a new observation, given the passage of time and the current tick and liquidity values
/// @param last The specified observation to be transformed
/// @param blockTimestamp The timestamp of the new observation
/// @param tick The active tick at the time of the new observation
/// @param liquidity The total in-range liquidity at the time of the new observation
/// @return Observation The newly populated observation
function transform(
Observation memory last,
uint32 blockTimestamp,
int24 tick,
uint128 liquidity
) private pure returns (Observation memory) {
unchecked {
uint32 delta = blockTimestamp - last.blockTimestamp;
return Observation({
blockTimestamp: blockTimestamp,
tickCumulative: last.tickCumulative + int56(tick) * int56(uint56(delta)),
secondsPerLiquidityCumulativeX128: last.secondsPerLiquidityCumulativeX128
+ ((uint160(delta) << 128) / (liquidity > 0 ? liquidity : 1)),
initialized: true
});
}
}
/// @notice Writes an oracle observation to the page
/// @dev Writable at most once per block within a page
/// @param self The stored oracle page (512 slots)
/// @param index The index of the observation that was most recently written to the observations array
/// @param blockTimestamp The timestamp of the new observation
/// @param tick The active tick at the time of the new observation
/// @param liquidity The total in-range liquidity at the time of the new observation
/// @param cardinality The number of populated observations in this page
/// @param cardinalityNext The new length of the observations array after this write, capped at page size (512)
/// @return indexUpdated The new index of the most recently written element in the oracle array
/// @return cardinalityUpdated The new cardinality of the observations array
function write(
Observation[512] storage self,
uint16 index,
uint32 blockTimestamp,
int24 tick,
uint128 liquidity,
uint16 cardinality,
uint16 cardinalityNext
) internal returns (uint16 indexUpdated, uint16 cardinalityUpdated) {
unchecked {
Observation memory last = self[index];
// early return if we've already written an observation this block
if (last.blockTimestamp == blockTimestamp) {
return (index, cardinality);
}
// if the conditions are right, we can bump the cardinality
if (cardinalityNext > cardinality && index == (cardinality - 1)) {
cardinalityUpdated = cardinalityNext;
} else {
cardinalityUpdated = cardinality;
}
// increment index wrapping at page size (512)
indexUpdated = (index + 1) % 512;
self[indexUpdated] = transform(last, blockTimestamp, tick, liquidity);
}
}
/// @notice Prepares the page to store observations by setting next-cardinality
/// @dev Does not allocate storage; cardinality is incremented on first write
/// @param current The current cardinality
/// @param next The proposed next cardinality (what we want to grow to)
/// @return The new cardinality-next value, capped at 512 and MAX_CARDINALITY_ALLOWED
function grow(
Observation[512] storage,
uint16 current,
uint16 next
) internal pure returns (uint16) {
unchecked {
if (next <= current) return current;
// Cap at page size
if (next > 512) next = 512;
// Cap at global maximum
if (next > MAX_CARDINALITY_ALLOWED) next = MAX_CARDINALITY_ALLOWED;
return next;
}
}
/// @notice comparator for 32-bit timestamps
/// @dev safe for 0 or 1 overflows, a and b _must_ be chronologically before or equal to time
/// @param time A timestamp truncated to 32 bits
/// @param a A comparison timestamp from which to determine the relative position of `time`
/// @param b A comparison timestamp from which to determine the relative position of `time`
/// @return Whether `a` is chronologically <= `b`
function lte(
uint32 time,
uint32 a,
uint32 b
) private pure returns (bool) {
unchecked {
// if there hasn't been overflow, no need to adjust
if (a <= time && b <= time) return a <= b;
uint256 aAdjusted = a > time ? a : a + 2 ** 32;
uint256 bAdjusted = b > time ? b : b + 2 ** 32;
return aAdjusted <= bAdjusted;
}
}
/// @notice Fetches the observations beforeOrAt and atOrAfter a target, i.e. where [beforeOrAt, atOrAfter] is satisfied
/// @dev Assumes there is at least 1 initialized observation
/// @dev Used by observeSingle() to compute time-weighted averages
/// @param self The stored oracle array
/// @param time The current block.timestamp
/// @param target The timestamp at which the reserved observation should be for
/// @param tick The active tick at the time of the returned or simulated observation
/// @param index The index of the observation that was most recently written to the observations array
/// @param liquidity The total pool liquidity at the time of the call
/// @param cardinality The number of populated elements in the oracle array
/// @return beforeOrAt The observation recorded before, or at, the target
/// @return atOrAfter The observation recorded at, or after, the target
function getSurroundingObservations(
Observation[512] storage self,
uint32 time,
uint32 target,
int24 tick,
uint16 index,
uint128 liquidity,
uint16 cardinality
) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
unchecked {
// optimistically set before to the newest observation
beforeOrAt = self[index];
// if the target is chronologically at or after the newest observation, we can early return
if (lte(time, beforeOrAt.blockTimestamp, target)) {
if (beforeOrAt.blockTimestamp == target) {
return (beforeOrAt, atOrAfter);
} else {
return (beforeOrAt, transform(beforeOrAt, target, tick, liquidity));
}
}
// now, set before to the oldest observation
beforeOrAt = self[0];
if (!beforeOrAt.initialized) beforeOrAt = self[0];
// ensure that the target is chronologically at or after the oldest observation
if (!lte(time, beforeOrAt.blockTimestamp, target)) {
revert TargetPredatesOldestObservation(beforeOrAt.blockTimestamp, target);
}
// perform binary search
return binarySearch(self, time, target, index, cardinality);
}
}
/// @notice Fetches the observations beforeOrAt and atOrAfter a given target using binary search
/// @param self The stored oracle array
/// @param time The current block.timestamp
/// @param target The timestamp at which the reserved observation should be for
/// @param cardinality The number of populated elements in the oracle array
/// @return beforeOrAt The observation which occurred at, or before, the given timestamp
/// @return atOrAfter The observation which occurred at, or after, the given timestamp
function binarySearch(
Observation[512] storage self,
uint32 time,
uint32 target,
uint16,
uint16 cardinality
) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
unchecked {
uint256 l = 0;
uint256 r = cardinality - 1;
uint256 i;
while (true) {
i = (l + r) / 2;
beforeOrAt = self[i];
// we've landed on an uninitialized tick, keep searching higher (more recently)
if (!beforeOrAt.initialized) {
l = i + 1;
continue;
}
atOrAfter = self[i + 1];
bool targetAtOrAfter = lte(time, beforeOrAt.blockTimestamp, target);
// check if we've found the answer!
if (targetAtOrAfter && lte(time, target, atOrAfter.blockTimestamp)) {
break;
}
if (!targetAtOrAfter) r = i - 1;
else l = i + 1;
}
}
}
/// @notice Observes a single point in time
/// @param self The stored oracle array
/// @param time The current block timestamp
/// @param secondsAgo The amount of time to look back, in seconds, from the current block timestamp
/// @param tick The current tick
/// @param index The index of the observation that was most recently written to the observations array
/// @param liquidity The current in-range pool liquidity
/// @param cardinality The number of populated elements in the oracle array
/// @return tickCumulative The tick * time elapsed since the pool was first initialized, as of `secondsAgo`
/// @return secondsPerLiquidityCumulativeX128 The time elapsed / max(1, liquidity) since the pool was first initialized, as of `secondsAgo`
function observeSingle(
Observation[512] storage self,
uint32 time,
uint32 secondsAgo,
int24 tick,
uint16 index,
uint128 liquidity,
uint16 cardinality
) internal view returns (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) {
unchecked {
if (secondsAgo == 0) {
Observation memory last = self[index];
if (last.blockTimestamp != time) {
last = transform(last, time, tick, liquidity);
}
return (last.tickCumulative, last.secondsPerLiquidityCumulativeX128);
}
uint32 target = time - secondsAgo;
(Observation memory beforeOrAt, Observation memory atOrAfter) =
getSurroundingObservations(self, time, target, tick, index, liquidity, cardinality);
if (target == beforeOrAt.blockTimestamp) {
return (beforeOrAt.tickCumulative, beforeOrAt.secondsPerLiquidityCumulativeX128);
} else if (target == atOrAfter.blockTimestamp) {
return (atOrAfter.tickCumulative, atOrAfter.secondsPerLiquidityCumulativeX128);
} else {
// we're in the middle, interpolate
uint32 observationTimeDelta = atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp;
uint32 targetDelta = target - beforeOrAt.blockTimestamp;
tickCumulative = beforeOrAt.tickCumulative
+ ((atOrAfter.tickCumulative - beforeOrAt.tickCumulative) / int56(uint56(observationTimeDelta)))
* int56(uint56(targetDelta));
secondsPerLiquidityCumulativeX128 = beforeOrAt.secondsPerLiquidityCumulativeX128
+ uint160(
(uint256(
atOrAfter.secondsPerLiquidityCumulativeX128 - beforeOrAt.secondsPerLiquidityCumulativeX128
) * targetDelta) / observationTimeDelta
);
}
}
}
/// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`
/// @dev Reverts if `secondsAgos` > oldest observation
/// @param self The stored oracle array
/// @param time The current block.timestamp
/// @param secondsAgos Each amount of time to look back, in seconds, at which point to return an observation
/// @param tick The current tick
/// @param index The index of the observation that was most recently written to the observations array
/// @param liquidity The current in-range pool liquidity
/// @param cardinality The number of populated elements in the oracle array
/// @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each `secondsAgo`
/// @return secondsPerLiquidityCumulativeX128s The cumulative seconds / max(1, liquidity) since the pool was first initialized, as of each `secondsAgo`
function observe(
Observation[512] storage self,
uint32 time,
uint32[] memory secondsAgos,
int24 tick,
uint16 index,
uint128 liquidity,
uint16 cardinality
) internal view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) {
require(cardinality > 0, "I");
tickCumulatives = new int56[](secondsAgos.length);
secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);
unchecked {
for (uint256 i = 0; i < secondsAgos.length; i++) {
(tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i]) =
observeSingle(self, time, secondsAgos[i], tick, index, liquidity, cardinality);
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.20;
import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*/
library ERC1967Utils {
// We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
// This will be fixed in Solidity 0.8.21. At that point we should remove these events.
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IImmutableState} from "../interfaces/IImmutableState.sol";
/// @title Immutable State
/// @notice A collection of immutable state variables, commonly used across multiple contracts
contract ImmutableState is IImmutableState {
/// @inheritdoc IImmutableState
IPoolManager public immutable poolManager;
/// @notice Thrown when the caller is not PoolManager
error NotPoolManager();
/// @notice Only allow calls from the PoolManager contract
modifier onlyPoolManager() {
if (msg.sender != address(poolManager)) revert NotPoolManager();
_;
}
constructor(IPoolManager _poolManager) {
poolManager = _poolManager;
}
}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
/*//////////////////////////////////////////////////////////////
SIMPLIFIED FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
uint256 internal constant MAX_UINT256 = 2**256 - 1;
uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.
function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
}
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
}
function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
}
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
}
/*//////////////////////////////////////////////////////////////
LOW LEVEL FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
function mulDivDown(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
revert(0, 0)
}
// Divide x * y by the denominator.
z := div(mul(x, y), denominator)
}
}
function mulDivUp(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
revert(0, 0)
}
// If x * y modulo the denominator is strictly greater than 0,
// 1 is added to round up the division of x * y by the denominator.
z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))
}
}
function rpow(
uint256 x,
uint256 n,
uint256 scalar
) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
switch x
case 0 {
switch n
case 0 {
// 0 ** 0 = 1
z := scalar
}
default {
// 0 ** n = 0
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
// If n is even, store scalar in z for now.
z := scalar
}
default {
// If n is odd, store x in z for now.
z := x
}
// Shifting right by 1 is like dividing by 2.
let half := shr(1, scalar)
for {
// Shift n right by 1 before looping to halve it.
n := shr(1, n)
} n {
// Shift n right by 1 each iteration to halve it.
n := shr(1, n)
} {
// Revert immediately if x ** 2 would overflow.
// Equivalent to iszero(eq(div(xx, x), x)) here.
if shr(128, x) {
revert(0, 0)
}
// Store x squared.
let xx := mul(x, x)
// Round to the nearest number.
let xxRound := add(xx, half)
// Revert if xx + half overflowed.
if lt(xxRound, xx) {
revert(0, 0)
}
// Set x to scaled xxRound.
x := div(xxRound, scalar)
// If n is even:
if mod(n, 2) {
// Compute z * x.
let zx := mul(z, x)
// If z * x overflowed:
if iszero(eq(div(zx, x), z)) {
// Revert if x is non-zero.
if iszero(iszero(x)) {
revert(0, 0)
}
}
// Round to the nearest number.
let zxRound := add(zx, half)
// Revert if zx + half overflowed.
if lt(zxRound, zx) {
revert(0, 0)
}
// Return properly scaled zxRound.
z := div(zxRound, scalar)
}
}
}
}
}
/*//////////////////////////////////////////////////////////////
GENERAL NUMBER UTILITIES
//////////////////////////////////////////////////////////////*/
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let y := x // We start y at x, which will help us make our initial estimate.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// We check y >= 2^(k + 8) but shift right by k bits
// each branch to ensure that if x >= 256, then y >= 256.
if iszero(lt(y, 0x10000000000000000000000000000000000)) {
y := shr(128, y)
z := shl(64, z)
}
if iszero(lt(y, 0x1000000000000000000)) {
y := shr(64, y)
z := shl(32, z)
}
if iszero(lt(y, 0x10000000000)) {
y := shr(32, y)
z := shl(16, z)
}
if iszero(lt(y, 0x1000000)) {
y := shr(16, y)
z := shl(8, z)
}
// Goal was to get z*z*y within a small factor of x. More iterations could
// get y in a tighter range. Currently, we will have y in [256, 256*2^16).
// We ensured y >= 256 so that the relative difference between y and y+1 is small.
// That's not possible if x < 256 but we can just verify those cases exhaustively.
// Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.
// Correctness can be checked exhaustively for x < 256, so we assume y >= 256.
// Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.
// For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range
// (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.
// Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate
// sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.
// There is no overflow risk here since y < 2^136 after the first branch above.
z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If x+1 is a perfect square, the Babylonian method cycles between
// floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
// Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.
// If you don't care whether the floor or ceil square root is returned, you can remove this statement.
z := sub(z, lt(div(x, z), z))
}
}
function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Mod x by y. Note this will return
// 0 instead of reverting if y is zero.
z := mod(x, y)
}
}
function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
// Divide x by y. Note this will return
// 0 instead of reverting if y is zero.
r := div(x, y)
}
}
function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Add 1 to x * y if x % y > 0. Note this will
// return 0 instead of reverting if y is zero.
z := add(gt(mod(x, y), 0), div(x, y))
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
interface IOrderBookFactory {
function regularHookFeePercentage() external view returns (uint256);
function dynamicHookFeePercentage() external view returns (uint256);
function antiSnipeHookFeePercentage() external view returns (uint256);
function antiSnipeDynamicHookFeePercentage() external view returns (uint256);
/// @notice Returns the address of the strategy that reserved a pool, or address(0) if not reserved
/// @param poolId The pool ID to check
/// @return The address of the reserving strategy, or address(0)
function reservedPools(bytes32 poolId) external view returns (address);
/// @notice Compute the CREATE2 address for a volatility limit order hook without deploying
/// @dev Pure CREATE2 math - cheap view function. Use for poolId computation before lazy deployment.
/// @param hookOwner The owner of the hook
/// @param salt The pre-computed salt from HookMiner
/// @return hookAddr The predicted hook address
function computeVolatilityLimitOrderHookAddress(
address hookOwner,
bytes32 salt
) external view returns (address hookAddr);
/// @notice Compute the CREATE2 address for a volatility fee-only hook without deploying
/// @dev Pure CREATE2 math - cheap view function. Use for poolId computation before lazy deployment.
/// @param hookOwner The owner of the hook
/// @param salt The pre-computed salt from HookMiner
/// @return hookAddr The predicted hook address
function computeVolatilityFeeHookAddress(
address hookOwner,
bytes32 salt
) external view returns (address hookAddr);
/// @notice Compute the pool ID for a volatility dynamic limit order pool
/// @dev Uses cheap CREATE2 address computation instead of expensive HookMiner.find().
/// Hook will be deployed lazily during pool creation.
/// @param hookOwner The owner of the hook (determines hook address)
/// @param salt The pre-computed salt for the hook
/// @param currency0 The first currency
/// @param currency1 The second currency
/// @param tickSpacing The tick spacing
/// @return poolId The computed pool ID
function computePoolIdForVolatilityLimitOrder(
address hookOwner,
bytes32 salt,
Currency currency0,
Currency currency1,
int24 tickSpacing
) external view returns (bytes32 poolId);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Math library for liquidity
library LiquidityMath {
/// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
/// @param x The liquidity before change
/// @param y The delta by which liquidity should be changed
/// @return z The liquidity delta
function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
assembly ("memory-safe") {
z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))
if shr(128, z) {
// revert SafeCastOverflow()
mstore(0, 0x93dafdf1)
revert(0x1c, 0x04)
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
* ```
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {ImmutableState} from "./ImmutableState.sol";
/// @title Safe Callback
/// @notice A contract that only allows the Uniswap v4 PoolManager to call the unlockCallback
abstract contract SafeCallback is ImmutableState, IUnlockCallback {
constructor(IPoolManager _poolManager) ImmutableState(_poolManager) {}
/// @inheritdoc IUnlockCallback
/// @dev We force the onlyPoolManager modifier by exposing a virtual function after the onlyPoolManager check.
function unlockCallback(bytes calldata data) external onlyPoolManager returns (bytes memory) {
return _unlockCallback(data);
}
/// @dev to be implemented by the child contract, to safely guarantee the logic is only executed by the PoolManager
function _unlockCallback(bytes calldata data) internal virtual returns (bytes memory);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {LiquidityAmounts} from "v4-periphery/lib/v4-core/test/utils/LiquidityAmounts.sol";
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.sol";
import {IMultiPositionFactory} from "../interfaces/IMultiPositionFactory.sol";
import {ILiquidityStrategy} from "../strategies/ILiquidityStrategy.sol";
import {SharedStructs} from "../base/SharedStructs.sol";
import {PoolManagerUtils} from "./PoolManagerUtils.sol";
import {RebalanceLogic} from "./RebalanceLogic.sol";
import {PositionLogic} from "./PositionLogic.sol";
/**
* @title WithdrawLogic
* @notice Library containing all withdrawal-related logic for MultiPositionManager
*/
library WithdrawLogic {
using PoolIdLibrary for PoolKey;
using StateLibrary for IPoolManager;
using SafeERC20 for IERC20;
uint256 constant PRECISION = 1e36;
// Struct to reduce stack depth
struct CustomWithdrawParams {
uint256 amount0Desired;
uint256 amount1Desired;
address to;
uint256[2][] outMin;
uint256 totalSupply;
uint256 senderBalance;
address sender;
}
// Custom errors
error ZeroValue();
error ZeroAddress();
error InvalidRecipient();
error AmountMustBePositive();
error InsufficientBalance();
error NoSharesExist();
error OutMinLengthMismatch();
// Events (will be emitted by main contract)
event Withdraw(address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 shares, uint256 totalSupply, uint256 amount0, uint256 amount1);
event WithdrawCustom(address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1);
// Withdrawal path enum
enum WithdrawPath {
USE_CURRENT_BALANCE, // Step 1: sufficient idle balance
USE_BALANCE_PLUS_FEES, // Step 2: need zeroBurn for fees
BURN_AND_REBALANCE // Step 3: burn all + rebalance remaining
}
// Withdrawal path info struct
struct WithdrawPathInfo {
WithdrawPath path;
uint256 currentBalance0;
uint256 currentBalance1;
uint256 total0;
uint256 total1;
uint256 totalFee0;
uint256 totalFee1;
}
/**
* @notice Determine which withdrawal path to take (shared by processWithdrawCustom and preview)
* @param s Storage struct
* @param poolManager Pool manager contract
* @param amount0Desired Amount of token0 to withdraw
* @param amount1Desired Amount of token1 to withdraw
* @return info Withdrawal path information
*/
function determineWithdrawPath(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
uint256 amount0Desired,
uint256 amount1Desired
) internal view returns (WithdrawPathInfo memory info) {
// Get totals
(info.total0, info.total1, info.totalFee0, info.totalFee1) = getTotalAmounts(s, poolManager);
// Get current balances
info.currentBalance0 = s.currency0.balanceOfSelf();
info.currentBalance1 = s.currency1.balanceOfSelf();
// PATH 1: Current balance sufficient
if (info.currentBalance0 >= amount0Desired && info.currentBalance1 >= amount1Desired) {
info.path = WithdrawPath.USE_CURRENT_BALANCE;
return info;
}
// PATH 2: Balance + fees sufficient
uint256 availableWithFees0 = info.currentBalance0 + info.totalFee0;
uint256 availableWithFees1 = info.currentBalance1 + info.totalFee1;
if (availableWithFees0 >= amount0Desired && availableWithFees1 >= amount1Desired) {
info.path = WithdrawPath.USE_BALANCE_PLUS_FEES;
return info;
}
// PATH 3: Need to burn and rebalance
info.path = WithdrawPath.BURN_AND_REBALANCE;
}
/**
* @notice Process a standard withdrawal
* @param s Storage struct
* @param poolManager Pool manager contract
* @param shares Number of shares to burn
* @param to Recipient address
* @param outMin Minimum output amounts per position
* @param totalSupply Current total supply
* @param sender Address of the caller
* @param withdrawToWallet If true, transfers tokens to 'to'. If false, keeps tokens in contract.
* @return amount0 Amount of token0 withdrawn
* @return amount1 Amount of token1 withdrawn
*/
function processWithdraw(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
uint256 shares,
address to,
uint256[2][] memory outMin,
uint256 totalSupply,
address sender,
bool withdrawToWallet
) external returns (uint256 amount0, uint256 amount1) {
if (shares == 0) revert ZeroValue();
if (withdrawToWallet && to == address(0)) revert ZeroAddress();
if (outMin.length != s.basePositionsLength + s.limitPositionsLength) revert OutMinLengthMismatch();
// Execute withdrawal via callback
{
bytes memory params = abi.encode(shares, outMin);
bytes memory result = poolManager.unlock(abi.encode(IMultiPositionManager.Action.WITHDRAW, params));
(amount0, amount1) = abi.decode(result, (uint256, uint256));
}
// Calculate and transfer unused amounts only if withdrawing to wallet
if (withdrawToWallet) {
// Transfer withdrawn amounts
if (amount0 != 0) s.currency0.transfer(to, amount0);
if (amount1 != 0) s.currency1.transfer(to, amount1);
// Calculate and transfer unused amounts in a scoped block
{
uint256 unusedAmount0 = FullMath.mulDiv(s.currency0.balanceOfSelf(), shares, totalSupply);
uint256 unusedAmount1 = FullMath.mulDiv(s.currency1.balanceOfSelf(), shares, totalSupply);
if (unusedAmount0 != 0) {
unchecked {
amount0 += unusedAmount0;
}
s.currency0.transfer(to, unusedAmount0);
}
if (unusedAmount1 != 0) {
unchecked {
amount1 += unusedAmount1;
}
s.currency1.transfer(to, unusedAmount1);
}
}
// Note: Main contract will handle burning shares
emit Withdraw(sender, to, shares, amount0, amount1);
} else {
// For non-wallet withdrawals, just calculate unused amounts for reporting
{
uint256 unusedAmount0 = FullMath.mulDiv(s.currency0.balanceOfSelf(), shares, totalSupply);
uint256 unusedAmount1 = FullMath.mulDiv(s.currency1.balanceOfSelf(), shares, totalSupply);
unchecked {
amount0 += unusedAmount0;
amount1 += unusedAmount1;
}
}
// Tokens stay in contract, emit Burn event
emit Burn(sender, shares, totalSupply, amount0, amount1);
}
}
/**
* @notice Helper function to transfer tokens
*/
function _transferWithdrawCustom(
SharedStructs.ManagerStorage storage s,
address to,
uint256 amount0Out,
uint256 amount1Out
) private {
if (amount0Out != 0) {
s.currency0.transfer(to, amount0Out);
}
if (amount1Out != 0) {
s.currency1.transfer(to, amount1Out);
}
}
/**
* @notice Helper function to transfer tokens and emit event
*/
function _transferAndEmitWithdrawCustom(
SharedStructs.ManagerStorage storage s,
address sender,
address to,
uint256 amount0Out,
uint256 amount1Out,
uint256 sharesBurned
) private {
_transferWithdrawCustom(s, to, amount0Out, amount1Out);
emit WithdrawCustom(sender, to, sharesBurned, amount0Out, amount1Out);
}
/**
* @notice Process a custom withdrawal (both tokens)
* @param s Storage struct
* @param poolManager Pool manager contract
* @param params Withdrawal parameters bundled to reduce stack depth
* @return amount0Out Amount of token0 withdrawn
* @return amount1Out Amount of token1 withdrawn
* @return sharesBurned Number of shares to burn
*/
function processWithdrawCustom(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
CustomWithdrawParams memory params
) external returns (uint256 amount0Out, uint256 amount1Out, uint256 sharesBurned) {
if (params.to == address(0)) revert InvalidRecipient();
if (params.amount0Desired == 0 && params.amount1Desired == 0) revert AmountMustBePositive();
// Determine withdrawal path using shared helper
WithdrawPathInfo memory pathInfo =
determineWithdrawPath(s, poolManager, params.amount0Desired, params.amount1Desired);
// Check if requested amounts exceed total available
if (params.amount0Desired > pathInfo.total0) revert InsufficientBalance();
if (params.amount1Desired > pathInfo.total1) revert InsufficientBalance();
// Calculate shares to burn based on combined withdrawal value
{
sharesBurned = calculateSharesToBurn(
s,
poolManager,
params.amount0Desired,
params.amount1Desired,
params.totalSupply,
pathInfo.total0,
pathInfo.total1
);
if (sharesBurned > params.senderBalance) revert InsufficientBalance();
}
// Execute withdrawal based on path
if (pathInfo.path == WithdrawPath.USE_CURRENT_BALANCE) {
// Step 1: Direct transfer from current balance
amount0Out = params.amount0Desired;
amount1Out = params.amount1Desired;
_transferAndEmitWithdrawCustom(s, params.sender, params.to, amount0Out, amount1Out, sharesBurned);
return (amount0Out, amount1Out, sharesBurned);
}
if (pathInfo.path == WithdrawPath.USE_BALANCE_PLUS_FEES) {
// Step 2: Collect fees then transfer
zeroBurnAllWithoutUnlock(s, poolManager);
amount0Out = params.amount0Desired;
amount1Out = params.amount1Desired;
_transferAndEmitWithdrawCustom(s, params.sender, params.to, amount0Out, amount1Out, sharesBurned);
return (amount0Out, amount1Out, sharesBurned);
}
// Step 3: Partial position burn to get sufficient assets
// Calculate how much of positions to burn
uint256 positionSharesToBurn = calculatePositionSharesToBurn(
s, poolManager, params.amount0Desired, params.amount1Desired, params.totalSupply
);
// Execute partial withdrawal using standard WITHDRAW action
bytes memory withdrawParams = abi.encode(positionSharesToBurn, params.outMin);
poolManager.unlock(abi.encode(IMultiPositionManager.Action.WITHDRAW, withdrawParams));
// The WITHDRAW action has:
// 1. Collected ALL fees from positions
// 2. Burned liquidity pro-rata
// 3. Taken pro-rata share of unused balance
// Get balances after burn
uint256 balance0 = s.currency0.balanceOfSelf();
uint256 balance1 = s.currency1.balanceOfSelf();
// Transfer actual balance when short due to rounding, otherwise transfer requested amount
amount0Out = balance0 < params.amount0Desired ? balance0 : params.amount0Desired;
amount1Out = balance1 < params.amount1Desired ? balance1 : params.amount1Desired;
_transferWithdrawCustom(s, params.to, amount0Out, amount1Out);
// NO REBALANCING - excess remains as unused balance
emit WithdrawCustom(params.sender, params.to, sharesBurned, amount0Out, amount1Out);
return (amount0Out, amount1Out, sharesBurned);
}
/**
* @notice Calculate minimum shares worth of positions to burn to get desired amounts
* @dev PUBLIC so SimpleLens can call it directly
* @param s Storage struct
* @param poolManager Pool manager contract
* @param amount0Desired Amount of token0 needed
* @param amount1Desired Amount of token1 needed
* @param totalSupply Total supply of shares
* @return positionShares Shares worth of positions to burn
*/
function calculatePositionSharesToBurn(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
uint256 amount0Desired,
uint256 amount1Desired,
uint256 totalSupply
) internal view returns (uint256 positionShares) {
if (totalSupply == 0) revert NoSharesExist();
// Get total amounts (positions + fees + unused balances)
(uint256 total0, uint256 total1,,) = getTotalAmounts(s, poolManager);
// Calculate shares needed for each token (ceiling division for safety)
uint256 sharesForToken0;
uint256 sharesForToken1;
if (amount0Desired != 0 && total0 != 0) {
// Ceiling division
unchecked {
sharesForToken0 = (amount0Desired * totalSupply + total0 - 1) / total0;
}
}
if (amount1Desired != 0 && total1 != 0) {
unchecked {
sharesForToken1 = (amount1Desired * totalSupply + total1 - 1) / total1;
}
}
// Take maximum to ensure both requirements met
positionShares = sharesForToken0 > sharesForToken1 ? sharesForToken0 : sharesForToken1;
// Cap at total supply
if (positionShares > totalSupply) {
positionShares = totalSupply;
}
}
/**
* @notice Calculate shares to burn for custom withdrawal (both tokens)
*/
function calculateSharesToBurn(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
uint256 amount0Desired,
uint256 amount1Desired,
uint256 totalSupply,
uint256 pool0,
uint256 pool1
) internal view returns (uint256 shares) {
if (totalSupply == 0) revert NoSharesExist();
// Get current price from pool
(uint160 sqrtPriceX96,,,) = poolManager.getSlot0(s.poolKey.toId());
// Calculate price of token0 in terms of token1 with PRECISION
uint256 price =
FullMath.mulDiv(FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96);
// Calculate total withdrawal value in token1 terms (combining both tokens)
uint256 withdrawalValue0InToken1 = FullMath.mulDiv(amount0Desired, price, PRECISION);
uint256 withdrawalValueInToken1;
uint256 poolValueInToken1;
unchecked {
withdrawalValueInToken1 = withdrawalValue0InToken1 + amount1Desired;
// Calculate pool value in token1 terms
poolValueInToken1 = pool1 + FullMath.mulDiv(pool0, price, PRECISION);
}
// Calculate shares to burn
shares = FullMath.mulDiv(withdrawalValueInToken1, totalSupply, poolValueInToken1);
}
/**
* @notice Public wrapper for calculateSharesToBurn that works with MultiPositionManager
* @param manager The MultiPositionManager contract
* @param amount0Desired Amount of token0 desired to withdraw
* @param amount1Desired Amount of token1 desired to withdraw
* @param totalSupply Total supply of vault shares
* @param pool0 Total amount of token0 in pool
* @param pool1 Total amount of token1 in pool
* @return shares Number of shares to burn
*/
function calculateSharesToBurnForManager(
address manager,
uint256 amount0Desired,
uint256 amount1Desired,
uint256 totalSupply,
uint256 pool0,
uint256 pool1
) external view returns (uint256 shares) {
if (totalSupply == 0) revert NoSharesExist();
// Get manager's pool key and pool manager using interface
IMultiPositionManager mpm = IMultiPositionManager(manager);
IPoolManager poolManager = mpm.poolManager();
PoolKey memory poolKey = mpm.poolKey();
// Get current price from pool
(uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolKey.toId());
// Calculate price of token0 in terms of token1 with PRECISION
uint256 price =
FullMath.mulDiv(FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96);
// Calculate total withdrawal value in token1 terms (combining both tokens)
uint256 withdrawalValue0InToken1 = FullMath.mulDiv(amount0Desired, price, PRECISION);
uint256 withdrawalValueInToken1;
uint256 poolValueInToken1;
unchecked {
withdrawalValueInToken1 = withdrawalValue0InToken1 + amount1Desired;
// Calculate pool value in token1 terms
poolValueInToken1 = pool1 + FullMath.mulDiv(pool0, price, PRECISION);
}
// Calculate shares to burn
shares = FullMath.mulDiv(withdrawalValueInToken1, totalSupply, poolValueInToken1);
}
/**
* @notice Public wrapper for calculatePositionSharesToBurn for SimpleLens
* @param manager The MultiPositionManager contract address
* @param amount0Desired Amount of token0 needed
* @param amount1Desired Amount of token1 needed
* @return positionShares Shares worth of positions to burn
*/
function calculatePositionSharesToBurnForSimpleLens(address manager, uint256 amount0Desired, uint256 amount1Desired)
external
view
returns (uint256 positionShares)
{
IMultiPositionManager mpm = IMultiPositionManager(manager);
uint256 totalSupply = mpm.totalSupply();
if (totalSupply == 0) revert NoSharesExist();
// Get total amounts using the interface
(uint256 total0, uint256 total1,,) = mpm.getTotalAmounts();
// Calculate shares needed for each token (ceiling division for safety)
uint256 sharesForToken0;
uint256 sharesForToken1;
if (amount0Desired != 0 && total0 != 0) {
// Ceiling division
unchecked {
sharesForToken0 = (amount0Desired * totalSupply + total0 - 1) / total0;
}
}
if (amount1Desired != 0 && total1 != 0) {
unchecked {
sharesForToken1 = (amount1Desired * totalSupply + total1 - 1) / total1;
}
}
// Take maximum to ensure both requirements met
positionShares = sharesForToken0 > sharesForToken1 ? sharesForToken0 : sharesForToken1;
// Cap at total supply
if (positionShares > totalSupply) {
positionShares = totalSupply;
}
}
/**
* @notice Claim accumulated fees to the fee recipient (internal helper)
* @param poolManager Pool manager contract
* @param factory Factory contract address to get fee recipient
* @param currency Currency to claim fees for
*/
function _claimFeeCurrency(IPoolManager poolManager, address factory, Currency currency) internal {
uint256 amount = poolManager.balanceOf(address(this), currency.toId());
if (amount == 0) return;
poolManager.burn(address(this), currency.toId(), amount);
// Get feeRecipient from factory
address recipient = IMultiPositionFactory(factory).feeRecipient();
poolManager.take(currency, recipient, amount);
}
/**
* @notice Claim accumulated fees to the fee recipient (external)
* @param poolManager Pool manager contract
* @param factory Factory contract address to get fee recipient
* @param currency Currency to claim fees for
*/
function claimFee(IPoolManager poolManager, address factory, Currency currency) external {
_claimFeeCurrency(poolManager, factory, currency);
}
/**
* @notice Process claim fee action - collects fees and distributes to owner and treasury
* @param s Storage pointer
* @param poolManager Pool manager contract
* @param caller Address initiating the claim
* @param owner Owner address
*/
function processClaimFee(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
address caller,
address owner
) external {
// If owner is calling, perform zeroBurn to collect new fees
if (caller == owner) {
// Perform zeroBurn and get the exact fee amounts
(uint256 totalFee0, uint256 totalFee1) = zeroBurnAllWithoutUnlock(s, poolManager);
// After zeroBurnAll, treasury portion is minted as ERC-6909 to contract
// The owner's portion creates negative deltas that are settled by close
PoolManagerUtils.close(poolManager, s.currency1);
PoolManagerUtils.close(poolManager, s.currency0);
// If there are fees, transfer owner's portion
// After close, owner's fees are in contract as ETH or ERC20
if (s.fee != 0) {
// Calculate exact splits
uint256 treasuryFee0;
uint256 treasuryFee1;
uint256 ownerFee0;
uint256 ownerFee1;
unchecked {
treasuryFee0 = totalFee0 / s.fee;
treasuryFee1 = totalFee1 / s.fee;
ownerFee0 = totalFee0 - treasuryFee0;
ownerFee1 = totalFee1 - treasuryFee1;
}
// Transfer owner's portion (now in contract after close)
if (ownerFee0 != 0) {
if (s.currency0.isAddressZero()) {
// Native token - transfer ETH
payable(owner).transfer(ownerFee0);
} else {
// ERC20 token
IERC20(Currency.unwrap(s.currency0)).safeTransfer(owner, ownerFee0);
}
}
if (ownerFee1 != 0) {
// Currency1 is never native, always ERC20
IERC20(Currency.unwrap(s.currency1)).safeTransfer(owner, ownerFee1);
}
}
}
// Always transfer treasury portion to fee recipient
// For protocol fee claims (caller == address(0)), this just transfers existing balance
// For owner claims, this transfers the freshly collected treasury portion
_claimFeeCurrency(poolManager, s.factory, s.currency0);
_claimFeeCurrency(poolManager, s.factory, s.currency1);
}
/**
* @notice Get total amounts including fees
*/
function getTotalAmounts(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
internal
view
returns (uint256 total0, uint256 total1, uint256 totalFee0, uint256 totalFee1)
{
// Get amounts from base positions
for (uint8 i = 0; i < s.basePositionsLength;) {
(, uint256 amount0, uint256 amount1, uint256 feesOwed0, uint256 feesOwed1) =
PoolManagerUtils.getAmountsOf(poolManager, s.poolKey, s.basePositions[i]);
unchecked {
total0 += amount0;
total1 += amount1;
totalFee0 += feesOwed0;
totalFee1 += feesOwed1;
++i;
}
}
// Get amounts from limit positions
for (uint8 i = 0; i < s.limitPositionsLength;) {
(, uint256 amount0, uint256 amount1, uint256 feesOwed0, uint256 feesOwed1) =
PoolManagerUtils.getAmountsOf(poolManager, s.poolKey, s.limitPositions[i]);
unchecked {
total0 += amount0;
total1 += amount1;
totalFee0 += feesOwed0;
totalFee1 += feesOwed1;
++i;
}
}
// Exclude protocol fee from the total amount
unchecked {
totalFee0 -= (totalFee0 / s.fee);
totalFee1 -= (totalFee1 / s.fee);
// Add fees net of protocol fees to the total amount
total0 += totalFee0;
total1 += totalFee1;
// Add unused balances
total0 += s.currency0.balanceOfSelf();
total1 += s.currency1.balanceOfSelf();
}
}
/**
* @notice Process BURN_ALL action in callback
* @dev Burns all positions and clears storage
* @param s Storage struct
* @param poolManager Pool manager contract
* @param totalSupply Current total supply
* @param params Encoded parameters (outMin array)
* @return Encoded burned amounts (amount0, amount1)
*/
function processBurnAllInCallback(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
uint256 totalSupply,
bytes memory params
) external returns (bytes memory) {
// Decode parameters
uint256[2][] memory outMin = abi.decode(params, (uint256[2][]));
// Burn all positions
(uint256 amount0, uint256 amount1) =
PositionLogic.burnLiquidities(poolManager, s, totalSupply, totalSupply, outMin);
// Clear position storage
s.basePositionsLength = 0;
delete s.limitPositions[0];
delete s.limitPositions[1];
s.limitPositionsLength = 0;
// Return burned amounts
return abi.encode(amount0, amount1);
}
/**
* @notice Zero burn all positions without unlock to collect fees
* @dev Collects fees from all positions without burning liquidity
* @param s Storage struct
* @param poolManager Pool manager contract
* @return totalFee0 Total fees collected in token0
* @return totalFee1 Total fees collected in token1
*/
function zeroBurnAllWithoutUnlock(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
public
returns (uint256 totalFee0, uint256 totalFee1)
{
// Build base positions array inline to avoid cross-library storage parameter issues
uint256 baseLength = s.basePositionsLength;
IMultiPositionManager.Range[] memory baseRangesArray = new IMultiPositionManager.Range[](baseLength);
for (uint8 i = 0; i < baseLength;) {
baseRangesArray[i] = s.basePositions[i];
unchecked {
++i;
}
}
// Build limit positions array inline
IMultiPositionManager.Range[2] memory limitRangesArray;
limitRangesArray[0] = s.limitPositions[0];
limitRangesArray[1] = s.limitPositions[1];
// Collect fees from all positions
(totalFee0, totalFee1) = PoolManagerUtils.zeroBurnAll(
poolManager, s.poolKey, baseRangesArray, limitRangesArray, s.currency0, s.currency1, s.fee
);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.sol";
import {SharedStructs} from "../base/SharedStructs.sol";
import {WithdrawLogic} from "./WithdrawLogic.sol";
import {DepositRatioLib} from "./DepositRatioLib.sol";
import {PoolManagerUtils} from "./PoolManagerUtils.sol";
/**
* @title DepositLogic
* @notice Library containing all deposit-related logic for MultiPositionManager
*/
library DepositLogic {
using PoolIdLibrary for PoolKey;
using StateLibrary for IPoolManager;
uint256 constant PRECISION = 1e36;
// Custom errors
error InvalidRecipient();
error CannotSendETHForERC20Pair();
error NoSharesMinted();
error InvalidInMinLength();
// Events
event Deposit(address indexed from, address indexed to, uint256 amount0, uint256 amount1, uint256 shares);
event Compound(uint256 amount0, uint256 amount1);
/**
* @notice Process a deposit (tokens go to vault as idle balance)
* @param s Storage struct
* @param poolManager Pool manager contract
* @param deposit0Desired Desired amount of token0 to deposit
* @param deposit1Desired Desired amount of token1 to deposit
* @param to Recipient address for shares
* @param totalSupply Current total supply of shares
* @param msgValue Value sent with transaction
* @return shares Number of shares minted
* @return deposit0 Actual amount of token0 deposited
* @return deposit1 Actual amount of token1 deposited
*/
function processDeposit(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
uint256 deposit0Desired,
uint256 deposit1Desired,
address to,
address from,
uint256 totalSupply,
uint256 msgValue
) external returns (uint256 shares, uint256 deposit0, uint256 deposit1) {
if (to == address(0)) revert InvalidRecipient();
if (!s.currency0.isAddressZero() && msgValue != 0) {
revert CannotSendETHForERC20Pair();
}
// Use the actual deposit amounts
deposit0 = deposit0Desired;
deposit1 = deposit1Desired;
if (totalSupply == 0) {
// First deposit - use simple max since we don't have positions yet
shares = Math.max(deposit0, deposit1);
} else {
// Calculate shares for subsequent deposits
shares = calculateShares(s, poolManager, deposit0, deposit1, totalSupply);
}
if (shares == 0) revert NoSharesMinted();
// Emit event
emit Deposit(from, to, deposit0, deposit1, shares);
// Return values for main contract to handle minting and transfers
return (shares, deposit0, deposit1);
}
/**
* @notice Calculate shares to mint for a deposit
* @param s Storage struct
* @param poolManager Pool manager contract
* @param deposit0 Amount of token0 to deposit
* @param deposit1 Amount of token1 to deposit
* @param totalSupply Current total supply of shares
* @return shares Number of shares to mint
*/
function calculateShares(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
uint256 deposit0,
uint256 deposit1,
uint256 totalSupply
) public view returns (uint256 shares) {
// Get current pool totals
(uint256 pool0, uint256 pool1,,) = WithdrawLogic.getTotalAmounts(s, poolManager);
// Get price from the pool
(uint160 sqrtPriceX96,,,) = poolManager.getSlot0(s.poolKey.toId());
// Calculate price of token0 in terms of token1 with PRECISION
uint256 price =
FullMath.mulDiv(FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96);
// Calculate deposit value in token1 terms
uint256 depositValueInToken1 = deposit1 + FullMath.mulDiv(deposit0, price, PRECISION);
// Calculate pool value in token1 terms
uint256 pool0PricedInToken1 = FullMath.mulDiv(pool0, price, PRECISION);
uint256 poolValueInToken1 = pool0PricedInToken1 + pool1;
// Calculate shares
if (poolValueInToken1 != 0) {
shares = FullMath.mulDiv(depositValueInToken1, totalSupply, poolValueInToken1);
} else {
shares = depositValueInToken1;
}
}
/**
* @notice Get amounts for direct deposit into positions
* @param s Storage struct
* @param poolManager Pool manager contract
* @param deposit0 Amount of token0 being deposited
* @param deposit1 Amount of token1 being deposited
* @param inMin Minimum input amounts per position
* @return amount0ForPositions Amount of token0 for positions
* @return amount1ForPositions Amount of token1 for positions
*/
function getDirectDepositAmounts(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
uint256 deposit0,
uint256 deposit1,
uint256[2][] memory inMin
) external view returns (uint256 amount0ForPositions, uint256 amount1ForPositions) {
if (s.basePositionsLength == 0) {
return (0, 0);
}
// Validate inMin array size (basePositions + actual limit positions count)
if (inMin.length != s.basePositionsLength + s.limitPositionsLength) revert InvalidInMinLength();
// Get current totals
(uint256 total0, uint256 total1,,) = WithdrawLogic.getTotalAmounts(s, poolManager);
// Use library to calculate amounts that fit the ratio
return DepositRatioLib.getRatioAmounts(total0, total1, deposit0, deposit1);
}
/**
* @notice Process direct deposit liquidity addition to existing positions
* @param s Storage struct
* @param poolManager Pool manager contract
* @param amount0 Amount of token0 to deposit
* @param amount1 Amount of token1 to deposit
* @param inMin Minimum amounts per position for slippage protection
*/
function directDepositLiquidity(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
uint256 amount0,
uint256 amount1,
uint256[2][] memory inMin
) external {
// Calculate distribution amounts and add liquidity
(uint256[] memory amounts0, uint256[] memory amounts1) =
calculateDirectDepositAmounts(s, poolManager, amount0, amount1);
addLiquidityToPositions(s, poolManager, amounts0, amounts1, inMin);
}
struct DepositAmountsParams {
IPoolManager poolManager;
PoolKey poolKey;
uint256 amount0;
uint256 amount1;
uint256 basePositionsLength;
}
/**
* @notice Calculate how to distribute deposit amounts across positions
* @param s Storage struct
* @param poolManager Pool manager contract
* @param amount0 Amount of token0 to distribute
* @param amount1 Amount of token1 to distribute
* @return amounts0 Array of token0 amounts for each position
* @return amounts1 Array of token1 amounts for each position
*/
function calculateDirectDepositAmounts(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
uint256 amount0,
uint256 amount1
) public view returns (uint256[] memory amounts0, uint256[] memory amounts1) {
DepositAmountsParams memory params = DepositAmountsParams({
poolManager: poolManager,
poolKey: s.poolKey,
amount0: amount0,
amount1: amount1,
basePositionsLength: s.basePositionsLength
});
// Get current token amounts in each position
uint256 totalToken0InPositions;
uint256 totalToken1InPositions;
uint256[] memory positionToken0 = new uint256[](params.basePositionsLength + 2);
uint256[] memory positionToken1 = new uint256[](params.basePositionsLength + 2);
// Get token amounts for base positions
for (uint8 i = 0; i < params.basePositionsLength;) {
IMultiPositionManager.Range memory range = s.basePositions[i];
(, uint256 amount0InPos, uint256 amount1InPos,,) =
PoolManagerUtils.getAmountsOf(params.poolManager, params.poolKey, range);
positionToken0[i] = amount0InPos;
positionToken1[i] = amount1InPos;
unchecked {
totalToken0InPositions += amount0InPos;
totalToken1InPositions += amount1InPos;
++i;
}
}
// Get token amounts for limit positions if they exist
for (uint8 i = 0; i < 2;) {
uint256 idx = params.basePositionsLength + i;
IMultiPositionManager.Range memory limitRange = s.limitPositions[i];
if (limitRange.lowerTick != limitRange.upperTick) {
(, uint256 amount0InPos, uint256 amount1InPos,,) =
PoolManagerUtils.getAmountsOf(params.poolManager, params.poolKey, limitRange);
positionToken0[idx] = amount0InPos;
positionToken1[idx] = amount1InPos;
unchecked {
totalToken0InPositions += amount0InPos;
totalToken1InPositions += amount1InPos;
}
}
unchecked {
++i;
}
}
// If no tokens in positions, fall back to liquidity-based distribution
if (totalToken0InPositions == 0 && totalToken1InPositions == 0) {
// Get total liquidity for fallback
uint256 totalLiquidity;
for (uint8 i = 0; i < params.basePositionsLength;) {
IMultiPositionManager.Range memory range = s.basePositions[i];
(uint128 liquidity,,,,) = PoolManagerUtils.getAmountsOf(params.poolManager, params.poolKey, range);
unchecked {
totalLiquidity += liquidity;
++i;
}
}
// Check limit positions
for (uint8 i = 0; i < 2;) {
IMultiPositionManager.Range memory limitRange = s.limitPositions[i];
if (limitRange.lowerTick != limitRange.upperTick) {
(uint128 liquidity,,,,) =
PoolManagerUtils.getAmountsOf(params.poolManager, params.poolKey, limitRange);
unchecked {
totalLiquidity += liquidity;
}
}
unchecked {
++i;
}
}
if (totalLiquidity == 0) {
// No positions to add to
amounts0 = new uint256[](params.basePositionsLength + 2);
amounts1 = new uint256[](params.basePositionsLength + 2);
return (amounts0, amounts1);
}
// For now, just return empty arrays since we can't distribute without knowing token requirements
// This case should be rare (positions with liquidity but no tokens)
amounts0 = new uint256[](params.basePositionsLength + 2);
amounts1 = new uint256[](params.basePositionsLength + 2);
return (amounts0, amounts1);
}
// First determine what CAN actually go into positions based on their ratio
// Use library function to calculate amounts that maintain the ratio
(uint256 amount0ToDistribute, uint256 amount1ToDistribute) = DepositRatioLib.getRatioAmounts(
totalToken0InPositions, totalToken1InPositions, params.amount0, params.amount1
);
// Now distribute these amounts proportionally based on current holdings
amounts0 = new uint256[](params.basePositionsLength + 2);
amounts1 = new uint256[](params.basePositionsLength + 2);
// Distribute token0 to positions that hold token0
if (totalToken0InPositions != 0 && amount0ToDistribute != 0) {
uint256 totalPositions = params.basePositionsLength + 2;
for (uint256 i = 0; i < totalPositions;) {
if (positionToken0[i] != 0) {
amounts0[i] = FullMath.mulDiv(amount0ToDistribute, positionToken0[i], totalToken0InPositions);
}
unchecked {
++i;
}
}
}
// Distribute token1 to positions that hold token1
if (totalToken1InPositions != 0 && amount1ToDistribute != 0) {
uint256 totalPositions = params.basePositionsLength + 2;
for (uint256 i = 0; i < totalPositions;) {
if (positionToken1[i] != 0) {
amounts1[i] = FullMath.mulDiv(amount1ToDistribute, positionToken1[i], totalToken1InPositions);
}
unchecked {
++i;
}
}
}
}
/**
* @notice Add liquidity to positions with calculated amounts
* @param s Storage struct
* @param poolManager Pool manager contract
* @param amounts0 Array of token0 amounts for each position
* @param amounts1 Array of token1 amounts for each position
* @param inMin Minimum amounts per position for slippage protection
*/
function addLiquidityToPositions(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
uint256[] memory amounts0,
uint256[] memory amounts1,
uint256[2][] memory inMin
) private {
// Add liquidity to each base position
uint256 baseLength = s.basePositionsLength;
uint256 totalPositions = baseLength + s.limitPositionsLength;
// If empty inMin passed, create zero-filled array (no slippage protection)
if (inMin.length == 0) {
inMin = new uint256[2][](totalPositions);
}
for (uint8 i = 0; i < baseLength;) {
if (amounts0[i] != 0 || amounts1[i] != 0) {
PoolManagerUtils._mintLiquidityForAmounts(
poolManager, s.poolKey, s.basePositions[i], amounts0[i], amounts1[i], inMin[i]
);
}
unchecked {
++i;
}
}
// Add liquidity to limit positions if they exist
uint256 limitLength = s.limitPositionsLength;
for (uint8 i = 0; i < limitLength;) {
uint256 idx = baseLength + i;
if (
s.limitPositions[i].lowerTick != s.limitPositions[i].upperTick
&& (amounts0[idx] != 0 || amounts1[idx] != 0)
) {
PoolManagerUtils._mintLiquidityForAmounts(
poolManager, s.poolKey, s.limitPositions[i], amounts0[idx], amounts1[idx], inMin[idx]
);
}
unchecked {
++i;
}
}
}
/**
* @notice Process compound: collect fees via zeroBurn, add idle to positions
* @param s Storage struct
* @param poolManager Pool manager contract
* @param inMin Minimum amounts for slippage protection
*/
function processCompound(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
uint256[2][] memory inMin
) external {
if (s.basePositionsLength == 0) return;
// Step 1: Collect fees into vault via zeroBurn
WithdrawLogic.zeroBurnAllWithoutUnlock(s, poolManager);
// Step 2: Get idle balances (fees + existing idle)
uint256 idle0 = s.currency0.balanceOfSelf();
uint256 idle1 = s.currency1.balanceOfSelf();
if (idle0 == 0 && idle1 == 0) return;
// Step 3: Add liquidity to positions
// Calculate distribution amounts and add liquidity
(uint256[] memory amounts0, uint256[] memory amounts1) =
calculateDirectDepositAmounts(s, poolManager, idle0, idle1);
addLiquidityToPositions(s, poolManager, amounts0, amounts1, inMin);
// Emit compound event
emit Compound(idle0, idle1);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
/**
* @title IMulticall
* @notice Interface for batching multiple calls in a single transaction
*/
interface IMulticall {
/**
* @notice Execute multiple calls in a single transaction
* @param data Array of encoded function calls
* @return results Array of return data from each call
*/
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import {Currency} from "v4-core/types/Currency.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
/// @notice Library used to interact with PoolManager.sol to settle any open deltas.
/// @dev Note that sync() is called before any erc-20 transfer in `settle`.
library CurrencySettler {
using SafeERC20 for IERC20;
/// @notice Settle (pay) a currency to the PoolManager
/// @param currency Currency to settle
/// @param manager IPoolManager to settle to
/// @param payer Address of the payer, the token sender
/// @param amount Amount to send
/// @param burn If true, burn the ERC-6909 token, otherwise ERC20-transfer to the PoolManager
function settle(Currency currency, IPoolManager manager, address payer, uint256 amount, bool burn) internal {
if (burn) {
manager.burn(payer, currency.toId(), amount);
} else if (currency.isAddressZero()) {
manager.settle{value: amount}();
} else {
manager.sync(currency);
if (payer != address(this)) {
IERC20(Currency.unwrap(currency)).safeTransferFrom(payer, address(manager), amount);
} else {
IERC20(Currency.unwrap(currency)).safeTransfer(address(manager), amount);
}
manager.settle();
}
}
/// @notice Take (receive) a currency from the PoolManager
/// @param currency Currency to take
/// @param manager IPoolManager to take from
/// @param recipient Address of the recipient, the token receiver
/// @param amount Amount to receive
/// @param claims If true, mint the ERC-6909 token, otherwise ERC20-transfer from the PoolManager to recipient
function take(Currency currency, IPoolManager manager, address recipient, uint256 amount, bool claims) internal {
claims ? manager.mint(recipient, currency.toId(), amount) : manager.take(currency, recipient, amount);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @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 towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (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 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 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.
uint256 twos = denominator & (0 - denominator);
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 (unsignedRoundsUp(rounding) && 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
* towards zero.
*
* 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* 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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* 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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* 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 256, 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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolManagerUtils} from "./PoolManagerUtils.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
/**
* @title DepositRatioLib
* @notice Internal library for calculating deposit ratios and proportional distributions
*/
library DepositRatioLib {
/**
* @notice Calculate amounts that match the vault's current ratio for directDeposit
* @param total0 Current total amount of token0 in vault
* @param total1 Current total amount of token1 in vault
* @param amount0Desired Amount of token0 user wants to deposit
* @param amount1Desired Amount of token1 user wants to deposit
* @return amount0ForPositions Amount of token0 that fits the ratio
* @return amount1ForPositions Amount of token1 that fits the ratio
*/
function getRatioAmounts(uint256 total0, uint256 total1, uint256 amount0Desired, uint256 amount1Desired)
internal
pure
returns (uint256 amount0ForPositions, uint256 amount1ForPositions)
{
if (total0 == 0 && total1 == 0) {
// No existing positions, can use full amounts
return (amount0Desired, amount1Desired);
}
if (total0 == 0) {
// Only token1 in positions
return (0, amount1Desired);
}
if (total1 == 0) {
// Only token0 in positions
return (amount0Desired, 0);
}
// Calculate amounts that fit the current ratio using cross-product
uint256 cross = Math.min(amount0Desired * total1, amount1Desired * total0);
if (cross == 0) {
return (0, 0);
}
// Calculate the amounts that maintain the ratio
amount0ForPositions = (cross - 1) / total1 + 1;
amount1ForPositions = (cross - 1) / total0 + 1;
// Ensure we don't try to use more than deposited
amount0ForPositions = Math.min(amount0ForPositions, amount0Desired);
amount1ForPositions = Math.min(amount1ForPositions, amount1Desired);
return (amount0ForPositions, amount1ForPositions);
}
/**
* @notice Calculate how to distribute amounts across positions proportionally based on liquidity
* @param positionLiquidities Array of liquidities for each position
* @param totalLiquidity Total liquidity across all positions
* @param amount0 Total amount of token0 to distribute
* @param amount1 Total amount of token1 to distribute
* @return amounts0 Array of token0 amounts for each position
* @return amounts1 Array of token1 amounts for each position
*/
function getProportionalAmounts(
uint128[] memory positionLiquidities,
uint256 totalLiquidity,
uint256 amount0,
uint256 amount1
) internal pure returns (uint256[] memory amounts0, uint256[] memory amounts1) {
uint256 length = positionLiquidities.length;
amounts0 = new uint256[](length);
amounts1 = new uint256[](length);
if (totalLiquidity == 0) {
return (amounts0, amounts1);
}
// Distribute amounts proportionally
for (uint256 i = 0; i < length; i++) {
if (positionLiquidities[i] > 0) {
amounts0[i] = FullMath.mulDiv(amount0, positionLiquidities[i], totalLiquidity);
amounts1[i] = FullMath.mulDiv(amount1, positionLiquidities[i], totalLiquidity);
}
}
return (amounts0, amounts1);
}
}{
"remappings": [
"@ensdomains/=lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"@openzeppelin/contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/",
"@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
"ds-test/=lib/v4-periphery/lib/v4-core/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/v4-periphery/lib/forge-gas-snapshot/src/",
"forge-std/=lib/forge-std/src/",
"hardhat/=lib/v4-periphery/lib/v4-core/node_modules/hardhat/",
"openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"permit2/=lib/v4-periphery/lib/permit2/",
"solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
"v4-core/=lib/v4-periphery/lib/v4-core/src/",
"v4-periphery/=lib/v4-periphery/",
"@openzeppelin-latest/=lib/liquidity-launcher/lib/openzeppelin-contracts/",
"@optimism/=lib/liquidity-launcher/lib/optimism/packages/contracts-bedrock/",
"@solady/=lib/liquidity-launcher/lib/solady/",
"@uniswap/v4-periphery/=lib/liquidity-launcher/lib/v4-periphery/",
"btt/=lib/liquidity-launcher/lib/continuous-clearing-auction/test/btt/",
"continuous-clearing-auction/=lib/liquidity-launcher/lib/continuous-clearing-auction/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"kontrol-cheatcodes/=lib/liquidity-launcher/lib/optimism/packages/contracts-bedrock/lib/kontrol-cheatcodes/src/",
"lib-keccak/=lib/liquidity-launcher/lib/optimism/packages/contracts-bedrock/lib/lib-keccak/contracts/",
"liquidity-launcher/=lib/liquidity-launcher/",
"merkle-distributor/=lib/liquidity-launcher/lib/merkle-distributor/",
"openzeppelin-contracts-4.7/=lib/liquidity-launcher/lib/openzeppelin-contracts-4.7/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts-v5/=lib/liquidity-launcher/lib/optimism/packages/contracts-bedrock/lib/openzeppelin-contracts-v5/",
"optimism/=lib/liquidity-launcher/lib/optimism/",
"safe-contracts/=lib/liquidity-launcher/lib/optimism/packages/contracts-bedrock/lib/safe-contracts/contracts/",
"solady-v0.0.245/=lib/liquidity-launcher/lib/optimism/packages/contracts-bedrock/lib/solady-v0.0.245/src/",
"solady/=lib/liquidity-launcher/lib/solady/src/",
"test/=lib/liquidity-launcher/lib/continuous-clearing-auction/test/"
],
"optimizer": {
"enabled": true,
"runs": 800
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": false
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"_limitOrderLens","type":"address"},{"internalType":"address","name":"_limitOrderHook","type":"address"},{"internalType":"address","name":"_multiPositionFactory","type":"address"},{"internalType":"address","name":"_dynamicFeeLimitOrderRegistry","type":"address"},{"internalType":"address","name":"_volatilityDynamicLimitOrderRegistry","type":"address"},{"internalType":"address","name":"_dynamicFeeRegistry","type":"address"},{"internalType":"address","name":"_volatilityDynamicFeeRegistry","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"DynamicFeeNotAllowed","type":"error"},{"inputs":[],"name":"ETHRefundFailed","type":"error"},{"inputs":[],"name":"ETHTransferFailed","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[],"name":"InsufficientETH","type":"error"},{"inputs":[],"name":"InvalidAmount","type":"error"},{"inputs":[],"name":"InvalidHookAddress","type":"error"},{"inputs":[],"name":"NoFeesToWithdraw","type":"error"},{"inputs":[],"name":"NoLiquidityProvided","type":"error"},{"inputs":[],"name":"NotAuthorizedStrategyFactory","type":"error"},{"inputs":[],"name":"PoolAlreadyReserved","type":"error"},{"inputs":[],"name":"PoolReservedForOther","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"SharedVolatilityOracleNotSet","type":"error"},{"inputs":[],"name":"TokenOrderingIncorrect","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"factory","type":"address"}],"name":"AuthorizedStrategyFactorySet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldRegistry","type":"address"},{"indexed":true,"internalType":"address","name":"newRegistry","type":"address"}],"name":"DynamicFeeRegistryUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newFee","type":"uint256"}],"name":"DynamicPoolCreationFeeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"FeesWithdrawn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"creator","type":"address"},{"indexed":true,"internalType":"address","name":"hook","type":"address"},{"indexed":false,"internalType":"uint24","name":"fee","type":"uint24"}],"name":"PoolCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"creator","type":"address"},{"indexed":false,"internalType":"uint256","name":"fee","type":"uint256"}],"name":"PoolCreationFeeCollected","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"bool","name":"isDynamic","type":"bool"}],"name":"PoolInfoStored","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"}],"name":"PoolReservationCleared","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"strategy","type":"address"}],"name":"PoolReserved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newFee","type":"uint256"}],"name":"RegularPoolCreationFeeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oracle","type":"address"}],"name":"SharedVolatilityOracleSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newFee","type":"uint256"}],"name":"VolatilityDynamicCreationFeeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldRegistry","type":"address"},{"indexed":true,"internalType":"address","name":"newRegistry","type":"address"}],"name":"VolatilityDynamicRegistryUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"hookOwner","type":"address"},{"indexed":true,"internalType":"address","name":"hookAddr","type":"address"}],"name":"VolatilityHookDeployed","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"FEE_COLLECTOR_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"authorizedStrategyFactory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collectedFees","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"hookOwner","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"int24","name":"tickSpacing","type":"int24"}],"name":"computePoolIdForVolatilityLimitOrder","outputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"creator","type":"address"},{"internalType":"address","name":"factory","type":"address"}],"name":"computeSaltForDynamicFee","outputs":[{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"address","name":"hookAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"creator","type":"address"},{"internalType":"address","name":"_limitOrderManager","type":"address"},{"internalType":"address","name":"factory","type":"address"}],"name":"computeSaltForDynamicLimitOrder","outputs":[{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"address","name":"hookAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"creator","type":"address"},{"internalType":"address","name":"factory","type":"address"}],"name":"computeSaltForVolatilityDynamicFee","outputs":[{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"address","name":"hookAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"creator","type":"address"},{"internalType":"address","name":"_limitOrderManager","type":"address"},{"internalType":"address","name":"factory","type":"address"}],"name":"computeSaltForVolatilityDynamicLimitOrder","outputs":[{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"address","name":"hookAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"hookOwner","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"name":"computeVolatilityFeeHookAddress","outputs":[{"internalType":"address","name":"hookAddr","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"hookOwner","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"name":"computeVolatilityLimitOrderHookAddress","outputs":[{"internalType":"address","name":"hookAddr","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint24","name":"initialFee","type":"uint24"},{"internalType":"uint256","name":"deposit0Desired","type":"uint256"},{"internalType":"uint256","name":"deposit1Desired","type":"uint256"},{"internalType":"address","name":"managerOwner","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bool","name":"useSwap","type":"bool"},{"components":[{"internalType":"enum RebalanceLogic.Aggregator","name":"aggregator","type":"uint8"},{"internalType":"address","name":"aggregatorAddress","type":"address"},{"internalType":"bytes","name":"swapData","type":"bytes"},{"internalType":"bool","name":"swapToken0","type":"bool"},{"internalType":"uint256","name":"swapAmount","type":"uint256"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"}],"internalType":"struct RebalanceLogic.SwapParams","name":"swapParams","type":"tuple"},{"internalType":"uint256[2][]","name":"inMin","type":"uint256[2][]"},{"components":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"int24","name":"center","type":"int24"},{"internalType":"uint24","name":"tLeft","type":"uint24"},{"internalType":"uint24","name":"tRight","type":"uint24"},{"internalType":"uint24","name":"limitWidth","type":"uint24"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"},{"internalType":"bool","name":"useCarpet","type":"bool"}],"internalType":"struct IMultiPositionManager.RebalanceParams","name":"rebalanceParams","type":"tuple"}],"internalType":"struct OrderBookFactory.DynamicPoolParams","name":"params","type":"tuple"}],"name":"createDynamicFeePoolWithManager","outputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"address","name":"mpm","type":"address"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint24","name":"initialFee","type":"uint24"},{"internalType":"uint256","name":"deposit0Desired","type":"uint256"},{"internalType":"uint256","name":"deposit1Desired","type":"uint256"},{"internalType":"address","name":"managerOwner","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bool","name":"useSwap","type":"bool"},{"components":[{"internalType":"enum RebalanceLogic.Aggregator","name":"aggregator","type":"uint8"},{"internalType":"address","name":"aggregatorAddress","type":"address"},{"internalType":"bytes","name":"swapData","type":"bytes"},{"internalType":"bool","name":"swapToken0","type":"bool"},{"internalType":"uint256","name":"swapAmount","type":"uint256"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"}],"internalType":"struct RebalanceLogic.SwapParams","name":"swapParams","type":"tuple"},{"internalType":"uint256[2][]","name":"inMin","type":"uint256[2][]"},{"components":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"int24","name":"center","type":"int24"},{"internalType":"uint24","name":"tLeft","type":"uint24"},{"internalType":"uint24","name":"tRight","type":"uint24"},{"internalType":"uint24","name":"limitWidth","type":"uint24"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"},{"internalType":"bool","name":"useCarpet","type":"bool"}],"internalType":"struct IMultiPositionManager.RebalanceParams","name":"rebalanceParams","type":"tuple"}],"internalType":"struct OrderBookFactory.DynamicPoolParams","name":"params","type":"tuple"}],"name":"createDynamicLimitOrderPoolWithManager","outputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"address","name":"mpm","type":"address"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"uint256","name":"deposit0Desired","type":"uint256"},{"internalType":"uint256","name":"deposit1Desired","type":"uint256"},{"internalType":"address","name":"managerOwner","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bool","name":"useSwap","type":"bool"},{"components":[{"internalType":"enum RebalanceLogic.Aggregator","name":"aggregator","type":"uint8"},{"internalType":"address","name":"aggregatorAddress","type":"address"},{"internalType":"bytes","name":"swapData","type":"bytes"},{"internalType":"bool","name":"swapToken0","type":"bool"},{"internalType":"uint256","name":"swapAmount","type":"uint256"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"}],"internalType":"struct RebalanceLogic.SwapParams","name":"swapParams","type":"tuple"},{"internalType":"uint256[2][]","name":"inMin","type":"uint256[2][]"},{"components":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"int24","name":"center","type":"int24"},{"internalType":"uint24","name":"tLeft","type":"uint24"},{"internalType":"uint24","name":"tRight","type":"uint24"},{"internalType":"uint24","name":"limitWidth","type":"uint24"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"},{"internalType":"bool","name":"useCarpet","type":"bool"}],"internalType":"struct IMultiPositionManager.RebalanceParams","name":"rebalanceParams","type":"tuple"}],"internalType":"struct OrderBookFactory.RegularPoolParams","name":"params","type":"tuple"}],"name":"createRegularPoolWithManager","outputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"address","name":"mpm","type":"address"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint24","name":"baseFee","type":"uint24"},{"internalType":"uint24","name":"surgeMultiplier","type":"uint24"},{"internalType":"uint32","name":"surgeDuration","type":"uint32"},{"internalType":"uint24","name":"initialMaxTicksPerBlock","type":"uint24"},{"internalType":"uint256","name":"deposit0Desired","type":"uint256"},{"internalType":"uint256","name":"deposit1Desired","type":"uint256"},{"internalType":"address","name":"managerOwner","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bool","name":"useSwap","type":"bool"},{"components":[{"internalType":"enum RebalanceLogic.Aggregator","name":"aggregator","type":"uint8"},{"internalType":"address","name":"aggregatorAddress","type":"address"},{"internalType":"bytes","name":"swapData","type":"bytes"},{"internalType":"bool","name":"swapToken0","type":"bool"},{"internalType":"uint256","name":"swapAmount","type":"uint256"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"}],"internalType":"struct RebalanceLogic.SwapParams","name":"swapParams","type":"tuple"},{"internalType":"uint256[2][]","name":"inMin","type":"uint256[2][]"},{"components":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"int24","name":"center","type":"int24"},{"internalType":"uint24","name":"tLeft","type":"uint24"},{"internalType":"uint24","name":"tRight","type":"uint24"},{"internalType":"uint24","name":"limitWidth","type":"uint24"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"},{"internalType":"bool","name":"useCarpet","type":"bool"}],"internalType":"struct IMultiPositionManager.RebalanceParams","name":"rebalanceParams","type":"tuple"},{"internalType":"address","name":"hookOwner","type":"address"}],"internalType":"struct OrderBookFactory.VolatilityDynamicPoolParams","name":"params","type":"tuple"}],"name":"createVolatilityDynamicFeePoolWithManager","outputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"address","name":"mpm","type":"address"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint24","name":"baseFee","type":"uint24"},{"internalType":"uint24","name":"surgeMultiplier","type":"uint24"},{"internalType":"uint32","name":"surgeDuration","type":"uint32"},{"internalType":"uint24","name":"initialMaxTicksPerBlock","type":"uint24"},{"internalType":"uint256","name":"deposit0Desired","type":"uint256"},{"internalType":"uint256","name":"deposit1Desired","type":"uint256"},{"internalType":"address","name":"managerOwner","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bool","name":"useSwap","type":"bool"},{"components":[{"internalType":"enum RebalanceLogic.Aggregator","name":"aggregator","type":"uint8"},{"internalType":"address","name":"aggregatorAddress","type":"address"},{"internalType":"bytes","name":"swapData","type":"bytes"},{"internalType":"bool","name":"swapToken0","type":"bool"},{"internalType":"uint256","name":"swapAmount","type":"uint256"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"}],"internalType":"struct RebalanceLogic.SwapParams","name":"swapParams","type":"tuple"},{"internalType":"uint256[2][]","name":"inMin","type":"uint256[2][]"},{"components":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"int24","name":"center","type":"int24"},{"internalType":"uint24","name":"tLeft","type":"uint24"},{"internalType":"uint24","name":"tRight","type":"uint24"},{"internalType":"uint24","name":"limitWidth","type":"uint24"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"},{"internalType":"bool","name":"useCarpet","type":"bool"}],"internalType":"struct IMultiPositionManager.RebalanceParams","name":"rebalanceParams","type":"tuple"},{"internalType":"address","name":"hookOwner","type":"address"}],"internalType":"struct OrderBookFactory.VolatilityDynamicPoolParams","name":"params","type":"tuple"}],"name":"createVolatilityDynamicLimitOrderPoolWithManager","outputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"address","name":"mpm","type":"address"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"creatorDynamicFeeHooks","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"creatorDynamicLimitOrderHooks","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"creatorVolatilityDynamicFeeHooks","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"creatorVolatilityDynamicLimitOrderHooks","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"dynamicFeeLimitOrderRegistry","outputs":[{"internalType":"contract DynamicFeeLimitOrderHookRegistry","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"dynamicFeeRegistry","outputs":[{"internalType":"contract DynamicFeeHookRegistry","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"dynamicPoolCreationFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"creator","type":"address"}],"name":"getPoolInfoByCreator","outputs":[{"components":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"bool","name":"isDynamic","type":"bool"}],"internalType":"struct OrderBookFactory.PoolInfo[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"creator","type":"address"}],"name":"getPoolsByCreator","outputs":[{"internalType":"bytes32[]","name":"poolIds","type":"bytes32[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"limitOrderHook","outputs":[{"internalType":"contract LimitOrderHook","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"limitOrderLens","outputs":[{"internalType":"contract LimitOrderLens","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"limitOrderManager","outputs":[{"internalType":"contract LimitOrderManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"multiPositionFactory","outputs":[{"internalType":"contract MultiPositionFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"poolCreators","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolManager","outputs":[{"internalType":"contract IPoolManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"regularPoolCreationFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"address","name":"strategy","type":"address"}],"name":"reservePoolForStrategy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"reservedPools","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"factory","type":"address"}],"name":"setAuthorizedStrategyFactory","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_registry","type":"address"}],"name":"setDynamicFeeLimitOrderRegistry","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_registry","type":"address"}],"name":"setDynamicFeeRegistry","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_fee","type":"uint256"}],"name":"setDynamicPoolCreationFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_fee","type":"uint256"}],"name":"setRegularPoolCreationFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"oracle","type":"address"}],"name":"setSharedVolatilityOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_fee","type":"uint256"}],"name":"setVolatilityDynamicCreationFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_registry","type":"address"}],"name":"setVolatilityDynamicFeeRegistry","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_registry","type":"address"}],"name":"setVolatilityDynamicLimitOrderRegistry","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sharedVolatilityOracle","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"userToPoolInfo","outputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"bool","name":"isDynamic","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"volatilityDynamicCreationFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"volatilityDynamicFeeRegistry","outputs":[{"internalType":"contract VolatilityDynamicFeeHookRegistry","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"volatilityDynamicLimitOrderRegistry","outputs":[{"internalType":"contract VolatilityDynamicFeeLimitOrderHookRegistry","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"}],"name":"withdrawFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]Contract Creation Code
60a060405234801561000f575f80fd5b5060405161567538038061567583398101604081905261002e91610376565b6001600160a01b0386166100555760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b03851661007c5760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0384166100a35760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0383166100ca5760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0382166100f15760405163d92e233d60e01b815260040160405180910390fd5b6001600160a01b0381166101185760405163d92e233d60e01b815260040160405180910390fd5b600280546001600160a01b0319166001600160a01b0389169081179091556040805163dc4c90d360e01b8152905163dc4c90d3916004808201926020929091908290030181865afa15801561016f573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610193919061040d565b600380546001600160a01b0319166001600160a01b03928316179055600254604080516348566a3360e01b8152905191909216916348566a339160048083019260209291908290030181865afa1580156101ef573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610213919061040d565b600180546001600160a01b03199081166001600160a01b0393841617909155600980548216878416179055600a80548216868416179055600b80548216858416179055600c8054821684841617905560048054909116888316179055851660805261027e5f336102b6565b506102a97f2dca0f5ce7e75a4b43fe2b0d6f5d0b7a2bf92ecf89f8f0aa17b8308b67038821336102b6565b505050505050505061042f565b5f828152602081815260408083206001600160a01b038516845290915281205460ff16610356575f838152602081815260408083206001600160a01b03861684529091529020805460ff1916600117905561030e3390565b6001600160a01b0316826001600160a01b0316847f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a4506001610359565b505f5b92915050565b6001600160a01b0381168114610373575f80fd5b50565b5f805f805f805f60e0888a03121561038c575f80fd5b87516103978161035f565b60208901519097506103a88161035f565b60408901519096506103b98161035f565b60608901519095506103ca8161035f565b60808901519094506103db8161035f565b60a08901519093506103ec8161035f565b60c08901519092506103fd8161035f565b8091505092959891949750929550565b5f6020828403121561041d575f80fd5b81516104288161035f565b9392505050565b6080516152126104635f395f8181610ade01528181613745015281816137f9015281816138a201526138ff01526152125ff3fe608060405260043610610353575f3560e01c80637224dc82116101bd578063b66b1d6f116100f2578063d547741f11610092578063f07f574e1161006d578063f07f574e14610a88578063f1716acf14610aa7578063f4c7a2a214610aba578063fc3d920e14610acd575f80fd5b8063d547741f14610a16578063d61d6b8314610a35578063dc4c90d314610a69575f80fd5b8063c30aa893116100cd578063c30aa89314610997578063c30d261f146109ac578063c84728ef146109cb578063cdb77163146109f7575f80fd5b8063b66b1d6f1461093a578063bb1e707714610959578063bb46d76514610978575f80fd5b80639003adfe1161015d5780639f541711116101385780639f541711146108cd578063a217fddf146108e0578063a5214e18146108f3578063a605e3b514610906575f80fd5b80639003adfe1461085757806391d148541461086c5780639d347281146108ae575f80fd5b80637981581b116101985780637981581b146107d85780637b5708f3146107ed578063897371f5146108195780638dd121b214610838575f80fd5b80637224dc821461077057806373bc22961461078f5780637883b59e146107c3575f80fd5b80632f2ff15d1161029357806346eea25711610233578063522066ca1161020e578063522066ca146106b65780635f072d56146106ea57806362a2a47c1461071e57806363a9084a14610751575f80fd5b806346eea2571461065957806348566a33146106785780634998476c14610697575f80fd5b80633d7b0f5f1161026e5780633d7b0f5f146105ce57806341d9c94d146105fc57806342c4bf091461061b578063462e997b1461063a575f80fd5b80632f2ff15d1461057157806336568abe146105905780633c63ec42146105af575f80fd5b80631dca04e0116102fe578063248a9ca3116102d9578063248a9ca3146104c35780632be1b438146104ff5780632c398d781461051e5780632eaee54514610552575f80fd5b80631dca04e0146104645780631fce4a331461048357806320aec29e146104a2575f80fd5b806309ac3c791161032e57806309ac3c79146103e85780630e3547c014610409578063164e68de14610445575f80fd5b806301ffc9a71461035e5780630286d77e1461039257806303c7f7dd146103c9575f80fd5b3661035a57005b5f80fd5b348015610369575f80fd5b5061037d610378366004614611565b610b00565b60405190151581526020015b60405180910390f35b34801561039d575f80fd5b506015546103b1906001600160a01b031681565b6040516001600160a01b039091168152602001610389565b3480156103d4575f80fd5b50600b546103b1906001600160a01b031681565b3480156103f3575f80fd5b5061040761040236600461465c565b610b36565b005b348015610414575f80fd5b5061042861042336600461468a565b610bee565b604080519283526001600160a01b03909116602083015201610389565b348015610450575f80fd5b5061040761045f3660046146b6565b610cf2565b34801561046f575f80fd5b5061040761047e3660046146b6565b610e1f565b34801561048e575f80fd5b5061040761049d3660046146b6565b610ea2565b6104b56104b03660046146d1565b610f1d565b60405161038992919061475c565b3480156104ce575f80fd5b506104f16104dd366004614780565b5f9081526020819052604090206001015490565b604051908152602001610389565b34801561050a575f80fd5b50610407610519366004614780565b6113d4565b348015610529575f80fd5b506103b16105383660046146b6565b60106020525f90815260409020546001600160a01b031681565b34801561055d575f80fd5b5061042861056c366004614797565b61141b565b34801561057c575f80fd5b5061040761058b36600461465c565b6114f4565b34801561059b575f80fd5b506104076105aa36600461465c565b611518565b3480156105ba575f80fd5b506104f16105c93660046147f8565b611550565b3480156105d9575f80fd5b506105ed6105e836600461485c565b6115c4565b60405161038993929190614886565b348015610607575f80fd5b50600c546103b1906001600160a01b031681565b348015610626575f80fd5b50610407610635366004614780565b61165d565b348015610645575f80fd5b506103b161065436600461485c565b61169c565b348015610664575f80fd5b50610428610673366004614797565b611815565b348015610683575f80fd5b506001546103b1906001600160a01b031681565b3480156106a2575f80fd5b506104076106b13660046146b6565b6118ff565b3480156106c1575f80fd5b506103b16106d0366004614780565b60116020525f90815260409020546001600160a01b031681565b3480156106f5575f80fd5b506103b16107043660046146b6565b600f6020525f90815260409020546001600160a01b031681565b348015610729575f80fd5b506104f17f2dca0f5ce7e75a4b43fe2b0d6f5d0b7a2bf92ecf89f8f0aa17b8308b6703882181565b34801561075c575f80fd5b506004546103b1906001600160a01b031681565b34801561077b575f80fd5b506103b161078a36600461485c565b61197a565b34801561079a575f80fd5b506103b16107a93660046146b6565b600e6020525f90815260409020546001600160a01b031681565b3480156107ce575f80fd5b506104f160075481565b3480156107e3575f80fd5b506104f160065481565b3480156107f8575f80fd5b5061080c6108073660046146b6565b611a49565b60405161038991906148aa565b348015610824575f80fd5b5061042861083336600461468a565b611b28565b348015610843575f80fd5b506013546103b1906001600160a01b031681565b348015610862575f80fd5b506104f160085481565b348015610877575f80fd5b5061037d61088636600461465c565b5f918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b3480156108b9575f80fd5b506002546103b1906001600160a01b031681565b6104b56108db36600461490f565b611bd2565b3480156108eb575f80fd5b506104f15f81565b6104b561090136600461490f565b612074565b348015610911575f80fd5b506103b1610920366004614780565b60146020525f90815260409020546001600160a01b031681565b348015610945575f80fd5b506104076109543660046146b6565b612331565b348015610964575f80fd5b50600a546103b1906001600160a01b031681565b348015610983575f80fd5b506104076109923660046146b6565b6123b4565b3480156109a2575f80fd5b506104f160055481565b3480156109b7575f80fd5b506009546103b1906001600160a01b031681565b3480156109d6575f80fd5b506109ea6109e53660046146b6565b612437565b6040516103899190614947565b348015610a02575f80fd5b50610407610a113660046146b6565b6125a8565b348015610a21575f80fd5b50610407610a3036600461465c565b61262b565b348015610a40575f80fd5b506103b1610a4f3660046146b6565b600d6020525f90815260409020546001600160a01b031681565b348015610a74575f80fd5b506003546103b1906001600160a01b031681565b348015610a93575f80fd5b50610407610aa2366004614780565b61264f565b6104b5610ab53660046146d1565b61268e565b6104b5610ac836600461497e565b612c65565b348015610ad8575f80fd5b506103b17f000000000000000000000000000000000000000000000000000000000000000081565b5f6001600160e01b03198216637965db0b60e01b1480610b3057506301ffc9a760e01b6001600160e01b03198316145b92915050565b6015546001600160a01b03163314610b6157604051631ac3200f60e21b815260040160405180910390fd5b5f828152601460205260409020546001600160a01b031615610b965760405163ef7a0c8d60e01b815260040160405180910390fd5b5f8281526014602052604080822080546001600160a01b0319166001600160a01b0385169081179091559051909184917fd9345d9350de063de8ed64ea65f84f4cb4d084a36c923e457522c8b46bb85e1b9190a35050565b6013545f9081906001600160a01b0316610c1b5760405163cc1be59d60e01b815260040160405180910390fd5b600c54604080516352c7420d60e01b8152905160c0925f926001600160a01b03909116916352c7420d9160048082019286929091908290030181865afa158015610c67573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610c8e9190810190614a6f565b600354601354604080516001600160a01b03938416602082015291831690820152888216606082015290871660808201529091505f9060a0015b6040516020818303038152906040529050610ce58684848461301f565b9890975095505050505050565b7f2dca0f5ce7e75a4b43fe2b0d6f5d0b7a2bf92ecf89f8f0aa17b8308b67038821610d1c816130fc565b6001600160a01b038216610d435760405163d92e233d60e01b815260040160405180910390fd5b6008545f819003610d6757604051630d00db4d60e31b815260040160405180910390fd5b5f6008556040518181526001600160a01b038416907fc0819c13be868895eb93e40eaceb96de976442fa1d404e5c55f14bb65a8c489a9060200160405180910390a25f836001600160a01b0316826040515f6040518083038185875af1925050503d805f8114610df2576040519150601f19603f3d011682016040523d82523d5f602084013e610df7565b606091505b5050905080610e195760405163b12d13eb60e01b815260040160405180910390fd5b50505050565b5f610e29816130fc565b6001600160a01b038216610e505760405163d92e233d60e01b815260040160405180910390fd5b600a80546001600160a01b038481166001600160a01b0319831681179093556040519116919082907fdeff25089442120c3e5d2fc7072cb58c8287d65c1fdb6501f281923beb331f3d905f90a3505050565b5f610eac816130fc565b6001600160a01b038216610ed35760405163d92e233d60e01b815260040160405180910390fd5b601380546001600160a01b0319166001600160a01b0384169081179091556040517f4a4603e6539261d5881585a47c1eaa39ba238693700eb1c852b99b2a57bd1c23905f90a25050565b6040805160a0810182525f808252602082018190529181018290526060810182905260808101919091525f610f5860408401602085016146b6565b6001600160a01b0316610f6e60208501856146b6565b6001600160a01b031610610f95576040516305188ae360e11b815260040160405180910390fd5b5f610fa8610180850161016086016146b6565b6001600160a01b031603610fcf5760405163d92e233d60e01b815260040160405180910390fd5b5f610fe26101c085016101a086016146b6565b6001600160a01b0316036110095760405163d92e233d60e01b815260040160405180910390fd5b61012083013515801561101f5750610140830135155b1561103d5760405163019e6dc160e11b815260040160405180910390fd5b620186a061105160e0850160c08601614afb565b62ffffff1611156110755760405163162908e360e11b815260040160405180910390fd5b61271061108860e0850160c08601614afb565b62ffffff1610156110ac5760405163162908e360e11b815260040160405180910390fd5b6110be6101e084016101c08501614b2c565b80156110f057505f6110d46101e0850185614b47565b6110e59060408101906020016146b6565b6001600160a01b0316145b1561110e5760405163d92e233d60e01b815260040160405180910390fd5b5f805f61111a86613109565b915091508061112b5760075461112d565b5f5b6040805160a081019091529093508061114960208901896146b6565b6001600160a01b0316815260200187602001602081019061116a91906146b6565b6001600160a01b031681526280000060208201526040908101906111949060608a01908a01614b65565b60020b81526001600160a01b0384166020909101819052909550639d32af28866111c460c08a0160a08b01614afb565b6111d460e08b0160c08c01614afb565b6111e56101008c0160e08d01614b80565b6111f76101208d016101008e01614afb565b6040518663ffffffff1660e01b8152600401611217959493929190614ba3565b5f604051808303815f87803b15801561122e575f80fd5b505af1158015611240573d5f803e3d5ffd5b505050506112628587606001602081019061125b91906146b6565b6001613340565b505f905061128261127660208701876146b6565b86610120013584613693565b90506113af848261129b61018089016101608a016146b6565b6112a96101808a018a614bea565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152505050506101208a01356101408b01356112fa6101c08d016101a08e016146b6565b61130c6101e08e016101c08f01614b2c565b61131a6101e08f018f614b47565b61132390614c81565b8e8061020001906113349190614d11565b808060200260200160405190810160405280939291908181526020015f905b82821015611390576040805180820182529080840287019060029083908390808284375f9201919091525050508152600190910190602001611353565b50505050508f610220018036038101906113aa9190614d57565b61372e565b92506113cd6113c160208701876146b6565b866101200135846139cd565b5050915091565b5f6113de816130fc565b60068290556040518281527f6da0320d887f02077fcd4adbf4fdc333fcfb8f4f6c017a83ec8d2f141d41d2ec906020015b60405180910390a15050565b600954604080516352c7420d60e01b815290515f92839260c09284926001600160a01b0316916352c7420d91600480830192869291908290030181865afa158015611468573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261148f9190810190614a6f565b600354604080516001600160a01b03928316602082015289831691810191909152898216606082015290871660808201529091505f9060a0015b60405160208183030381529060405290506114e68684848461301f565b999098509650505050505050565b5f8281526020819052604090206001015461150e816130fc565b610e198383613a6b565b6001600160a01b03811633146115415760405163334bd91960e11b815260040160405180910390fd5b61154b8282613b12565b505050565b6001600160a01b038086165f908152600e60205260408120549091168061157e5761157b878761169c565b90505b6040805160a080820183526001600160a01b0397881682529587166020820152628000009181019190915260029390930b60608401529093166080820152209392505050565b6012602052815f5260405f2081815481106115dd575f80fd5b5f91825260209182902060059091020180546040805160a08101825260018401546001600160a01b0390811682526002808601548083169784019790975262ffffff600160a01b88041693830193909352600160b81b90950490910b60608201526003830154909316608084015260049091015490935090915060ff1683565b5f611667816130fc565b60058290556040518281527f2467aeb9c1b7999c2730a0d9535e7b324bc4b0c6ec6f8ffed5534b66de8399929060200161140f565b6013545f906001600160a01b03166116c75760405163cc1be59d60e01b815260040160405180910390fd5b600a54604080516352c7420d60e01b815290515f926001600160a01b0316916352c7420d91600480830192869291908290030181865afa15801561170d573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526117349190810190614a6f565b600354600154601354604080516001600160a01b039485166020820152928416908301528216606082015290861660808201523060a082015260c0015b60408051601f198184030181529082905261178f9291602001614e06565b60408051808303601f1901815282825280516020918201207fff00000000000000000000000000000000000000000000000000000000000000828501523060601b6bffffffffffffffffffffffff191660218501526035840196909652605580840196909652815180840390960186526075909201905283519301929092209392505050565b6013545f9081906001600160a01b03166118425760405163cc1be59d60e01b815260040160405180910390fd5b600a54604080516352c7420d60e01b815290516120c0925f926001600160a01b03909116916352c7420d9160048082019286929091908290030181865afa15801561188f573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526118b69190810190614a6f565b600354601354604080516001600160a01b0393841660208201528a8416918101919091529082166060820152898216608082015290871660a08201529091505f9060c0016114c9565b5f611909816130fc565b6001600160a01b0382166119305760405163d92e233d60e01b815260040160405180910390fd5b601580546001600160a01b0319166001600160a01b0384169081179091556040517f26f2ce530eaacb85b82deb6981f827223a2bd625692d87b396afbc6a6a54aafc905f90a25050565b6013545f906001600160a01b03166119a55760405163cc1be59d60e01b815260040160405180910390fd5b600c54604080516352c7420d60e01b815290515f926001600160a01b0316916352c7420d91600480830192869291908290030181865afa1580156119eb573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611a129190810190614a6f565b600354601354604080516001600160a01b03938416602082015291831690820152908616606082015230608082015260a001611771565b6001600160a01b0381165f908152601260209081526040808320805482518185028101850190935280835260609492939192909184015b82821015611b1d575f84815260209081902060408051606080820183526005870290930180548252825160a0810184526001808301546001600160a01b039081168352600280850154808316858b015262ffffff600160a01b82041685890152600160b81b9004900b9683019690965260038301549095166080820152828601526004015460ff1615159181019190915283529092019101611a80565b505050509050919050565b600b54604080516352c7420d60e01b815290515f92839260809284926001600160a01b0316916352c7420d91600480830192869291908290030181865afa158015611b75573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611b9c9190810190614a6f565b600354604080516001600160a01b0392831660208201528983169181019190915290871660608201529091505f90608001610cc8565b6040805160a0810182525f808252602082018190529181018290526060810182905260808101919091525f611c0d60408401602085016146b6565b6001600160a01b0316611c2360208501856146b6565b6001600160a01b031610611c4a576040516305188ae360e11b815260040160405180910390fd5b5f611c5d610120850161010086016146b6565b6001600160a01b031603611c845760405163d92e233d60e01b815260040160405180910390fd5b5f611c97610160850161014086016146b6565b6001600160a01b031603611cbe5760405163d92e233d60e01b815260040160405180910390fd5b60c0830135158015611cd2575060e0830135155b15611cf05760405163019e6dc160e11b815260040160405180910390fd5b611d0261018084016101608501614b2c565b8015611d3457505f611d18610180850185614b47565b611d299060408101906020016146b6565b6001600160a01b0316145b15611d525760405163d92e233d60e01b815260040160405180910390fd5b335f908152600d60205260409020546001600160a01b031680611da657611d7c8460800135613b93565b335f908152600d6020526040902080546001600160a01b0319166001600160a01b03831617905590505b6040805160a0810190915280611dbf60208701876146b6565b6001600160a01b03168152602001856020016020810190611de091906146b6565b6001600160a01b03168152628000006020820152604090810190611e0a9060608801908801614b65565b60020b81526001600160a01b03831660209091018190526040516319c0fa6160e31b81529194509063ce07d30890611e46908690600401614e22565b5f604051808303815f87803b158015611e5d575f80fd5b505af1158015611e6f573d5f803e3d5ffd5b50505050611e8a8385606001602081019061125b91906146b6565b5f611e9b60c0860160a08701614afb565b62ffffff161115611f11576001600160a01b038116635275965184611ec660c0880160a08901614afb565b6040518363ffffffff1660e01b8152600401611ee3929190614e30565b5f604051808303815f87803b158015611efa575f80fd5b505af1158015611f0c573d5f803e3d5ffd5b505050505b5f611f2f611f2260208701876146b6565b8660c00135600654613693565b90506120558482611f4861012089016101008a016146b6565b611f566101208a018a614bea565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525050505060c08a013560e08b0135611fa56101608d016101408e016146b6565b611fb76101808e016101608f01614b2c565b611fc56101808f018f614b47565b611fce90614c81565b8e806101a00190611fdf9190614d11565b808060200260200160405190810160405280939291908181526020015f905b8282101561203b576040805180820182529080840287019060029083908390808284375f9201919091525050508152600190910190602001611ffe565b50505050508f6101c0018036038101906113aa9190614d57565b92506113cd61206760208701876146b6565b8660c001356006546139cd565b6040805160a0810182525f808252602082018190529181018290526060810182905260808101919091525f6120af60408401602085016146b6565b6001600160a01b03166120c560208501856146b6565b6001600160a01b0316106120ec576040516305188ae360e11b815260040160405180910390fd5b5f6120ff610120850161010086016146b6565b6001600160a01b0316036121265760405163d92e233d60e01b815260040160405180910390fd5b5f612139610160850161014086016146b6565b6001600160a01b0316036121605760405163d92e233d60e01b815260040160405180910390fd5b60c0830135158015612174575060e0830135155b156121925760405163019e6dc160e11b815260040160405180910390fd5b6121a461018084016101608501614b2c565b80156121d657505f6121ba610180850185614b47565b6121cb9060408101906020016146b6565b6001600160a01b0316145b156121f45760405163d92e233d60e01b815260040160405180910390fd5b335f908152600f60205260409020546001600160a01b0316806122485761221e8460800135613c89565b335f908152600f6020526040902080546001600160a01b0319166001600160a01b03831617905590505b6040805160a081019091528061226160208701876146b6565b6001600160a01b0316815260200185602001602081019061228291906146b6565b6001600160a01b031681526280000060208201526040908101906122ac9060608801908801614b65565b60020b81526001600160a01b03831660209091018190526040516319c0fa6160e31b81529194509063ce07d308906122e8908690600401614e22565b5f604051808303815f87803b1580156122ff575f80fd5b505af1158015612311573d5f803e3d5ffd5b50505050611e8a8385606001602081019061232c91906146b6565b613d2c565b5f61233b816130fc565b6001600160a01b0382166123625760405163d92e233d60e01b815260040160405180910390fd5b600980546001600160a01b038481166001600160a01b0319831681179093556040519116919082907f0bd9ce7374b6692c2850de34837b13648cbbb91115800606057fc28c60243b58905f90a3505050565b5f6123be816130fc565b6001600160a01b0382166123e55760405163d92e233d60e01b815260040160405180910390fd5b600b80546001600160a01b038481166001600160a01b0319831681179093556040519116919082907f0bd9ce7374b6692c2850de34837b13648cbbb91115800606057fc28c60243b58905f90a3505050565b6001600160a01b0381165f908152601260209081526040808320805482518185028101850190935280835260609493849084015b82821015612508575f84815260209081902060408051606080820183526005870290930180548252825160a0810184526001808301546001600160a01b039081168352600280850154808316858b015262ffffff600160a01b82041685890152600160b81b9004900b9683019690965260038301549095166080820152828601526004015460ff161515918101919091528352909201910161246b565b505050509050805167ffffffffffffffff811115612528576125286149b6565b604051908082528060200260200182016040528015612551578160200160208202803683370190505b5091505f5b81518110156125a15781818151811061257157612571614e50565b60200260200101515f015183828151811061258e5761258e614e50565b6020908102919091010152600101612556565b5050919050565b5f6125b2816130fc565b6001600160a01b0382166125d95760405163d92e233d60e01b815260040160405180910390fd5b600c80546001600160a01b038481166001600160a01b0319831681179093556040519116919082907fdeff25089442120c3e5d2fc7072cb58c8287d65c1fdb6501f281923beb331f3d905f90a3505050565b5f82815260208190526040902060010154612645816130fc565b610e198383613b12565b5f612659816130fc565b60078290556040518281527faa6fbd4ea51a023802ca95b28849c3292d916de40795840276e000614241fd339060200161140f565b6040805160a0810182525f808252602082018190529181018290526060810182905260808101919091525f6126c960408401602085016146b6565b6001600160a01b03166126df60208501856146b6565b6001600160a01b031610612706576040516305188ae360e11b815260040160405180910390fd5b5f612719610180850161016086016146b6565b6001600160a01b0316036127405760405163d92e233d60e01b815260040160405180910390fd5b5f6127536101c085016101a086016146b6565b6001600160a01b03160361277a5760405163d92e233d60e01b815260040160405180910390fd5b6101208301351580156127905750610140830135155b156127ae5760405163019e6dc160e11b815260040160405180910390fd5b620186a06127c260e0850160c08601614afb565b62ffffff1611156127e65760405163162908e360e11b815260040160405180910390fd5b6127106127f960e0850160c08601614afb565b62ffffff16101561281d5760405163162908e360e11b815260040160405180910390fd5b61282f6101e084016101c08501614b2c565b801561286157505f6128456101e0850185614b47565b6128569060408101906020016146b6565b6001600160a01b0316145b1561287f5760405163d92e233d60e01b815260040160405180910390fd5b5f80612893610340860161032087016146b6565b6001600160a01b0316036128a757336128b9565b6128b9610340850161032086016146b6565b6001600160a01b038082165f9081526010602052604090205491925016806129cd576128e9856080013583613f8e565b9050613fff811660c0808316811461291457604051632a96f9e160e21b815260040160405180910390fd5b6001600160a01b038481165f908152601060205260409081902080546001600160a01b03191686841690811790915560135491516350d2994b60e11b8152600481019190915291169063a1a53296906024015f604051808303815f87803b15801561297d575f80fd5b505af115801561298f573d5f803e3d5ffd5b50506040516001600160a01b038087169350871691507f8fcacf3ee9b00512c4a7bf8c3c70ebf3f8d5a2312f59e74f2451ab3c475706a5905f90a350505b6040805160a08101909152806129e660208801886146b6565b6001600160a01b03168152602001866020016020810190612a0791906146b6565b6001600160a01b03168152628000006020820152604090810190612a319060608901908901614b65565b60020b81526001600160a01b0383166020909101819052909450639d32af2885612a6160c0890160a08a01614afb565b612a7160e08a0160c08b01614afb565b612a826101008b0160e08c01614b80565b612a946101208c016101008d01614afb565b6040518663ffffffff1660e01b8152600401612ab4959493929190614ba3565b5f604051808303815f87803b158015612acb575f80fd5b505af1158015612add573d5f803e3d5ffd5b50505050612af88486606001602081019061232c91906146b6565b505f9050612b1a612b0c60208601866146b6565b856101200135600754613693565b9050612c3f8382612b33610180880161016089016146b6565b612b41610180890189614bea565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152505050506101208901356101408a0135612b926101c08c016101a08d016146b6565b612ba46101e08d016101c08e01614b2c565b612bb26101e08e018e614b47565b612bbb90614c81565b612bc96102008f018f614d11565b808060200260200160405190810160405280939291908181526020015f905b82821015612c25576040805180820182529080840287019060029083908390808284375f9201919091525050508152600190910190602001612be8565b50505050508e610220018036038101906113aa9190614d57565b9150612c5f612c5160208601866146b6565b8561012001356007546139cd565b50915091565b6040805160a0810182525f808252602082018190529181018290526060810182905260808101919091525f612ca060408401602085016146b6565b6001600160a01b0316612cb660208501856146b6565b6001600160a01b031610612cdd576040516305188ae360e11b815260040160405180910390fd5b5f612cef610100850160e086016146b6565b6001600160a01b031603612d165760405163d92e233d60e01b815260040160405180910390fd5b5f612d29610140850161012086016146b6565b6001600160a01b031603612d505760405163d92e233d60e01b815260040160405180910390fd5b60a0830135158015612d64575060c0830135155b15612d825760405163019e6dc160e11b815260040160405180910390fd5b62800000612d966060850160408601614afb565b62ffffff1603612db95760405163dfe6158b60e01b815260040160405180910390fd5b612dcb61016084016101408501614b2c565b8015612dfd57505f612de1610160850185614b47565b612df29060408101906020016146b6565b6001600160a01b0316145b15612e1b5760405163d92e233d60e01b815260040160405180910390fd5b6040805160a0810190915280612e3460208601866146b6565b6001600160a01b03168152602001846020016020810190612e5591906146b6565b6001600160a01b03168152602001612e736060860160408701614afb565b62ffffff168152602001612e8d6080860160608701614b65565b60020b81526004546001600160a01b03166020909101529150612ec082612eba60a08601608087016146b6565b5f613340565b5f612ede612ed160208601866146b6565b8560a00135600554613693565b90506130008382612ef6610100880160e089016146b6565b612f04610100890189614bea565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525050505060a089013560c08a0135612f536101408c016101208d016146b6565b612f656101608d016101408e01614b2c565b612f736101608e018e614b47565b612f7c90614c81565b612f8a6101808f018f614d11565b808060200260200160405190810160405280939291908181526020015f905b82821015612fe6576040805180820182529080840287019060029083908390808284375f9201919091525050508152600190910190602001612fa9565b50505050508e6101a0018036038101906113aa9190614d57565b9150612c5f61301260208601866146b6565b8560a001356005546139cd565b5f80613fff851694505f848460405160200161303c929190614e06565b60405160208183030381529060405290505f805b620272bc8110156130a5576130668982856140a8565b9150613fff82166001600160a01b03891614801561308c57506001600160a01b0382163b155b1561309d5790935091506130f39050565b600101613050565b5060405162461bcd60e51b815260206004820152601e60248201527f486f6f6b4d696e65723a20636f756c64206e6f742066696e642073616c74000060448201526064015b60405180910390fd5b94509492505050565b6131068133614121565b50565b5f80808061311f610340860161032087016146b6565b6001600160a01b0316036131335733613145565b613145610340850161032086016146b6565b6001600160a01b038082165f908152600e602052604090205416935090508261325b57613176846080013582614177565b9250613fff83166120c080851681146131a257604051632a96f9e160e21b815260040160405180910390fd5b6001600160a01b038381165f908152600e60205260409081902080546001600160a01b03191688841690811790915560135491516350d2994b60e11b8152600481019190915291169063a1a53296906024015f604051808303815f87803b15801561320b575f80fd5b505af115801561321d573d5f803e3d5ffd5b50506040516001600160a01b038089169350861691507f8fcacf3ee9b00512c4a7bf8c3c70ebf3f8d5a2312f59e74f2451ab3c475706a5905f90a350505b5f61329282608087013561327260208901896146b6565b61328260408a0160208b016146b6565b6105c960608b0160408c01614b65565b5f818152601460205260409020549091506001600160a01b031680158015906132c457506001600160a01b0381163314155b156132e25760405163de14f86560e01b815260040160405180910390fd5b6001600160a01b03811615613338575f8281526014602052604080822080546001600160a01b03191690555183917fa43c93c12a241464ace3decc5c835ed1c440a3a31afad7747cbec8ca9d279a3791a2600193505b505050915091565b60035460405163313b65df60e11b81526001600160a01b0390911690636276cbbe90613372908690869060040161475c565b6020604051808303815f875af115801561338e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906133b29190614e64565b506002546001600160a01b031663d6b25f0b6133cf8560a0902090565b856040518363ffffffff1660e01b81526004016133ed929190614e7f565b5f604051808303815f87803b158015613404575f80fd5b505af1158015613416573d5f803e3d5ffd5b505050505f6134268460a0902090565b5f8181526011602090815260408083208054336001600160a01b03199182168117909255818552601284528285208351606080820186528882528187018d81528b1515838801908152845460018181018755958b529989902093516005909a02909301988955518051938901805486166001600160a01b0395861617905596870151600289018054978901519289015191851676ffffffffffffffffffffffffffffffffffffffffffffff1990981697909717600160a01b62ffffff938416021762ffffff60b81b1916600160b81b9290911691909102179094556080948501516003870180549093169082161790915591516004909401805460ff191694151594909417909355908701519293509190911690827fb29812400276d077334c388dc76eb945746169469439cda860c7787bd3856a018561356b578760400151613570565b628000005b60405162ffffff909116815260200160405180910390a46040518215158152819033907fc223bf2c7087f12483b2d44ae651b6dc077e37d639852808d9f9a9150a704ac09060200160405180910390a36001546001600160a01b0316636a90700b6135dc8660a0902090565b6040516001600160e01b031960e084901b1681526004810191909152600160248201526044015f604051808303815f87803b158015613619575f80fd5b505af115801561362b573d5f803e3d5ffd5b50506001546080870151604051632acfe5f560e11b81526001600160a01b0391821660048201529116925063559fcbea91506024015f604051808303815f87803b158015613677575f80fd5b505af1158015613689573d5f803e3d5ffd5b5050505050505050565b5f816001600160a01b0385166136b3576136ad8482614ea7565b90508391505b803410156136d457604051631a84bc4160e21b815260040160405180910390fd5b8215613726578260085f8282546136eb9190614ea7565b909155505060405183815233907fdc1278cd3aa93a00427622f7f3aa06ab8bd89ddcdca97c4c9978ce404ddb1d2d9060200160405180910390a25b509392505050565b5f6137428c5f01518d602001518a8a61425b565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316632f6b4b0e8e8d8d6040518463ffffffff1660e01b815260040161379393929190614ee8565b602060405180830381865afa1580156137ae573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137d29190614f16565b90506137e88d5f01518e602001518b8b856142a7565b82516001600160a01b031661389a577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316637b47a0ae8d8f8e8e8e8e8e8c8c6040518a63ffffffff1660e01b8152600401613852989796959493929190615010565b60206040518083038185885af115801561386e573d5f803e3d5ffd5b50505050506040513d601f19601f820116820180604052508101906138939190614f16565b915061399c565b85156138fd577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638f1c19c98d8f8e8e8e8e8e8d8d8d6040518b63ffffffff1660e01b81526004016138529998979695949392919061508e565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316637b47a0ae8d8f8e8e8e8e8e8c8c6040518a63ffffffff1660e01b8152600401613958989796959493929190615010565b60206040518083038185885af1158015613974573d5f803e3d5ffd5b50505050506040513d601f19601f820116820180604052508101906139999190614f16565b91505b806001600160a01b0316826001600160a01b0316146139bd576139bd61518f565b509b9a5050505050505050505050565b806001600160a01b0384166139e9576139e68382614ea7565b90505b5f6139f482346151a3565b90508015613a64576040515f90339083908381818185875af1925050503d805f8114613a3b576040519150601f19603f3d011682016040523d82523d5f602084013e613a40565b606091505b5050905080613a6257604051633fdf366b60e11b815260040160405180910390fd5b505b5050505050565b5f828152602081815260408083206001600160a01b038516845290915281205460ff16613b0b575f838152602081815260408083206001600160a01b03861684529091529020805460ff19166001179055613ac33390565b6001600160a01b0316826001600160a01b0316847f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a4506001610b30565b505f610b30565b5f828152602081815260408083206001600160a01b038516845290915281205460ff1615613b0b575f838152602081815260408083206001600160a01b0386168085529252808320805460ff1916905551339286917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a4506001610b30565b5f805f60095f9054906101000a90046001600160a01b03166001600160a01b03166352c7420d6040518163ffffffff1660e01b81526004015f60405180830381865afa158015613be5573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052613c0c9190810190614a6f565b600354600154604080516001600160a01b039384166020820152929091169082015233606082015230608082015260a0015b60408051601f1981840301815290829052613c5c9291602001614e06565b6040516020818303038152906040529050838151602083015ff59150813b613c82575f80fd5b5092915050565b5f805f600b5f9054906101000a90046001600160a01b03166001600160a01b03166352c7420d6040518163ffffffff1660e01b81526004015f60405180830381865afa158015613cdb573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052613d029190810190614a6f565b600354604080516001600160a01b0390921660208301523390820152306060820152608001613c3e565b60035460405163313b65df60e11b81526001600160a01b0390911690636276cbbe90613d5e908590859060040161475c565b6020604051808303815f875af1158015613d7a573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613d9e9190614e64565b506002546001600160a01b031663d6b25f0b613dbb8460a0902090565b846040518363ffffffff1660e01b8152600401613dd9929190614e7f565b5f604051808303815f87803b158015613df0575f80fd5b505af1158015613e02573d5f803e3d5ffd5b505050505f613e128360a0902090565b5f8181526011602090815260408083208054336001600160a01b03199182168117909255818552601284528285208351606080820186528882528187018c8152600183880181815285548083018755958b529989902093516005909502909301938455518051928401805486166001600160a01b0394851617905580880151600285018054838a01519484015192861676ffffffffffffffffffffffffffffffffffffffffffffff1990911617600160a01b62ffffff958616021762ffffff60b81b1916600160b81b9490921693909302179091556080908101516003840180549095169083161790935595516004909101805460ff1916911515919091179055880151915162800000815294955092169284917fb29812400276d077334c388dc76eb945746169469439cda860c7787bd3856a01910160405180910390a460405160018152819033907fc223bf2c7087f12483b2d44ae651b6dc077e37d639852808d9f9a9150a704ac09060200160405180910390a3505050565b6013545f906001600160a01b0316613fb95760405163cc1be59d60e01b815260040160405180910390fd5b5f80600c5f9054906101000a90046001600160a01b03166001600160a01b03166352c7420d6040518163ffffffff1660e01b81526004015f60405180830381865afa15801561400a573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526140319190810190614a6f565b600354601354604080516001600160a01b03938416602082015291831690820152908616606082015230608082015260a0015b60408051601f19818403018152908290526140829291602001614e06565b6040516020818303038152906040529050848151602083015ff59150813b613726575f80fd5b8051602080830191909120604080517fff0000000000000000000000000000000000000000000000000000000000000081850152606087901b6bffffffffffffffffffffffff191660218201526035810186905260558082019390935281518082039093018352607501905280519101205b9392505050565b5f828152602081815260408083206001600160a01b038516845290915290205460ff166141735760405163e2517d3f60e01b81526001600160a01b0382166004820152602481018390526044016130ea565b5050565b6013545f906001600160a01b03166141a25760405163cc1be59d60e01b815260040160405180910390fd5b5f80600a5f9054906101000a90046001600160a01b03166001600160a01b03166352c7420d6040518163ffffffff1660e01b81526004015f60405180830381865afa1580156141f3573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261421a9190810190614a6f565b600354600154601354604080516001600160a01b039485166020820152928416908301528216606082015290861660808201523060a082015260c001614064565b6001600160a01b0384161515801561427257505f82115b1561428c5761428c6001600160a01b0385163330856142f1565b8015610e1957610e196001600160a01b0384163330846142f1565b6001600160a01b038516151580156142be57505f83115b156142d7576142d76001600160a01b038616828561436d565b8115613a6457613a646001600160a01b038516828461436d565b6040516001600160a01b038481166024830152838116604483015260648201839052610e199186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff838183161783525050505061440d565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1663095ea7b360e01b1790526143d3848261446e565b610e19576040516001600160a01b0384811660248301525f604483015261440791869182169063095ea7b390606401614326565b610e1984825b5f6144216001600160a01b0384168361450f565b905080515f1415801561444557508080602001905181019061444391906151b6565b155b1561154b57604051635274afe760e01b81526001600160a01b03841660048201526024016130ea565b5f805f846001600160a01b03168460405161448991906151d1565b5f604051808303815f865af19150503d805f81146144c2576040519150601f19603f3d011682016040523d82523d5f602084013e6144c7565b606091505b50915091508180156144f15750805115806144f15750808060200190518101906144f191906151b6565b801561450657505f856001600160a01b03163b115b95945050505050565b606061411a83835f845f80856001600160a01b0316848660405161453391906151d1565b5f6040518083038185875af1925050503d805f811461456d576040519150601f19603f3d011682016040523d82523d5f602084013e614572565b606091505b509150915061458286838361458c565b9695505050505050565b6060826145a15761459c826145e8565b61411a565b81511580156145b857506001600160a01b0384163b155b156145e157604051639996b31560e01b81526001600160a01b03851660048201526024016130ea565b508061411a565b8051156145f85780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b5f60208284031215614621575f80fd5b81356001600160e01b03198116811461411a575f80fd5b6001600160a01b0381168114613106575f80fd5b803561465781614638565b919050565b5f806040838503121561466d575f80fd5b82359150602083013561467f81614638565b809150509250929050565b5f806040838503121561469b575f80fd5b82356146a681614638565b9150602083013561467f81614638565b5f602082840312156146c6575f80fd5b813561411a81614638565b5f602082840312156146e1575f80fd5b813567ffffffffffffffff8111156146f7575f80fd5b8201610340818503121561411a575f80fd5b6001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b60c0810161476a8285614709565b6001600160a01b03831660a08301529392505050565b5f60208284031215614790575f80fd5b5035919050565b5f805f606084860312156147a9575f80fd5b83356147b481614638565b925060208401356147c481614638565b915060408401356147d481614638565b809150509250925092565b8060020b8114613106575f80fd5b8035614657816147df565b5f805f805f60a0868803121561480c575f80fd5b853561481781614638565b945060208601359350604086013561482e81614638565b9250606086013561483e81614638565b9150608086013561484e816147df565b809150509295509295909350565b5f806040838503121561486d575f80fd5b823561487881614638565b946020939093013593505050565b83815260e0810161489a6020830185614709565b82151560c0830152949350505050565b602080825282518282018190525f918401906040840190835b818110156149045783518051845260208101516148e36020860182614709565b5060400151151560c08401526020939093019260e0909201916001016148c3565b509095945050505050565b5f6020828403121561491f575f80fd5b813567ffffffffffffffff811115614935575f80fd5b82016102c0818503121561411a575f80fd5b602080825282518282018190525f918401906040840190835b81811015614904578351835260209384019390920191600101614960565b5f6020828403121561498e575f80fd5b813567ffffffffffffffff8111156149a4575f80fd5b82016102a0818503121561411a575f80fd5b634e487b7160e01b5f52604160045260245ffd5b60405160c0810167ffffffffffffffff811182821017156149ed576149ed6149b6565b60405290565b604051610100810167ffffffffffffffff811182821017156149ed576149ed6149b6565b604051601f8201601f1916810167ffffffffffffffff81118282101715614a4057614a406149b6565b604052919050565b5f67ffffffffffffffff821115614a6157614a616149b6565b50601f01601f191660200190565b5f60208284031215614a7f575f80fd5b815167ffffffffffffffff811115614a95575f80fd5b8201601f81018413614aa5575f80fd5b8051614ab8614ab382614a48565b614a17565b818152856020838501011115614acc575f80fd5b8160208401602083015e5f91810160200191909152949350505050565b803562ffffff81168114614657575f80fd5b5f60208284031215614b0b575f80fd5b61411a82614ae9565b8015158114613106575f80fd5b803561465781614b14565b5f60208284031215614b3c575f80fd5b813561411a81614b14565b5f823560be19833603018112614b5b575f80fd5b9190910192915050565b5f60208284031215614b75575f80fd5b813561411a816147df565b5f60208284031215614b90575f80fd5b813563ffffffff8116811461411a575f80fd5b6101208101614bb28288614709565b62ffffff861660a083015262ffffff851660c083015263ffffffff841660e083015262ffffff83166101008301529695505050505050565b5f808335601e19843603018112614bff575f80fd5b83018035915067ffffffffffffffff821115614c19575f80fd5b602001915036819003821315614c2d575f80fd5b9250929050565b5f82601f830112614c43575f80fd5b8135614c51614ab382614a48565b818152846020838601011115614c65575f80fd5b816020850160208301375f918101602001919091529392505050565b5f60c08236031215614c91575f80fd5b614c996149ca565b823560048110614ca7575f80fd5b8152614cb56020840161464c565b6020820152604083013567ffffffffffffffff811115614cd3575f80fd5b614cdf36828601614c34565b604083015250614cf160608401614b21565b60608201526080838101359082015260a092830135928101929092525090565b5f808335601e19843603018112614d26575f80fd5b83018035915067ffffffffffffffff821115614d40575f80fd5b6020019150600681901b3603821315614c2d575f80fd5b5f610100828403128015614d69575f80fd5b50614d726149f3565b8235614d7d81614638565b8152614d8b602084016147ed565b6020820152614d9c60408401614ae9565b6040820152614dad60608401614ae9565b6060820152614dbe60808401614ae9565b608082015260a0838101359082015260c08084013590820152614de360e08401614b21565b60e08201529392505050565b5f81518060208401855e5f93019283525090919050565b5f614e1a614e148386614def565b84614def565b949350505050565b60a08101610b308284614709565b60c08101614e3e8285614709565b62ffffff831660a08301529392505050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215614e74575f80fd5b815161411a816147df565b82815260c0810161411a6020830184614709565b634e487b7160e01b5f52601160045260245ffd5b80820180821115610b3057610b30614e93565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b614ef28185614709565b6001600160a01b03831660a082015260e060c08201525f61450660e0830184614eba565b5f60208284031215614f26575f80fd5b815161411a81614638565b5f8151808452602084019350602083015f5b82811015614f88578151865f5b6002811015614f6f578251825260209283019290910190600101614f50565b5050506040959095019460209190910190600101614f43565b5093949350505050565b6001600160a01b038151168252602081015160020b602083015262ffffff60408201511660408301526060810151614fd1606084018262ffffff169052565b506080810151614fe8608084018262ffffff169052565b5060a081015160a083015260c081015160c083015260e081015161154b60e084018215159052565b61501a818a614709565b6001600160a01b03881660a082015261026060c08201525f615040610260830189614eba565b8760e0840152866101008401526001600160a01b0386166101208401528281036101408401526150708186614f31565b915050615081610160830184614f92565b9998505050505050505050565b615098818b614709565b6001600160a01b03891660a082015261028060c08201525f6150be61028083018a614eba565b8860e0840152876101008401526001600160a01b03871661012084015282810361014084015285516004811061510257634e487b7160e01b5f52602160045260245ffd5b808252506001600160a01b036020870151166020820152604086015160c0604083015261513260c0830182614eba565b90506060870151615147606084018215159052565b506080870151608083015260a087015160a083015283810361016085015261516f8187614f31565b92505050615181610180830184614f92565b9a9950505050505050505050565b634e487b7160e01b5f52600160045260245ffd5b81810381811115610b3057610b30614e93565b5f602082840312156151c6575f80fd5b815161411a81614b14565b5f61411a8284614def56fea2646970667358221220448ddaa40a5536dd53573c5b0cbe7190da510fedbe720a6684183d3a2bab3bd064736f6c634300081a00330000000000000000000000004483915019f259814b410a12a9f8633e5d85208f00000000000000000000000029c1ebd856769fb4a3e8d30f609196baaf3c10c0000000000000000000000000c920e83e5d91758baf1b138fbce893df7a3f4dd0000000000000000000000000d11dd2cf14593e1d4736a054f6d9c726dac81a210000000000000000000000001fd1be7495fe49eb404a3b6457331fac3811df2c000000000000000000000000daebe16c001d7368409c654bf3027082719db2ef00000000000000000000000070be410728e7b4b4f53149ed02ddc97c4c0197cd
Deployed Bytecode
0x608060405260043610610353575f3560e01c80637224dc82116101bd578063b66b1d6f116100f2578063d547741f11610092578063f07f574e1161006d578063f07f574e14610a88578063f1716acf14610aa7578063f4c7a2a214610aba578063fc3d920e14610acd575f80fd5b8063d547741f14610a16578063d61d6b8314610a35578063dc4c90d314610a69575f80fd5b8063c30aa893116100cd578063c30aa89314610997578063c30d261f146109ac578063c84728ef146109cb578063cdb77163146109f7575f80fd5b8063b66b1d6f1461093a578063bb1e707714610959578063bb46d76514610978575f80fd5b80639003adfe1161015d5780639f541711116101385780639f541711146108cd578063a217fddf146108e0578063a5214e18146108f3578063a605e3b514610906575f80fd5b80639003adfe1461085757806391d148541461086c5780639d347281146108ae575f80fd5b80637981581b116101985780637981581b146107d85780637b5708f3146107ed578063897371f5146108195780638dd121b214610838575f80fd5b80637224dc821461077057806373bc22961461078f5780637883b59e146107c3575f80fd5b80632f2ff15d1161029357806346eea25711610233578063522066ca1161020e578063522066ca146106b65780635f072d56146106ea57806362a2a47c1461071e57806363a9084a14610751575f80fd5b806346eea2571461065957806348566a33146106785780634998476c14610697575f80fd5b80633d7b0f5f1161026e5780633d7b0f5f146105ce57806341d9c94d146105fc57806342c4bf091461061b578063462e997b1461063a575f80fd5b80632f2ff15d1461057157806336568abe146105905780633c63ec42146105af575f80fd5b80631dca04e0116102fe578063248a9ca3116102d9578063248a9ca3146104c35780632be1b438146104ff5780632c398d781461051e5780632eaee54514610552575f80fd5b80631dca04e0146104645780631fce4a331461048357806320aec29e146104a2575f80fd5b806309ac3c791161032e57806309ac3c79146103e85780630e3547c014610409578063164e68de14610445575f80fd5b806301ffc9a71461035e5780630286d77e1461039257806303c7f7dd146103c9575f80fd5b3661035a57005b5f80fd5b348015610369575f80fd5b5061037d610378366004614611565b610b00565b60405190151581526020015b60405180910390f35b34801561039d575f80fd5b506015546103b1906001600160a01b031681565b6040516001600160a01b039091168152602001610389565b3480156103d4575f80fd5b50600b546103b1906001600160a01b031681565b3480156103f3575f80fd5b5061040761040236600461465c565b610b36565b005b348015610414575f80fd5b5061042861042336600461468a565b610bee565b604080519283526001600160a01b03909116602083015201610389565b348015610450575f80fd5b5061040761045f3660046146b6565b610cf2565b34801561046f575f80fd5b5061040761047e3660046146b6565b610e1f565b34801561048e575f80fd5b5061040761049d3660046146b6565b610ea2565b6104b56104b03660046146d1565b610f1d565b60405161038992919061475c565b3480156104ce575f80fd5b506104f16104dd366004614780565b5f9081526020819052604090206001015490565b604051908152602001610389565b34801561050a575f80fd5b50610407610519366004614780565b6113d4565b348015610529575f80fd5b506103b16105383660046146b6565b60106020525f90815260409020546001600160a01b031681565b34801561055d575f80fd5b5061042861056c366004614797565b61141b565b34801561057c575f80fd5b5061040761058b36600461465c565b6114f4565b34801561059b575f80fd5b506104076105aa36600461465c565b611518565b3480156105ba575f80fd5b506104f16105c93660046147f8565b611550565b3480156105d9575f80fd5b506105ed6105e836600461485c565b6115c4565b60405161038993929190614886565b348015610607575f80fd5b50600c546103b1906001600160a01b031681565b348015610626575f80fd5b50610407610635366004614780565b61165d565b348015610645575f80fd5b506103b161065436600461485c565b61169c565b348015610664575f80fd5b50610428610673366004614797565b611815565b348015610683575f80fd5b506001546103b1906001600160a01b031681565b3480156106a2575f80fd5b506104076106b13660046146b6565b6118ff565b3480156106c1575f80fd5b506103b16106d0366004614780565b60116020525f90815260409020546001600160a01b031681565b3480156106f5575f80fd5b506103b16107043660046146b6565b600f6020525f90815260409020546001600160a01b031681565b348015610729575f80fd5b506104f17f2dca0f5ce7e75a4b43fe2b0d6f5d0b7a2bf92ecf89f8f0aa17b8308b6703882181565b34801561075c575f80fd5b506004546103b1906001600160a01b031681565b34801561077b575f80fd5b506103b161078a36600461485c565b61197a565b34801561079a575f80fd5b506103b16107a93660046146b6565b600e6020525f90815260409020546001600160a01b031681565b3480156107ce575f80fd5b506104f160075481565b3480156107e3575f80fd5b506104f160065481565b3480156107f8575f80fd5b5061080c6108073660046146b6565b611a49565b60405161038991906148aa565b348015610824575f80fd5b5061042861083336600461468a565b611b28565b348015610843575f80fd5b506013546103b1906001600160a01b031681565b348015610862575f80fd5b506104f160085481565b348015610877575f80fd5b5061037d61088636600461465c565b5f918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b3480156108b9575f80fd5b506002546103b1906001600160a01b031681565b6104b56108db36600461490f565b611bd2565b3480156108eb575f80fd5b506104f15f81565b6104b561090136600461490f565b612074565b348015610911575f80fd5b506103b1610920366004614780565b60146020525f90815260409020546001600160a01b031681565b348015610945575f80fd5b506104076109543660046146b6565b612331565b348015610964575f80fd5b50600a546103b1906001600160a01b031681565b348015610983575f80fd5b506104076109923660046146b6565b6123b4565b3480156109a2575f80fd5b506104f160055481565b3480156109b7575f80fd5b506009546103b1906001600160a01b031681565b3480156109d6575f80fd5b506109ea6109e53660046146b6565b612437565b6040516103899190614947565b348015610a02575f80fd5b50610407610a113660046146b6565b6125a8565b348015610a21575f80fd5b50610407610a3036600461465c565b61262b565b348015610a40575f80fd5b506103b1610a4f3660046146b6565b600d6020525f90815260409020546001600160a01b031681565b348015610a74575f80fd5b506003546103b1906001600160a01b031681565b348015610a93575f80fd5b50610407610aa2366004614780565b61264f565b6104b5610ab53660046146d1565b61268e565b6104b5610ac836600461497e565b612c65565b348015610ad8575f80fd5b506103b17f000000000000000000000000c920e83e5d91758baf1b138fbce893df7a3f4dd081565b5f6001600160e01b03198216637965db0b60e01b1480610b3057506301ffc9a760e01b6001600160e01b03198316145b92915050565b6015546001600160a01b03163314610b6157604051631ac3200f60e21b815260040160405180910390fd5b5f828152601460205260409020546001600160a01b031615610b965760405163ef7a0c8d60e01b815260040160405180910390fd5b5f8281526014602052604080822080546001600160a01b0319166001600160a01b0385169081179091559051909184917fd9345d9350de063de8ed64ea65f84f4cb4d084a36c923e457522c8b46bb85e1b9190a35050565b6013545f9081906001600160a01b0316610c1b5760405163cc1be59d60e01b815260040160405180910390fd5b600c54604080516352c7420d60e01b8152905160c0925f926001600160a01b03909116916352c7420d9160048082019286929091908290030181865afa158015610c67573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610c8e9190810190614a6f565b600354601354604080516001600160a01b03938416602082015291831690820152888216606082015290871660808201529091505f9060a0015b6040516020818303038152906040529050610ce58684848461301f565b9890975095505050505050565b7f2dca0f5ce7e75a4b43fe2b0d6f5d0b7a2bf92ecf89f8f0aa17b8308b67038821610d1c816130fc565b6001600160a01b038216610d435760405163d92e233d60e01b815260040160405180910390fd5b6008545f819003610d6757604051630d00db4d60e31b815260040160405180910390fd5b5f6008556040518181526001600160a01b038416907fc0819c13be868895eb93e40eaceb96de976442fa1d404e5c55f14bb65a8c489a9060200160405180910390a25f836001600160a01b0316826040515f6040518083038185875af1925050503d805f8114610df2576040519150601f19603f3d011682016040523d82523d5f602084013e610df7565b606091505b5050905080610e195760405163b12d13eb60e01b815260040160405180910390fd5b50505050565b5f610e29816130fc565b6001600160a01b038216610e505760405163d92e233d60e01b815260040160405180910390fd5b600a80546001600160a01b038481166001600160a01b0319831681179093556040519116919082907fdeff25089442120c3e5d2fc7072cb58c8287d65c1fdb6501f281923beb331f3d905f90a3505050565b5f610eac816130fc565b6001600160a01b038216610ed35760405163d92e233d60e01b815260040160405180910390fd5b601380546001600160a01b0319166001600160a01b0384169081179091556040517f4a4603e6539261d5881585a47c1eaa39ba238693700eb1c852b99b2a57bd1c23905f90a25050565b6040805160a0810182525f808252602082018190529181018290526060810182905260808101919091525f610f5860408401602085016146b6565b6001600160a01b0316610f6e60208501856146b6565b6001600160a01b031610610f95576040516305188ae360e11b815260040160405180910390fd5b5f610fa8610180850161016086016146b6565b6001600160a01b031603610fcf5760405163d92e233d60e01b815260040160405180910390fd5b5f610fe26101c085016101a086016146b6565b6001600160a01b0316036110095760405163d92e233d60e01b815260040160405180910390fd5b61012083013515801561101f5750610140830135155b1561103d5760405163019e6dc160e11b815260040160405180910390fd5b620186a061105160e0850160c08601614afb565b62ffffff1611156110755760405163162908e360e11b815260040160405180910390fd5b61271061108860e0850160c08601614afb565b62ffffff1610156110ac5760405163162908e360e11b815260040160405180910390fd5b6110be6101e084016101c08501614b2c565b80156110f057505f6110d46101e0850185614b47565b6110e59060408101906020016146b6565b6001600160a01b0316145b1561110e5760405163d92e233d60e01b815260040160405180910390fd5b5f805f61111a86613109565b915091508061112b5760075461112d565b5f5b6040805160a081019091529093508061114960208901896146b6565b6001600160a01b0316815260200187602001602081019061116a91906146b6565b6001600160a01b031681526280000060208201526040908101906111949060608a01908a01614b65565b60020b81526001600160a01b0384166020909101819052909550639d32af28866111c460c08a0160a08b01614afb565b6111d460e08b0160c08c01614afb565b6111e56101008c0160e08d01614b80565b6111f76101208d016101008e01614afb565b6040518663ffffffff1660e01b8152600401611217959493929190614ba3565b5f604051808303815f87803b15801561122e575f80fd5b505af1158015611240573d5f803e3d5ffd5b505050506112628587606001602081019061125b91906146b6565b6001613340565b505f905061128261127660208701876146b6565b86610120013584613693565b90506113af848261129b61018089016101608a016146b6565b6112a96101808a018a614bea565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152505050506101208a01356101408b01356112fa6101c08d016101a08e016146b6565b61130c6101e08e016101c08f01614b2c565b61131a6101e08f018f614b47565b61132390614c81565b8e8061020001906113349190614d11565b808060200260200160405190810160405280939291908181526020015f905b82821015611390576040805180820182529080840287019060029083908390808284375f9201919091525050508152600190910190602001611353565b50505050508f610220018036038101906113aa9190614d57565b61372e565b92506113cd6113c160208701876146b6565b866101200135846139cd565b5050915091565b5f6113de816130fc565b60068290556040518281527f6da0320d887f02077fcd4adbf4fdc333fcfb8f4f6c017a83ec8d2f141d41d2ec906020015b60405180910390a15050565b600954604080516352c7420d60e01b815290515f92839260c09284926001600160a01b0316916352c7420d91600480830192869291908290030181865afa158015611468573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261148f9190810190614a6f565b600354604080516001600160a01b03928316602082015289831691810191909152898216606082015290871660808201529091505f9060a0015b60405160208183030381529060405290506114e68684848461301f565b999098509650505050505050565b5f8281526020819052604090206001015461150e816130fc565b610e198383613a6b565b6001600160a01b03811633146115415760405163334bd91960e11b815260040160405180910390fd5b61154b8282613b12565b505050565b6001600160a01b038086165f908152600e60205260408120549091168061157e5761157b878761169c565b90505b6040805160a080820183526001600160a01b0397881682529587166020820152628000009181019190915260029390930b60608401529093166080820152209392505050565b6012602052815f5260405f2081815481106115dd575f80fd5b5f91825260209182902060059091020180546040805160a08101825260018401546001600160a01b0390811682526002808601548083169784019790975262ffffff600160a01b88041693830193909352600160b81b90950490910b60608201526003830154909316608084015260049091015490935090915060ff1683565b5f611667816130fc565b60058290556040518281527f2467aeb9c1b7999c2730a0d9535e7b324bc4b0c6ec6f8ffed5534b66de8399929060200161140f565b6013545f906001600160a01b03166116c75760405163cc1be59d60e01b815260040160405180910390fd5b600a54604080516352c7420d60e01b815290515f926001600160a01b0316916352c7420d91600480830192869291908290030181865afa15801561170d573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526117349190810190614a6f565b600354600154601354604080516001600160a01b039485166020820152928416908301528216606082015290861660808201523060a082015260c0015b60408051601f198184030181529082905261178f9291602001614e06565b60408051808303601f1901815282825280516020918201207fff00000000000000000000000000000000000000000000000000000000000000828501523060601b6bffffffffffffffffffffffff191660218501526035840196909652605580840196909652815180840390960186526075909201905283519301929092209392505050565b6013545f9081906001600160a01b03166118425760405163cc1be59d60e01b815260040160405180910390fd5b600a54604080516352c7420d60e01b815290516120c0925f926001600160a01b03909116916352c7420d9160048082019286929091908290030181865afa15801561188f573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526118b69190810190614a6f565b600354601354604080516001600160a01b0393841660208201528a8416918101919091529082166060820152898216608082015290871660a08201529091505f9060c0016114c9565b5f611909816130fc565b6001600160a01b0382166119305760405163d92e233d60e01b815260040160405180910390fd5b601580546001600160a01b0319166001600160a01b0384169081179091556040517f26f2ce530eaacb85b82deb6981f827223a2bd625692d87b396afbc6a6a54aafc905f90a25050565b6013545f906001600160a01b03166119a55760405163cc1be59d60e01b815260040160405180910390fd5b600c54604080516352c7420d60e01b815290515f926001600160a01b0316916352c7420d91600480830192869291908290030181865afa1580156119eb573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611a129190810190614a6f565b600354601354604080516001600160a01b03938416602082015291831690820152908616606082015230608082015260a001611771565b6001600160a01b0381165f908152601260209081526040808320805482518185028101850190935280835260609492939192909184015b82821015611b1d575f84815260209081902060408051606080820183526005870290930180548252825160a0810184526001808301546001600160a01b039081168352600280850154808316858b015262ffffff600160a01b82041685890152600160b81b9004900b9683019690965260038301549095166080820152828601526004015460ff1615159181019190915283529092019101611a80565b505050509050919050565b600b54604080516352c7420d60e01b815290515f92839260809284926001600160a01b0316916352c7420d91600480830192869291908290030181865afa158015611b75573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611b9c9190810190614a6f565b600354604080516001600160a01b0392831660208201528983169181019190915290871660608201529091505f90608001610cc8565b6040805160a0810182525f808252602082018190529181018290526060810182905260808101919091525f611c0d60408401602085016146b6565b6001600160a01b0316611c2360208501856146b6565b6001600160a01b031610611c4a576040516305188ae360e11b815260040160405180910390fd5b5f611c5d610120850161010086016146b6565b6001600160a01b031603611c845760405163d92e233d60e01b815260040160405180910390fd5b5f611c97610160850161014086016146b6565b6001600160a01b031603611cbe5760405163d92e233d60e01b815260040160405180910390fd5b60c0830135158015611cd2575060e0830135155b15611cf05760405163019e6dc160e11b815260040160405180910390fd5b611d0261018084016101608501614b2c565b8015611d3457505f611d18610180850185614b47565b611d299060408101906020016146b6565b6001600160a01b0316145b15611d525760405163d92e233d60e01b815260040160405180910390fd5b335f908152600d60205260409020546001600160a01b031680611da657611d7c8460800135613b93565b335f908152600d6020526040902080546001600160a01b0319166001600160a01b03831617905590505b6040805160a0810190915280611dbf60208701876146b6565b6001600160a01b03168152602001856020016020810190611de091906146b6565b6001600160a01b03168152628000006020820152604090810190611e0a9060608801908801614b65565b60020b81526001600160a01b03831660209091018190526040516319c0fa6160e31b81529194509063ce07d30890611e46908690600401614e22565b5f604051808303815f87803b158015611e5d575f80fd5b505af1158015611e6f573d5f803e3d5ffd5b50505050611e8a8385606001602081019061125b91906146b6565b5f611e9b60c0860160a08701614afb565b62ffffff161115611f11576001600160a01b038116635275965184611ec660c0880160a08901614afb565b6040518363ffffffff1660e01b8152600401611ee3929190614e30565b5f604051808303815f87803b158015611efa575f80fd5b505af1158015611f0c573d5f803e3d5ffd5b505050505b5f611f2f611f2260208701876146b6565b8660c00135600654613693565b90506120558482611f4861012089016101008a016146b6565b611f566101208a018a614bea565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525050505060c08a013560e08b0135611fa56101608d016101408e016146b6565b611fb76101808e016101608f01614b2c565b611fc56101808f018f614b47565b611fce90614c81565b8e806101a00190611fdf9190614d11565b808060200260200160405190810160405280939291908181526020015f905b8282101561203b576040805180820182529080840287019060029083908390808284375f9201919091525050508152600190910190602001611ffe565b50505050508f6101c0018036038101906113aa9190614d57565b92506113cd61206760208701876146b6565b8660c001356006546139cd565b6040805160a0810182525f808252602082018190529181018290526060810182905260808101919091525f6120af60408401602085016146b6565b6001600160a01b03166120c560208501856146b6565b6001600160a01b0316106120ec576040516305188ae360e11b815260040160405180910390fd5b5f6120ff610120850161010086016146b6565b6001600160a01b0316036121265760405163d92e233d60e01b815260040160405180910390fd5b5f612139610160850161014086016146b6565b6001600160a01b0316036121605760405163d92e233d60e01b815260040160405180910390fd5b60c0830135158015612174575060e0830135155b156121925760405163019e6dc160e11b815260040160405180910390fd5b6121a461018084016101608501614b2c565b80156121d657505f6121ba610180850185614b47565b6121cb9060408101906020016146b6565b6001600160a01b0316145b156121f45760405163d92e233d60e01b815260040160405180910390fd5b335f908152600f60205260409020546001600160a01b0316806122485761221e8460800135613c89565b335f908152600f6020526040902080546001600160a01b0319166001600160a01b03831617905590505b6040805160a081019091528061226160208701876146b6565b6001600160a01b0316815260200185602001602081019061228291906146b6565b6001600160a01b031681526280000060208201526040908101906122ac9060608801908801614b65565b60020b81526001600160a01b03831660209091018190526040516319c0fa6160e31b81529194509063ce07d308906122e8908690600401614e22565b5f604051808303815f87803b1580156122ff575f80fd5b505af1158015612311573d5f803e3d5ffd5b50505050611e8a8385606001602081019061232c91906146b6565b613d2c565b5f61233b816130fc565b6001600160a01b0382166123625760405163d92e233d60e01b815260040160405180910390fd5b600980546001600160a01b038481166001600160a01b0319831681179093556040519116919082907f0bd9ce7374b6692c2850de34837b13648cbbb91115800606057fc28c60243b58905f90a3505050565b5f6123be816130fc565b6001600160a01b0382166123e55760405163d92e233d60e01b815260040160405180910390fd5b600b80546001600160a01b038481166001600160a01b0319831681179093556040519116919082907f0bd9ce7374b6692c2850de34837b13648cbbb91115800606057fc28c60243b58905f90a3505050565b6001600160a01b0381165f908152601260209081526040808320805482518185028101850190935280835260609493849084015b82821015612508575f84815260209081902060408051606080820183526005870290930180548252825160a0810184526001808301546001600160a01b039081168352600280850154808316858b015262ffffff600160a01b82041685890152600160b81b9004900b9683019690965260038301549095166080820152828601526004015460ff161515918101919091528352909201910161246b565b505050509050805167ffffffffffffffff811115612528576125286149b6565b604051908082528060200260200182016040528015612551578160200160208202803683370190505b5091505f5b81518110156125a15781818151811061257157612571614e50565b60200260200101515f015183828151811061258e5761258e614e50565b6020908102919091010152600101612556565b5050919050565b5f6125b2816130fc565b6001600160a01b0382166125d95760405163d92e233d60e01b815260040160405180910390fd5b600c80546001600160a01b038481166001600160a01b0319831681179093556040519116919082907fdeff25089442120c3e5d2fc7072cb58c8287d65c1fdb6501f281923beb331f3d905f90a3505050565b5f82815260208190526040902060010154612645816130fc565b610e198383613b12565b5f612659816130fc565b60078290556040518281527faa6fbd4ea51a023802ca95b28849c3292d916de40795840276e000614241fd339060200161140f565b6040805160a0810182525f808252602082018190529181018290526060810182905260808101919091525f6126c960408401602085016146b6565b6001600160a01b03166126df60208501856146b6565b6001600160a01b031610612706576040516305188ae360e11b815260040160405180910390fd5b5f612719610180850161016086016146b6565b6001600160a01b0316036127405760405163d92e233d60e01b815260040160405180910390fd5b5f6127536101c085016101a086016146b6565b6001600160a01b03160361277a5760405163d92e233d60e01b815260040160405180910390fd5b6101208301351580156127905750610140830135155b156127ae5760405163019e6dc160e11b815260040160405180910390fd5b620186a06127c260e0850160c08601614afb565b62ffffff1611156127e65760405163162908e360e11b815260040160405180910390fd5b6127106127f960e0850160c08601614afb565b62ffffff16101561281d5760405163162908e360e11b815260040160405180910390fd5b61282f6101e084016101c08501614b2c565b801561286157505f6128456101e0850185614b47565b6128569060408101906020016146b6565b6001600160a01b0316145b1561287f5760405163d92e233d60e01b815260040160405180910390fd5b5f80612893610340860161032087016146b6565b6001600160a01b0316036128a757336128b9565b6128b9610340850161032086016146b6565b6001600160a01b038082165f9081526010602052604090205491925016806129cd576128e9856080013583613f8e565b9050613fff811660c0808316811461291457604051632a96f9e160e21b815260040160405180910390fd5b6001600160a01b038481165f908152601060205260409081902080546001600160a01b03191686841690811790915560135491516350d2994b60e11b8152600481019190915291169063a1a53296906024015f604051808303815f87803b15801561297d575f80fd5b505af115801561298f573d5f803e3d5ffd5b50506040516001600160a01b038087169350871691507f8fcacf3ee9b00512c4a7bf8c3c70ebf3f8d5a2312f59e74f2451ab3c475706a5905f90a350505b6040805160a08101909152806129e660208801886146b6565b6001600160a01b03168152602001866020016020810190612a0791906146b6565b6001600160a01b03168152628000006020820152604090810190612a319060608901908901614b65565b60020b81526001600160a01b0383166020909101819052909450639d32af2885612a6160c0890160a08a01614afb565b612a7160e08a0160c08b01614afb565b612a826101008b0160e08c01614b80565b612a946101208c016101008d01614afb565b6040518663ffffffff1660e01b8152600401612ab4959493929190614ba3565b5f604051808303815f87803b158015612acb575f80fd5b505af1158015612add573d5f803e3d5ffd5b50505050612af88486606001602081019061232c91906146b6565b505f9050612b1a612b0c60208601866146b6565b856101200135600754613693565b9050612c3f8382612b33610180880161016089016146b6565b612b41610180890189614bea565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152505050506101208901356101408a0135612b926101c08c016101a08d016146b6565b612ba46101e08d016101c08e01614b2c565b612bb26101e08e018e614b47565b612bbb90614c81565b612bc96102008f018f614d11565b808060200260200160405190810160405280939291908181526020015f905b82821015612c25576040805180820182529080840287019060029083908390808284375f9201919091525050508152600190910190602001612be8565b50505050508e610220018036038101906113aa9190614d57565b9150612c5f612c5160208601866146b6565b8561012001356007546139cd565b50915091565b6040805160a0810182525f808252602082018190529181018290526060810182905260808101919091525f612ca060408401602085016146b6565b6001600160a01b0316612cb660208501856146b6565b6001600160a01b031610612cdd576040516305188ae360e11b815260040160405180910390fd5b5f612cef610100850160e086016146b6565b6001600160a01b031603612d165760405163d92e233d60e01b815260040160405180910390fd5b5f612d29610140850161012086016146b6565b6001600160a01b031603612d505760405163d92e233d60e01b815260040160405180910390fd5b60a0830135158015612d64575060c0830135155b15612d825760405163019e6dc160e11b815260040160405180910390fd5b62800000612d966060850160408601614afb565b62ffffff1603612db95760405163dfe6158b60e01b815260040160405180910390fd5b612dcb61016084016101408501614b2c565b8015612dfd57505f612de1610160850185614b47565b612df29060408101906020016146b6565b6001600160a01b0316145b15612e1b5760405163d92e233d60e01b815260040160405180910390fd5b6040805160a0810190915280612e3460208601866146b6565b6001600160a01b03168152602001846020016020810190612e5591906146b6565b6001600160a01b03168152602001612e736060860160408701614afb565b62ffffff168152602001612e8d6080860160608701614b65565b60020b81526004546001600160a01b03166020909101529150612ec082612eba60a08601608087016146b6565b5f613340565b5f612ede612ed160208601866146b6565b8560a00135600554613693565b90506130008382612ef6610100880160e089016146b6565b612f04610100890189614bea565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525050505060a089013560c08a0135612f536101408c016101208d016146b6565b612f656101608d016101408e01614b2c565b612f736101608e018e614b47565b612f7c90614c81565b612f8a6101808f018f614d11565b808060200260200160405190810160405280939291908181526020015f905b82821015612fe6576040805180820182529080840287019060029083908390808284375f9201919091525050508152600190910190602001612fa9565b50505050508e6101a0018036038101906113aa9190614d57565b9150612c5f61301260208601866146b6565b8560a001356005546139cd565b5f80613fff851694505f848460405160200161303c929190614e06565b60405160208183030381529060405290505f805b620272bc8110156130a5576130668982856140a8565b9150613fff82166001600160a01b03891614801561308c57506001600160a01b0382163b155b1561309d5790935091506130f39050565b600101613050565b5060405162461bcd60e51b815260206004820152601e60248201527f486f6f6b4d696e65723a20636f756c64206e6f742066696e642073616c74000060448201526064015b60405180910390fd5b94509492505050565b6131068133614121565b50565b5f80808061311f610340860161032087016146b6565b6001600160a01b0316036131335733613145565b613145610340850161032086016146b6565b6001600160a01b038082165f908152600e602052604090205416935090508261325b57613176846080013582614177565b9250613fff83166120c080851681146131a257604051632a96f9e160e21b815260040160405180910390fd5b6001600160a01b038381165f908152600e60205260409081902080546001600160a01b03191688841690811790915560135491516350d2994b60e11b8152600481019190915291169063a1a53296906024015f604051808303815f87803b15801561320b575f80fd5b505af115801561321d573d5f803e3d5ffd5b50506040516001600160a01b038089169350861691507f8fcacf3ee9b00512c4a7bf8c3c70ebf3f8d5a2312f59e74f2451ab3c475706a5905f90a350505b5f61329282608087013561327260208901896146b6565b61328260408a0160208b016146b6565b6105c960608b0160408c01614b65565b5f818152601460205260409020549091506001600160a01b031680158015906132c457506001600160a01b0381163314155b156132e25760405163de14f86560e01b815260040160405180910390fd5b6001600160a01b03811615613338575f8281526014602052604080822080546001600160a01b03191690555183917fa43c93c12a241464ace3decc5c835ed1c440a3a31afad7747cbec8ca9d279a3791a2600193505b505050915091565b60035460405163313b65df60e11b81526001600160a01b0390911690636276cbbe90613372908690869060040161475c565b6020604051808303815f875af115801561338e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906133b29190614e64565b506002546001600160a01b031663d6b25f0b6133cf8560a0902090565b856040518363ffffffff1660e01b81526004016133ed929190614e7f565b5f604051808303815f87803b158015613404575f80fd5b505af1158015613416573d5f803e3d5ffd5b505050505f6134268460a0902090565b5f8181526011602090815260408083208054336001600160a01b03199182168117909255818552601284528285208351606080820186528882528187018d81528b1515838801908152845460018181018755958b529989902093516005909a02909301988955518051938901805486166001600160a01b0395861617905596870151600289018054978901519289015191851676ffffffffffffffffffffffffffffffffffffffffffffff1990981697909717600160a01b62ffffff938416021762ffffff60b81b1916600160b81b9290911691909102179094556080948501516003870180549093169082161790915591516004909401805460ff191694151594909417909355908701519293509190911690827fb29812400276d077334c388dc76eb945746169469439cda860c7787bd3856a018561356b578760400151613570565b628000005b60405162ffffff909116815260200160405180910390a46040518215158152819033907fc223bf2c7087f12483b2d44ae651b6dc077e37d639852808d9f9a9150a704ac09060200160405180910390a36001546001600160a01b0316636a90700b6135dc8660a0902090565b6040516001600160e01b031960e084901b1681526004810191909152600160248201526044015f604051808303815f87803b158015613619575f80fd5b505af115801561362b573d5f803e3d5ffd5b50506001546080870151604051632acfe5f560e11b81526001600160a01b0391821660048201529116925063559fcbea91506024015f604051808303815f87803b158015613677575f80fd5b505af1158015613689573d5f803e3d5ffd5b5050505050505050565b5f816001600160a01b0385166136b3576136ad8482614ea7565b90508391505b803410156136d457604051631a84bc4160e21b815260040160405180910390fd5b8215613726578260085f8282546136eb9190614ea7565b909155505060405183815233907fdc1278cd3aa93a00427622f7f3aa06ab8bd89ddcdca97c4c9978ce404ddb1d2d9060200160405180910390a25b509392505050565b5f6137428c5f01518d602001518a8a61425b565b5f7f000000000000000000000000c920e83e5d91758baf1b138fbce893df7a3f4dd06001600160a01b0316632f6b4b0e8e8d8d6040518463ffffffff1660e01b815260040161379393929190614ee8565b602060405180830381865afa1580156137ae573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906137d29190614f16565b90506137e88d5f01518e602001518b8b856142a7565b82516001600160a01b031661389a577f000000000000000000000000c920e83e5d91758baf1b138fbce893df7a3f4dd06001600160a01b0316637b47a0ae8d8f8e8e8e8e8e8c8c6040518a63ffffffff1660e01b8152600401613852989796959493929190615010565b60206040518083038185885af115801561386e573d5f803e3d5ffd5b50505050506040513d601f19601f820116820180604052508101906138939190614f16565b915061399c565b85156138fd577f000000000000000000000000c920e83e5d91758baf1b138fbce893df7a3f4dd06001600160a01b0316638f1c19c98d8f8e8e8e8e8e8d8d8d6040518b63ffffffff1660e01b81526004016138529998979695949392919061508e565b7f000000000000000000000000c920e83e5d91758baf1b138fbce893df7a3f4dd06001600160a01b0316637b47a0ae8d8f8e8e8e8e8e8c8c6040518a63ffffffff1660e01b8152600401613958989796959493929190615010565b60206040518083038185885af1158015613974573d5f803e3d5ffd5b50505050506040513d601f19601f820116820180604052508101906139999190614f16565b91505b806001600160a01b0316826001600160a01b0316146139bd576139bd61518f565b509b9a5050505050505050505050565b806001600160a01b0384166139e9576139e68382614ea7565b90505b5f6139f482346151a3565b90508015613a64576040515f90339083908381818185875af1925050503d805f8114613a3b576040519150601f19603f3d011682016040523d82523d5f602084013e613a40565b606091505b5050905080613a6257604051633fdf366b60e11b815260040160405180910390fd5b505b5050505050565b5f828152602081815260408083206001600160a01b038516845290915281205460ff16613b0b575f838152602081815260408083206001600160a01b03861684529091529020805460ff19166001179055613ac33390565b6001600160a01b0316826001600160a01b0316847f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a4506001610b30565b505f610b30565b5f828152602081815260408083206001600160a01b038516845290915281205460ff1615613b0b575f838152602081815260408083206001600160a01b0386168085529252808320805460ff1916905551339286917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a4506001610b30565b5f805f60095f9054906101000a90046001600160a01b03166001600160a01b03166352c7420d6040518163ffffffff1660e01b81526004015f60405180830381865afa158015613be5573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052613c0c9190810190614a6f565b600354600154604080516001600160a01b039384166020820152929091169082015233606082015230608082015260a0015b60408051601f1981840301815290829052613c5c9291602001614e06565b6040516020818303038152906040529050838151602083015ff59150813b613c82575f80fd5b5092915050565b5f805f600b5f9054906101000a90046001600160a01b03166001600160a01b03166352c7420d6040518163ffffffff1660e01b81526004015f60405180830381865afa158015613cdb573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052613d029190810190614a6f565b600354604080516001600160a01b0390921660208301523390820152306060820152608001613c3e565b60035460405163313b65df60e11b81526001600160a01b0390911690636276cbbe90613d5e908590859060040161475c565b6020604051808303815f875af1158015613d7a573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613d9e9190614e64565b506002546001600160a01b031663d6b25f0b613dbb8460a0902090565b846040518363ffffffff1660e01b8152600401613dd9929190614e7f565b5f604051808303815f87803b158015613df0575f80fd5b505af1158015613e02573d5f803e3d5ffd5b505050505f613e128360a0902090565b5f8181526011602090815260408083208054336001600160a01b03199182168117909255818552601284528285208351606080820186528882528187018c8152600183880181815285548083018755958b529989902093516005909502909301938455518051928401805486166001600160a01b0394851617905580880151600285018054838a01519484015192861676ffffffffffffffffffffffffffffffffffffffffffffff1990911617600160a01b62ffffff958616021762ffffff60b81b1916600160b81b9490921693909302179091556080908101516003840180549095169083161790935595516004909101805460ff1916911515919091179055880151915162800000815294955092169284917fb29812400276d077334c388dc76eb945746169469439cda860c7787bd3856a01910160405180910390a460405160018152819033907fc223bf2c7087f12483b2d44ae651b6dc077e37d639852808d9f9a9150a704ac09060200160405180910390a3505050565b6013545f906001600160a01b0316613fb95760405163cc1be59d60e01b815260040160405180910390fd5b5f80600c5f9054906101000a90046001600160a01b03166001600160a01b03166352c7420d6040518163ffffffff1660e01b81526004015f60405180830381865afa15801561400a573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526140319190810190614a6f565b600354601354604080516001600160a01b03938416602082015291831690820152908616606082015230608082015260a0015b60408051601f19818403018152908290526140829291602001614e06565b6040516020818303038152906040529050848151602083015ff59150813b613726575f80fd5b8051602080830191909120604080517fff0000000000000000000000000000000000000000000000000000000000000081850152606087901b6bffffffffffffffffffffffff191660218201526035810186905260558082019390935281518082039093018352607501905280519101205b9392505050565b5f828152602081815260408083206001600160a01b038516845290915290205460ff166141735760405163e2517d3f60e01b81526001600160a01b0382166004820152602481018390526044016130ea565b5050565b6013545f906001600160a01b03166141a25760405163cc1be59d60e01b815260040160405180910390fd5b5f80600a5f9054906101000a90046001600160a01b03166001600160a01b03166352c7420d6040518163ffffffff1660e01b81526004015f60405180830381865afa1580156141f3573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261421a9190810190614a6f565b600354600154601354604080516001600160a01b039485166020820152928416908301528216606082015290861660808201523060a082015260c001614064565b6001600160a01b0384161515801561427257505f82115b1561428c5761428c6001600160a01b0385163330856142f1565b8015610e1957610e196001600160a01b0384163330846142f1565b6001600160a01b038516151580156142be57505f83115b156142d7576142d76001600160a01b038616828561436d565b8115613a6457613a646001600160a01b038516828461436d565b6040516001600160a01b038481166024830152838116604483015260648201839052610e199186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff838183161783525050505061440d565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1663095ea7b360e01b1790526143d3848261446e565b610e19576040516001600160a01b0384811660248301525f604483015261440791869182169063095ea7b390606401614326565b610e1984825b5f6144216001600160a01b0384168361450f565b905080515f1415801561444557508080602001905181019061444391906151b6565b155b1561154b57604051635274afe760e01b81526001600160a01b03841660048201526024016130ea565b5f805f846001600160a01b03168460405161448991906151d1565b5f604051808303815f865af19150503d805f81146144c2576040519150601f19603f3d011682016040523d82523d5f602084013e6144c7565b606091505b50915091508180156144f15750805115806144f15750808060200190518101906144f191906151b6565b801561450657505f856001600160a01b03163b115b95945050505050565b606061411a83835f845f80856001600160a01b0316848660405161453391906151d1565b5f6040518083038185875af1925050503d805f811461456d576040519150601f19603f3d011682016040523d82523d5f602084013e614572565b606091505b509150915061458286838361458c565b9695505050505050565b6060826145a15761459c826145e8565b61411a565b81511580156145b857506001600160a01b0384163b155b156145e157604051639996b31560e01b81526001600160a01b03851660048201526024016130ea565b508061411a565b8051156145f85780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b5f60208284031215614621575f80fd5b81356001600160e01b03198116811461411a575f80fd5b6001600160a01b0381168114613106575f80fd5b803561465781614638565b919050565b5f806040838503121561466d575f80fd5b82359150602083013561467f81614638565b809150509250929050565b5f806040838503121561469b575f80fd5b82356146a681614638565b9150602083013561467f81614638565b5f602082840312156146c6575f80fd5b813561411a81614638565b5f602082840312156146e1575f80fd5b813567ffffffffffffffff8111156146f7575f80fd5b8201610340818503121561411a575f80fd5b6001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b60c0810161476a8285614709565b6001600160a01b03831660a08301529392505050565b5f60208284031215614790575f80fd5b5035919050565b5f805f606084860312156147a9575f80fd5b83356147b481614638565b925060208401356147c481614638565b915060408401356147d481614638565b809150509250925092565b8060020b8114613106575f80fd5b8035614657816147df565b5f805f805f60a0868803121561480c575f80fd5b853561481781614638565b945060208601359350604086013561482e81614638565b9250606086013561483e81614638565b9150608086013561484e816147df565b809150509295509295909350565b5f806040838503121561486d575f80fd5b823561487881614638565b946020939093013593505050565b83815260e0810161489a6020830185614709565b82151560c0830152949350505050565b602080825282518282018190525f918401906040840190835b818110156149045783518051845260208101516148e36020860182614709565b5060400151151560c08401526020939093019260e0909201916001016148c3565b509095945050505050565b5f6020828403121561491f575f80fd5b813567ffffffffffffffff811115614935575f80fd5b82016102c0818503121561411a575f80fd5b602080825282518282018190525f918401906040840190835b81811015614904578351835260209384019390920191600101614960565b5f6020828403121561498e575f80fd5b813567ffffffffffffffff8111156149a4575f80fd5b82016102a0818503121561411a575f80fd5b634e487b7160e01b5f52604160045260245ffd5b60405160c0810167ffffffffffffffff811182821017156149ed576149ed6149b6565b60405290565b604051610100810167ffffffffffffffff811182821017156149ed576149ed6149b6565b604051601f8201601f1916810167ffffffffffffffff81118282101715614a4057614a406149b6565b604052919050565b5f67ffffffffffffffff821115614a6157614a616149b6565b50601f01601f191660200190565b5f60208284031215614a7f575f80fd5b815167ffffffffffffffff811115614a95575f80fd5b8201601f81018413614aa5575f80fd5b8051614ab8614ab382614a48565b614a17565b818152856020838501011115614acc575f80fd5b8160208401602083015e5f91810160200191909152949350505050565b803562ffffff81168114614657575f80fd5b5f60208284031215614b0b575f80fd5b61411a82614ae9565b8015158114613106575f80fd5b803561465781614b14565b5f60208284031215614b3c575f80fd5b813561411a81614b14565b5f823560be19833603018112614b5b575f80fd5b9190910192915050565b5f60208284031215614b75575f80fd5b813561411a816147df565b5f60208284031215614b90575f80fd5b813563ffffffff8116811461411a575f80fd5b6101208101614bb28288614709565b62ffffff861660a083015262ffffff851660c083015263ffffffff841660e083015262ffffff83166101008301529695505050505050565b5f808335601e19843603018112614bff575f80fd5b83018035915067ffffffffffffffff821115614c19575f80fd5b602001915036819003821315614c2d575f80fd5b9250929050565b5f82601f830112614c43575f80fd5b8135614c51614ab382614a48565b818152846020838601011115614c65575f80fd5b816020850160208301375f918101602001919091529392505050565b5f60c08236031215614c91575f80fd5b614c996149ca565b823560048110614ca7575f80fd5b8152614cb56020840161464c565b6020820152604083013567ffffffffffffffff811115614cd3575f80fd5b614cdf36828601614c34565b604083015250614cf160608401614b21565b60608201526080838101359082015260a092830135928101929092525090565b5f808335601e19843603018112614d26575f80fd5b83018035915067ffffffffffffffff821115614d40575f80fd5b6020019150600681901b3603821315614c2d575f80fd5b5f610100828403128015614d69575f80fd5b50614d726149f3565b8235614d7d81614638565b8152614d8b602084016147ed565b6020820152614d9c60408401614ae9565b6040820152614dad60608401614ae9565b6060820152614dbe60808401614ae9565b608082015260a0838101359082015260c08084013590820152614de360e08401614b21565b60e08201529392505050565b5f81518060208401855e5f93019283525090919050565b5f614e1a614e148386614def565b84614def565b949350505050565b60a08101610b308284614709565b60c08101614e3e8285614709565b62ffffff831660a08301529392505050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215614e74575f80fd5b815161411a816147df565b82815260c0810161411a6020830184614709565b634e487b7160e01b5f52601160045260245ffd5b80820180821115610b3057610b30614e93565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b614ef28185614709565b6001600160a01b03831660a082015260e060c08201525f61450660e0830184614eba565b5f60208284031215614f26575f80fd5b815161411a81614638565b5f8151808452602084019350602083015f5b82811015614f88578151865f5b6002811015614f6f578251825260209283019290910190600101614f50565b5050506040959095019460209190910190600101614f43565b5093949350505050565b6001600160a01b038151168252602081015160020b602083015262ffffff60408201511660408301526060810151614fd1606084018262ffffff169052565b506080810151614fe8608084018262ffffff169052565b5060a081015160a083015260c081015160c083015260e081015161154b60e084018215159052565b61501a818a614709565b6001600160a01b03881660a082015261026060c08201525f615040610260830189614eba565b8760e0840152866101008401526001600160a01b0386166101208401528281036101408401526150708186614f31565b915050615081610160830184614f92565b9998505050505050505050565b615098818b614709565b6001600160a01b03891660a082015261028060c08201525f6150be61028083018a614eba565b8860e0840152876101008401526001600160a01b03871661012084015282810361014084015285516004811061510257634e487b7160e01b5f52602160045260245ffd5b808252506001600160a01b036020870151166020820152604086015160c0604083015261513260c0830182614eba565b90506060870151615147606084018215159052565b506080870151608083015260a087015160a083015283810361016085015261516f8187614f31565b92505050615181610180830184614f92565b9a9950505050505050505050565b634e487b7160e01b5f52600160045260245ffd5b81810381811115610b3057610b30614e93565b5f602082840312156151c6575f80fd5b815161411a81614b14565b5f61411a8284614def56fea2646970667358221220448ddaa40a5536dd53573c5b0cbe7190da510fedbe720a6684183d3a2bab3bd064736f6c634300081a0033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
0000000000000000000000004483915019f259814b410a12a9f8633e5d85208f00000000000000000000000029c1ebd856769fb4a3e8d30f609196baaf3c10c0000000000000000000000000c920e83e5d91758baf1b138fbce893df7a3f4dd0000000000000000000000000d11dd2cf14593e1d4736a054f6d9c726dac81a210000000000000000000000001fd1be7495fe49eb404a3b6457331fac3811df2c000000000000000000000000daebe16c001d7368409c654bf3027082719db2ef00000000000000000000000070be410728e7b4b4f53149ed02ddc97c4c0197cd
-----Decoded View---------------
Arg [0] : _limitOrderLens (address): 0x4483915019F259814b410a12a9f8633e5d85208f
Arg [1] : _limitOrderHook (address): 0x29c1ebD856769fB4A3e8D30f609196baAF3c10C0
Arg [2] : _multiPositionFactory (address): 0xC920e83E5d91758bAF1B138fbcE893dF7a3F4DD0
Arg [3] : _dynamicFeeLimitOrderRegistry (address): 0xD11dd2cf14593e1D4736a054f6d9c726DaC81a21
Arg [4] : _volatilityDynamicLimitOrderRegistry (address): 0x1fd1BE7495fE49Eb404A3b6457331FAC3811DF2C
Arg [5] : _dynamicFeeRegistry (address): 0xDAebE16c001D7368409c654BF3027082719DB2EF
Arg [6] : _volatilityDynamicFeeRegistry (address): 0x70be410728e7b4B4f53149ED02ddc97C4c0197Cd
-----Encoded View---------------
7 Constructor Arguments found :
Arg [0] : 0000000000000000000000004483915019f259814b410a12a9f8633e5d85208f
Arg [1] : 00000000000000000000000029c1ebd856769fb4a3e8d30f609196baaf3c10c0
Arg [2] : 000000000000000000000000c920e83e5d91758baf1b138fbce893df7a3f4dd0
Arg [3] : 000000000000000000000000d11dd2cf14593e1d4736a054f6d9c726dac81a21
Arg [4] : 0000000000000000000000001fd1be7495fe49eb404a3b6457331fac3811df2c
Arg [5] : 000000000000000000000000daebe16c001d7368409c654bf3027082719db2ef
Arg [6] : 00000000000000000000000070be410728e7b4b4f53149ed02ddc97c4c0197cd
Net Worth in USD
Net Worth in ETH
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.