Source Code
Overview
ETH Balance
0 ETH
ETH Value
$0.00| Transaction Hash |
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
Latest 1 internal transaction
Advanced mode:
| Parent Transaction Hash | Block | From | To | |||
|---|---|---|---|---|---|---|
| 38487628 | 7 hrs ago | Contract Creation | 0 ETH |
Cross-Chain Transactions
Loading...
Loading
Contract Name:
SuperchainLBPStrategyFactory
Compiler Version
v0.8.26+commit.8a97fa7a
Optimization Enabled:
Yes with 800 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IDistributionContract} from "ll/interfaces/IDistributionContract.sol";
import {MigratorParameters} from "ll/types/MigratorParameters.sol";
import {IPositionManager} from "@uniswap/v4-periphery/src/interfaces/IPositionManager.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {OrderBookFactory} from "../LimitOrderBook/OrderBookFactory.sol";
import {SuperchainLBPStrategy} from "./SuperchainLBPStrategy.sol";
import {SuperchainLBPStrategyDeployer} from "./SuperchainLBPStrategyDeployer.sol";
import {ISuperchainLBPStrategyFactory} from "./interfaces/ISuperchainLBPStrategyFactory.sol";
import {IMultiPositionManager} from "../MultiPositionManager/interfaces/IMultiPositionManager.sol";
import {IOrderBookFactory} from "../LimitOrderBook/interfaces/IOrderBookFactory.sol";
/// @title SuperchainLBPStrategyFactory
/// @notice Factory for deploying SuperchainLBPStrategy instances
/// @dev Implements IDistributionStrategy for integration with LiquidityLauncher
/// Uses reservation system for front-running protection
contract SuperchainLBPStrategyFactory is ISuperchainLBPStrategyFactory {
/// @dev Parameters for strategy deployment (used to avoid stack too deep)
struct DeployParams {
address token;
uint128 amount;
bytes32 salt;
bytes32 hookSalt;
}
struct StrategyConfig {
MigratorParameters migratorParams;
IMultiPositionManager.RebalanceParams rebalanceParams;
string mpmName;
bytes initializerParams;
bytes32 hookSalt;
address callOptionFactory;
address buyback;
}
/// @notice The OrderBookFactory used to deploy pools and MPMs
OrderBookFactory private immutable unilaunchOrderBookFactory;
/// @notice The PoolManager used for Uniswap V4 pools
IPoolManager public immutable poolManager;
/// @notice The deployer contract for SuperchainLBPStrategy (reduces factory bytecode size)
SuperchainLBPStrategyDeployer public immutable deployer;
/// @notice The canonical LiquidityLauncher that can call initializeDistribution
address public immutable liquidityLauncher;
/// @notice The canonical ContinuousClearingAuction initializer factory
address public immutable ccaFactory;
/// @notice Error thrown when configuration data is invalid
error InvalidConfigData();
/// @notice Error when caller is not the liquidity launcher
error UnauthorizedCaller();
/// @notice Event emitted when a pool is reserved for a strategy
event PoolReservedForStrategy(bytes32 indexed poolId, address indexed strategy, address indexed hookOwner);
/// @param _orderBookFactory The OrderBookFactory contract
/// @param _poolManager The Uniswap V4 PoolManager contract
/// @param _liquidityLauncher The canonical LiquidityLauncher authorized to call initializeDistribution
/// @param _ccaFactory The canonical ContinuousClearingAuction factory
constructor(OrderBookFactory _orderBookFactory, IPoolManager _poolManager, address _liquidityLauncher, address _ccaFactory) {
if (address(_orderBookFactory) == address(0)) revert InvalidConfigData();
if (address(_poolManager) == address(0)) revert InvalidConfigData();
if (_liquidityLauncher == address(0)) revert InvalidConfigData();
if (_ccaFactory == address(0)) revert InvalidConfigData();
unilaunchOrderBookFactory = _orderBookFactory;
poolManager = _poolManager;
liquidityLauncher = _liquidityLauncher;
ccaFactory = _ccaFactory;
// Deploy the deployer contract with this factory as authorized caller
deployer = new SuperchainLBPStrategyDeployer(address(this));
}
/// @notice Initializes a new distribution strategy
/// @dev Decodes configData and deploys a new SuperchainLBPStrategy
/// Uses reservation system for front-running protection
/// @param token The token being distributed
/// @param amount The amount of tokens being distributed
/// @param configData Encoded configuration containing:
/// - MigratorParameters (currency, fees, blocks, etc.)
/// - IMultiPositionManager.RebalanceParams (strategy configuration)
/// - string mpmName (name for MPM ERC20 token)
/// - bytes initializerParams (CCA initializer parameters)
/// @param salt Salt for deterministic deployment
/// @return distributionContract The deployed SuperchainLBPStrategy
function initializeDistribution(address token, uint256 amount, bytes calldata configData, bytes32 salt)
external
virtual
override
returns (IDistributionContract distributionContract)
{
if (msg.sender != liquidityLauncher) revert UnauthorizedCaller();
if (amount > type(uint128).max) revert InvalidConfigData();
distributionContract = IDistributionContract(_initializeStrategy(token, uint128(amount), configData, salt));
}
function _initializeStrategy(address token, uint128 amount, bytes calldata configData, bytes32 salt)
internal
returns (address strategyAddress)
{
StrategyConfig memory config = _decodeConfig(configData);
strategyAddress = _deployAndAuthorize(token, amount, salt, config);
emit SuperchainLBPStrategyCreated(strategyAddress, token, amount);
}
function _decodeConfig(bytes calldata configData) internal view returns (StrategyConfig memory config) {
(
MigratorParameters memory migratorParams,
IMultiPositionManager.RebalanceParams memory rebalanceParams,
string memory mpmName,
bytes memory initializerParams,
bytes32 hookSalt,
address callOptionFactory,
address buyback
) = abi.decode(
configData,
(MigratorParameters, IMultiPositionManager.RebalanceParams, string, bytes, bytes32, address, address)
);
migratorParams.initializerFactory = ccaFactory;
if (migratorParams.currency != address(0)) revert InvalidConfigData();
config = StrategyConfig({
migratorParams: migratorParams,
rebalanceParams: rebalanceParams,
mpmName: mpmName,
initializerParams: initializerParams,
hookSalt: hookSalt,
callOptionFactory: callOptionFactory,
buyback: buyback
});
}
function _deployAndAuthorize(
address token,
uint128 amount,
bytes32 salt,
StrategyConfig memory config
) internal returns (address strategyAddress) {
DeployParams memory params = DeployParams({token: token, amount: amount, salt: salt, hookSalt: config.hookSalt});
SuperchainLBPStrategy newStrategy = _deployStrategy(
params,
config.migratorParams,
config.rebalanceParams,
config.mpmName,
config.initializerParams,
config.callOptionFactory,
config.buyback
);
unilaunchOrderBookFactory.authorizeStrategy(address(newStrategy), true);
return address(newStrategy);
}
/// @dev Internal function to deploy strategy (avoids stack too deep)
function _deployStrategy(
DeployParams memory params,
MigratorParameters memory migratorParams,
IMultiPositionManager.RebalanceParams memory rebalanceParams,
string memory mpmName,
bytes memory initializerParams,
address callOptionFactory,
address buyback
) internal returns (SuperchainLBPStrategy) {
// Cache struct fields to reduce stack pressure
bytes32 _salt = params.salt;
bytes32 _hookSalt = params.hookSalt;
SuperchainLBPStrategy.StrategyInitParams memory init =
SuperchainLBPStrategy.StrategyInitParams({
token: params.token,
totalSupply: params.amount,
migratorParams: migratorParams,
initializerParams: initializerParams,
positionManager: IPositionManager(address(0)),
poolManager: poolManager,
orderBookFactory: unilaunchOrderBookFactory,
rebalanceParams: rebalanceParams,
mpmName: mpmName,
hookSalt: _hookSalt,
callerSalt: _salt,
callOptionFactory: callOptionFactory,
buyback: buyback
});
address deployed = deployer.deploy(_salt, init);
return SuperchainLBPStrategy(payable(deployed));
}
/// @inheritdoc ISuperchainLBPStrategyFactory
function orderBookFactory() external view override returns (IOrderBookFactory) {
return IOrderBookFactory(address(unilaunchOrderBookFactory));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IDistributionContract
/// @notice Interface for token distribution contracts.
interface IDistributionContract {
/// @notice Error thrown when the token address is invalid
error InvalidToken(address token);
/// @notice Error thrown when the amount received is invalid upon receiving tokens
/// @param expected The expected amount
/// @param received The received amount
error InvalidAmountReceived(uint256 expected, uint256 received);
/// @notice Notify a distribution contract that it has received the tokens to distribute
function onTokensReceived() external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title MigratorParameters
/// @notice Parameters for the AdvancedLBPStrategy contract
struct MigratorParameters {
uint64 migrationBlock; // block number when the migration can begin
address currency; // the currency that the token will be paired with in the v4 pool (currency that the initializer raised funds in)
uint24 poolLPFee; // the LP fee that the v4 pool will use
int24 poolTickSpacing; // the tick spacing that the v4 pool will use
uint24 tokenSplit; // the percentage of the total supply of the token that will be sent to the initializer, expressed in mps (1e7 = 100%)
address initializerFactory; // the initializer factory that will be used to create the initializer
address positionRecipient; // the address that will receive the position
uint64 sweepBlock; // the block number when the operator can sweep currency and tokens from the pool
address operator; // the address that is able to sweep currency and tokens from the pool
uint128 maxCurrencyAmountForLP; // the maximum amount of currency that can be used for LP
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PositionInfo} from "../libraries/PositionInfoLibrary.sol";
import {INotifier} from "./INotifier.sol";
import {IImmutableState} from "./IImmutableState.sol";
import {IERC721Permit_v4} from "./IERC721Permit_v4.sol";
import {IEIP712_v4} from "./IEIP712_v4.sol";
import {IMulticall_v4} from "./IMulticall_v4.sol";
import {IPoolInitializer_v4} from "./IPoolInitializer_v4.sol";
import {IUnorderedNonce} from "./IUnorderedNonce.sol";
import {IPermit2Forwarder} from "./IPermit2Forwarder.sol";
/// @title IPositionManager
/// @notice Interface for the PositionManager contract
interface IPositionManager is
INotifier,
IImmutableState,
IERC721Permit_v4,
IEIP712_v4,
IMulticall_v4,
IPoolInitializer_v4,
IUnorderedNonce,
IPermit2Forwarder
{
/// @notice Thrown when the caller is not approved to modify a position
error NotApproved(address caller);
/// @notice Thrown when the block.timestamp exceeds the user-provided deadline
error DeadlinePassed(uint256 deadline);
/// @notice Thrown when calling transfer, subscribe, or unsubscribe when the PoolManager is unlocked.
/// @dev This is to prevent hooks from being able to trigger notifications at the same time the position is being modified.
error PoolManagerMustBeLocked();
/// @notice Unlocks Uniswap v4 PoolManager and batches actions for modifying liquidity
/// @dev This is the standard entrypoint for the PositionManager
/// @param unlockData is an encoding of actions, and parameters for those actions
/// @param deadline is the deadline for the batched actions to be executed
function modifyLiquidities(bytes calldata unlockData, uint256 deadline) external payable;
/// @notice Batches actions for modifying liquidity without unlocking v4 PoolManager
/// @dev This must be called by a contract that has already unlocked the v4 PoolManager
/// @param actions the actions to perform
/// @param params the parameters to provide for the actions
function modifyLiquiditiesWithoutUnlock(bytes calldata actions, bytes[] calldata params) external payable;
/// @notice Used to get the ID that will be used for the next minted liquidity position
/// @return uint256 The next token ID
function nextTokenId() external view returns (uint256);
/// @notice Returns the liquidity of a position
/// @param tokenId the ERC721 tokenId
/// @return liquidity the position's liquidity, as a liquidityAmount
/// @dev this value can be processed as an amount0 and amount1 by using the LiquidityAmounts library
function getPositionLiquidity(uint256 tokenId) external view returns (uint128 liquidity);
/// @notice Returns the pool key and position info of a position
/// @param tokenId the ERC721 tokenId
/// @return poolKey the pool key of the position
/// @return PositionInfo a uint256 packed value holding information about the position including the range (tickLower, tickUpper)
function getPoolAndPositionInfo(uint256 tokenId) external view returns (PoolKey memory, PositionInfo);
/// @notice Returns the position info of a position
/// @param tokenId the ERC721 tokenId
/// @return a uint256 packed value holding information about the position including the range (tickLower, tickUpper)
function positionInfo(uint256 tokenId) external view returns (PositionInfo);
}// 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: BUSL-1.1
pragma solidity ^0.8.24;
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {IERC20} from "@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 {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} 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 {RebalanceLogic} from "../MultiPositionManager/libraries/RebalanceLogic.sol";
import {IMultiPositionManager} from "../MultiPositionManager/interfaces/IMultiPositionManager.sol";
import {MultiPositionFactory} from "../MultiPositionManager/MultiPositionFactory.sol";
import {VolatilityDynamicFeeLimitOrderHook} from "./hooks/VolatilityDynamicFeeLimitOrderHook.sol";
import {VolatilityOracle} from "./libraries/VolatilityOracle.sol";
/// @title OrderBookFactory
/// @notice ETH-only pool factory for Unilaunch with singleton volatility hook
contract OrderBookFactory is AccessControl {
using CurrencyLibrary for Currency;
using PoolIdLibrary for PoolKey;
using SafeERC20 for IERC20;
bytes32 public constant HOOK_PARAM_MANAGER_ROLE = keccak256("HOOK_PARAM_MANAGER_ROLE");
error ZeroAddress();
error NotAuthorizedStrategy();
error TokenOrderingIncorrect();
error InvalidAmount();
error UnauthorizedInitializer();
struct VolatilityDynamicPoolParams {
Currency currency0;
Currency currency1;
int24 tickSpacing;
uint160 sqrtPriceX96;
uint256 deposit0Desired;
uint256 deposit1Desired;
address managerOwner;
string name;
address to;
uint256[2][] inMin;
IMultiPositionManager.RebalanceParams rebalanceParams;
}
IPoolManager public immutable poolManager;
LimitOrderManager public immutable limitOrderManager;
LimitOrderLens public immutable limitOrderLens;
MultiPositionFactory public immutable multiPositionFactory;
VolatilityDynamicFeeLimitOrderHook public immutable hook;
VolatilityOracle public immutable volatilityOracle;
mapping(address => bool) public authorizedStrategy;
uint24 public baseFee;
uint24 public surgeMultiplier;
uint32 public surgeDuration;
uint24 public initialMaxTicksPerBlock;
event StrategyAuthorized(address indexed strategy, bool allowed);
event PoolCreated(bytes32 indexed poolId, address indexed strategy, address indexed hook);
event HookParamsUpdated(uint24 baseFee, uint24 surgeMultiplier, uint32 surgeDuration, uint24 initialMaxTicksPerBlock);
constructor(
address admin,
IPoolManager _poolManager,
LimitOrderManager _limitOrderManager,
LimitOrderLens _limitOrderLens,
MultiPositionFactory _multiPositionFactory,
VolatilityOracle _volatilityOracle,
VolatilityDynamicFeeLimitOrderHook _hook,
uint24 _baseFee,
uint24 _surgeMultiplier,
uint32 _surgeDuration,
uint24 _initialMaxTicksPerBlock
) {
if (admin == address(0)) revert ZeroAddress();
if (address(_poolManager) == address(0)) revert ZeroAddress();
if (address(_limitOrderManager) == address(0)) revert ZeroAddress();
if (address(_limitOrderLens) == address(0)) revert ZeroAddress();
if (address(_multiPositionFactory) == address(0)) revert ZeroAddress();
if (address(_volatilityOracle) == address(0)) revert ZeroAddress();
if (address(_hook) == address(0)) revert ZeroAddress();
poolManager = _poolManager;
limitOrderManager = _limitOrderManager;
limitOrderLens = _limitOrderLens;
multiPositionFactory = _multiPositionFactory;
volatilityOracle = _volatilityOracle;
hook = _hook;
baseFee = _baseFee;
surgeMultiplier = _surgeMultiplier;
surgeDuration = _surgeDuration;
initialMaxTicksPerBlock = _initialMaxTicksPerBlock;
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_grantRole(HOOK_PARAM_MANAGER_ROLE, admin);
}
function authorizeStrategy(address strategy, bool allowed) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (strategy == address(0)) revert ZeroAddress();
authorizedStrategy[strategy] = allowed;
emit StrategyAuthorized(strategy, allowed);
}
function registerHookWithOracle() external onlyRole(DEFAULT_ADMIN_ROLE) {
volatilityOracle.addAuthorizedHook(address(hook));
}
function setHookParams(
uint24 _baseFee,
uint24 _surgeMultiplier,
uint32 _surgeDuration,
uint24 _initialMaxTicksPerBlock
) external onlyRole(HOOK_PARAM_MANAGER_ROLE) {
baseFee = _baseFee;
surgeMultiplier = _surgeMultiplier;
surgeDuration = _surgeDuration;
initialMaxTicksPerBlock = _initialMaxTicksPerBlock;
emit HookParamsUpdated(_baseFee, _surgeMultiplier, _surgeDuration, _initialMaxTicksPerBlock);
}
function updatePoolBaseFee(PoolKey calldata key, uint24 newBaseFee) external onlyRole(HOOK_PARAM_MANAGER_ROLE) {
hook.updateBaseFee(key, newBaseFee);
}
function updatePoolSurgeParams(PoolKey calldata key, uint24 multiplier, uint32 duration)
external
onlyRole(HOOK_PARAM_MANAGER_ROLE)
{
hook.updateSurgeParams(key, multiplier, duration);
}
function updatePoolOraclePolicy(
PoolKey calldata key,
uint24 minCap,
uint24 maxCap,
uint32 stepPpm,
uint32 budgetPpm,
uint32 decayWindow,
uint32 updateInterval
) external onlyRole(HOOK_PARAM_MANAGER_ROLE) {
hook.updateOraclePolicy(key, minCap, maxCap, stepPpm, budgetPpm, decayWindow, updateInterval);
}
function createVolatilityDynamicLimitOrderPoolWithManager(VolatilityDynamicPoolParams calldata params)
external
payable
returns (PoolKey memory poolKey, address mpm)
{
if (!authorizedStrategy[msg.sender]) revert NotAuthorizedStrategy();
if (Currency.unwrap(params.currency0) != address(0)) revert TokenOrderingIncorrect();
if (Currency.unwrap(params.currency1) == address(0)) revert TokenOrderingIncorrect();
if (params.tickSpacing != 60) revert TokenOrderingIncorrect();
if (params.managerOwner == address(0) || params.to == address(0)) revert ZeroAddress();
if (params.deposit0Desired == 0 && params.deposit1Desired == 0) revert InvalidAmount();
if (msg.value != params.deposit0Desired) revert InvalidAmount();
poolKey = PoolKey({
currency0: params.currency0,
currency1: params.currency1,
fee: LPFeeLibrary.DYNAMIC_FEE_FLAG,
tickSpacing: params.tickSpacing,
hooks: hook
});
hook.registerPool(poolKey, baseFee, surgeMultiplier, surgeDuration, initialMaxTicksPerBlock);
poolManager.initialize(poolKey, params.sqrtPriceX96);
limitOrderLens.addPoolId(poolKey.toId(), poolKey);
limitOrderManager.setWhitelistedPool(poolKey.toId(), true);
limitOrderManager.enableHook(address(hook));
_transferTokensFromUser(poolKey.currency1, params.deposit1Desired);
address futureMPM = multiPositionFactory.computeAddress(poolKey, params.managerOwner, params.name);
_approveTokenForMPM(poolKey.currency1, params.deposit1Desired, futureMPM);
mpm = multiPositionFactory.deployDepositAndRebalance{value: msg.value}(
poolKey,
params.managerOwner,
params.name,
params.deposit0Desired,
params.deposit1Desired,
params.to,
params.inMin,
params.rebalanceParams
);
emit PoolCreated(PoolId.unwrap(poolKey.toId()), msg.sender, address(hook));
}
function _transferTokensFromUser(Currency currency1, uint256 amount1) private {
if (amount1 == 0) return;
IERC20(Currency.unwrap(currency1)).safeTransferFrom(msg.sender, address(this), amount1);
}
function _approveTokenForMPM(Currency currency1, uint256 amount1, address mpm) private {
if (amount1 == 0) return;
IERC20(Currency.unwrap(currency1)).forceApprove(mpm, amount1);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {LBPStrategyBasic} from "./base/LBPStrategyBasic.sol";
import {MigratorParameters} from "ll/types/MigratorParameters.sol";
import {MigrationData} from "ll/types/MigrationData.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IPositionManager} from "@uniswap/v4-periphery/src/interfaces/IPositionManager.sol";
import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {OrderBookFactory} from "../LimitOrderBook/OrderBookFactory.sol";
import {IMultiPositionManager} from "../MultiPositionManager/interfaces/IMultiPositionManager.sol";
import {ISuperchainLBPStrategy} from "./interfaces/ISuperchainLBPStrategy.sol";
import {IOrderBookFactory} from "../LimitOrderBook/interfaces/IOrderBookFactory.sol";
import {BaseHook} from "@uniswap/v4-periphery/src/utils/BaseHook.sol";
import {CallOptionFactory} from "./CallOptionFactory.sol";
import {Buyback} from "./Buyback.sol";
/// @title SuperchainLBPStrategy
/// @notice Strategy to distribute tokens via CCA auction and migrate liquidity to MultiPositionManager
/// @dev Extends LBPStrategyBasic but overrides migration to use OrderBookFactory
contract SuperchainLBPStrategy is LBPStrategyBasic, ISuperchainLBPStrategy {
using CurrencyLibrary for Currency;
using SafeERC20 for IERC20;
struct StrategyInitParams {
address token;
uint128 totalSupply;
MigratorParameters migratorParams;
bytes initializerParams;
IPositionManager positionManager;
IPoolManager poolManager;
OrderBookFactory orderBookFactory;
IMultiPositionManager.RebalanceParams rebalanceParams;
string mpmName;
bytes32 hookSalt;
bytes32 callerSalt;
address callOptionFactory;
address buyback;
}
struct DepositParams {
Currency currency0;
Currency currency1;
uint256 deposit0Desired;
uint256 deposit1Desired;
uint256 ethValue;
}
/// @notice The OrderBookFactory used to deploy pool + MultiPositionManager
OrderBookFactory private immutable unilaunchOrderBookFactory;
/// @notice Rebalance parameters for the MPM strategy configuration
IMultiPositionManager.RebalanceParams public rebalanceParams;
/// @notice Name for the MPM token
string public mpmName;
/// @notice Pre-computed salt for hook deployment (used during lazy deployment)
bytes32 public hookSalt;
/// @notice Caller-unique salt from LiquidityLauncher (emitted with reservation)
bytes32 public callerSalt;
/// @notice Call option contract to set strike on migration
CallOptionFactory public immutable callOptionFactory;
/// @notice Buyback contract to set poolKey on migration
Buyback public immutable buyback;
/// @notice Deployed MultiPositionManager address (set during migration)
address public deployedMPM;
constructor(StrategyInitParams memory init)
LBPStrategyBasic(
init.token,
init.totalSupply,
init.migratorParams,
init.initializerParams,
init.positionManager,
init.poolManager
)
{
if (address(init.orderBookFactory) == address(0)) revert InvalidOrderBookFactory();
if (init.rebalanceParams.strategy == address(0)) revert InvalidStrategy();
if (init.callOptionFactory == address(0) || init.buyback == address(0)) revert InvalidOrderBookFactory();
unilaunchOrderBookFactory = init.orderBookFactory;
rebalanceParams = init.rebalanceParams;
mpmName = init.mpmName;
hookSalt = init.hookSalt;
callerSalt = init.callerSalt;
callOptionFactory = CallOptionFactory(payable(init.callOptionFactory));
buyback = Buyback(payable(init.buyback));
}
/// @dev Override to skip hook address validation
/// @notice Unilaunch uses OrderBookFactory for pool management
/// The strategy itself is not used as a hook for any pool
function validateHookAddress(BaseHook) internal pure virtual override {}
/// @inheritdoc ISuperchainLBPStrategy
function strategy() external view override returns (address) {
return rebalanceParams.strategy;
}
/// @inheritdoc ISuperchainLBPStrategy
function orderBookFactory() external view override returns (IOrderBookFactory) {
return IOrderBookFactory(address(unilaunchOrderBookFactory));
}
/// @inheritdoc ISuperchainLBPStrategy
function strategyData() external view override returns (bytes memory) {
return abi.encode(rebalanceParams);
}
/// @notice Overridden to prevent pool initialization (OrderBookFactory will initialize)
/// @dev Returns a PoolKey without initializing the pool
function _initializePool(MigrationData memory data) internal view override returns (PoolKey memory key) {
key = PoolKey({
currency0: _currency0(),
currency1: _currency1(),
fee: poolLPFee,
tickSpacing: poolTickSpacing,
hooks: IHooks(address(0)) // No hook needed - OrderBookFactory manages hooks
});
// Do NOT initialize pool here - OrderBookFactory will do it
return key;
}
/// @notice Overridden to skip position plan creation (not needed for OrderBookFactory)
function _createPositionPlan(MigrationData memory) internal pure override returns (bytes memory) {
// OrderBookFactory doesn't use position plans
return "";
}
/// @notice Overridden to call OrderBookFactory instead of V4 PositionManager
/// @dev This is the critical override that redirects migration to MultiPositionManager
function _transferAssetsAndExecutePlan(MigrationData memory data, bytes memory) internal override {
(PoolKey memory poolKey, address mpm) = _deployPoolAndMPM(data);
deployedMPM = mpm;
uint256 shares = IERC20(mpm).balanceOf(positionRecipient);
emit MPMDeployed(mpm, shares);
emit MigrationPoolCreated(poolKey, data.sqrtPriceX96, mpm);
callOptionFactory.setStrike(data.sqrtPriceX96);
buyback.setPoolKey(poolKey);
}
/// @notice Deploys pool and MPM via OrderBookFactory
/// @param data Migration data with amounts and price
/// @return poolKey The deployed pool key
/// @return mpm The deployed MultiPositionManager address
function _deployPoolAndMPM(MigrationData memory data) private returns (PoolKey memory poolKey, address mpm) {
(uint128 tokenAmount, uint128 currencyAmount) = _calculateTransferAmounts(data);
DepositParams memory depositParams = _buildDepositParams(tokenAmount, currencyAmount);
_approveTokens(depositParams);
(poolKey, mpm) = _callFactory(data, depositParams);
}
/// @notice Calculates transfer amounts
function _calculateTransferAmounts(MigrationData memory data)
private view returns (uint128 tokenAmount, uint128 currencyAmount)
{
// Transfer all available tokens (reserve or full range amount)
tokenAmount = reserveTokenAmount > data.fullRangeTokenAmount ? reserveTokenAmount : data.fullRangeTokenAmount;
// Transfer all currency intended for LP (full range amount plus leftover)
currencyAmount = data.fullRangeCurrencyAmount + data.leftoverCurrency;
}
/// @notice Prepares currencies and deposit amounts
function _buildDepositParams(uint128 tokenAmount, uint128 currencyAmount)
private
view
returns (DepositParams memory params)
{
address poolToken = _getPoolToken();
bool currencyIsToken0 = _currencyIsCurrency0();
params.currency0 = Currency.wrap(currencyIsToken0 ? currency : poolToken);
params.currency1 = Currency.wrap(currencyIsToken0 ? poolToken : currency);
params.deposit0Desired = currencyIsToken0 ? currencyAmount : tokenAmount;
params.deposit1Desired = currencyIsToken0 ? tokenAmount : currencyAmount;
params.ethValue = Currency.wrap(currency).isAddressZero() ? currencyAmount : 0;
}
/// @notice Approves tokens for OrderBookFactory
function _approveTokens(DepositParams memory params) private {
if (!params.currency0.isAddressZero()) {
IERC20(Currency.unwrap(params.currency0)).forceApprove(address(unilaunchOrderBookFactory), params.deposit0Desired);
}
if (!params.currency1.isAddressZero()) {
IERC20(Currency.unwrap(params.currency1)).forceApprove(address(unilaunchOrderBookFactory), params.deposit1Desired);
}
}
function _callFactory(MigrationData memory data, DepositParams memory params)
private
returns (PoolKey memory poolKey, address mpm)
{
uint256[2][] memory inMin = new uint256[2][](0);
OrderBookFactory.VolatilityDynamicPoolParams memory poolParams =
OrderBookFactory.VolatilityDynamicPoolParams({
currency0: params.currency0,
currency1: params.currency1,
tickSpacing: poolTickSpacing,
sqrtPriceX96: data.sqrtPriceX96,
deposit0Desired: params.deposit0Desired,
deposit1Desired: params.deposit1Desired,
managerOwner: positionRecipient,
name: mpmName,
to: positionRecipient,
inMin: inMin,
rebalanceParams: rebalanceParams
});
(poolKey, mpm) =
unilaunchOrderBookFactory.createVolatilityDynamicLimitOrderPoolWithManager{value: params.ethValue}(poolParams);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {SuperchainLBPStrategy} from "./SuperchainLBPStrategy.sol";
/// @title SuperchainLBPStrategyDeployer
/// @notice Deploys SuperchainLBPStrategy contracts with CREATE2
contract SuperchainLBPStrategyDeployer {
address public immutable authorizedFactory;
error UnauthorizedCaller();
constructor(address _authorizedFactory) {
authorizedFactory = _authorizedFactory;
}
function deploy(
bytes32 salt,
SuperchainLBPStrategy.StrategyInitParams memory init
) external returns (address) {
if (msg.sender != authorizedFactory) revert UnauthorizedCaller();
return address(
new SuperchainLBPStrategy{salt: salt}(init)
);
}
function computeAddress(
bytes32 salt,
SuperchainLBPStrategy.StrategyInitParams memory init
) external view returns (address predicted) {
bytes32 hash = keccak256(
abi.encodePacked(
type(SuperchainLBPStrategy).creationCode,
abi.encode(init)
)
);
predicted = address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), salt, hash)))));
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IDistributionStrategy} from "ll/interfaces/IDistributionStrategy.sol";
import {IOrderBookFactory} from "../../LimitOrderBook/interfaces/IOrderBookFactory.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
/// @title ISuperchainLBPStrategyFactory
/// @notice Factory for deploying SuperchainLBPStrategy instances
interface ISuperchainLBPStrategyFactory is IDistributionStrategy {
/// @notice Emitted when a new SuperchainLBPStrategy is created
/// @param strategy The address of the created strategy
/// @param token The token being distributed
/// @param amount The amount of tokens being distributed
event SuperchainLBPStrategyCreated(address indexed strategy, address indexed token, uint256 amount);
/// @notice Gets the OrderBookFactory used by this factory
/// @return The OrderBookFactory contract
function orderBookFactory() external view returns (IOrderBookFactory);
/// @notice Gets the PoolManager used by this factory
/// @return The PoolManager contract
function poolManager() external view returns (IPoolManager);
/// @notice Gets the authorized LiquidityLauncher
/// @return The LiquidityLauncher address
function liquidityLauncher() external view returns (address);
/// @notice Gets the canonical ContinuousClearingAuction factory
/// @return The CCA factory address
function ccaFactory() external view returns (address);
}/// 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; // Use full-range floor
}
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.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 dynamic limit order 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 computeDynamicLimitOrderHookAddress(
address hookOwner,
bytes32 salt
) external view returns (address hookAddr);
/// @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 dynamic 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 computeDynamicFeeHookAddress(
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);
function getDynamicLimitOrderHook(address hookOwner, bytes32 salt)
external
view
returns (address hookAddr, bool isDeployed);
function getVolatilityLimitOrderHook(address hookOwner, bytes32 salt)
external
view
returns (address hookAddr, bool isDeployed);
function getDynamicFeeHook(address hookOwner, bytes32 salt)
external
view
returns (address hookAddr, bool isDeployed);
function getVolatilityFeeHook(address hookOwner, bytes32 salt)
external
view
returns (address hookAddr, bool isDeployed);
/// @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;
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.24;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
/**
* @dev PositionInfo is a packed version of solidity structure.
* Using the packaged version saves gas and memory by not storing the structure fields in memory slots.
*
* Layout:
* 200 bits poolId | 24 bits tickUpper | 24 bits tickLower | 8 bits hasSubscriber
*
* Fields in the direction from the least significant bit:
*
* A flag to know if the tokenId is subscribed to an address
* uint8 hasSubscriber;
*
* The tickUpper of the position
* int24 tickUpper;
*
* The tickLower of the position
* int24 tickLower;
*
* The truncated poolId. Truncates a bytes32 value so the most signifcant (highest) 200 bits are used.
* bytes25 poolId;
*
* Note: If more bits are needed, hasSubscriber can be a single bit.
*
*/
type PositionInfo is uint256;
using PositionInfoLibrary for PositionInfo global;
library PositionInfoLibrary {
PositionInfo internal constant EMPTY_POSITION_INFO = PositionInfo.wrap(0);
uint256 internal constant MASK_UPPER_200_BITS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000;
uint256 internal constant MASK_8_BITS = 0xFF;
uint24 internal constant MASK_24_BITS = 0xFFFFFF;
uint256 internal constant SET_UNSUBSCRIBE = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00;
uint256 internal constant SET_SUBSCRIBE = 0x01;
uint8 internal constant TICK_LOWER_OFFSET = 8;
uint8 internal constant TICK_UPPER_OFFSET = 32;
/// @dev This poolId is NOT compatible with the poolId used in UniswapV4 core. It is truncated to 25 bytes, and just used to lookup PoolKey in the poolKeys mapping.
function poolId(PositionInfo info) internal pure returns (bytes25 _poolId) {
assembly ("memory-safe") {
_poolId := and(MASK_UPPER_200_BITS, info)
}
}
function tickLower(PositionInfo info) internal pure returns (int24 _tickLower) {
assembly ("memory-safe") {
_tickLower := signextend(2, shr(TICK_LOWER_OFFSET, info))
}
}
function tickUpper(PositionInfo info) internal pure returns (int24 _tickUpper) {
assembly ("memory-safe") {
_tickUpper := signextend(2, shr(TICK_UPPER_OFFSET, info))
}
}
function hasSubscriber(PositionInfo info) internal pure returns (bool _hasSubscriber) {
assembly ("memory-safe") {
_hasSubscriber := and(MASK_8_BITS, info)
}
}
/// @dev this does not actually set any storage
function setSubscribe(PositionInfo info) internal pure returns (PositionInfo _info) {
assembly ("memory-safe") {
_info := or(info, SET_SUBSCRIBE)
}
}
/// @dev this does not actually set any storage
function setUnsubscribe(PositionInfo info) internal pure returns (PositionInfo _info) {
assembly ("memory-safe") {
_info := and(info, SET_UNSUBSCRIBE)
}
}
/// @notice Creates the default PositionInfo struct
/// @dev Called when minting a new position
/// @param _poolKey the pool key of the position
/// @param _tickLower the lower tick of the position
/// @param _tickUpper the upper tick of the position
/// @return info packed position info, with the truncated poolId and the hasSubscriber flag set to false
function initialize(PoolKey memory _poolKey, int24 _tickLower, int24 _tickUpper)
internal
pure
returns (PositionInfo info)
{
bytes25 _poolId = bytes25(PoolId.unwrap(_poolKey.toId()));
assembly {
info := or(
or(and(MASK_UPPER_200_BITS, _poolId), shl(TICK_UPPER_OFFSET, and(MASK_24_BITS, _tickUpper))),
shl(TICK_LOWER_OFFSET, and(MASK_24_BITS, _tickLower))
)
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ISubscriber} from "./ISubscriber.sol";
/// @title INotifier
/// @notice Interface for the Notifier contract
interface INotifier {
/// @notice Thrown when unsubscribing without a subscriber
error NotSubscribed();
/// @notice Thrown when a subscriber does not have code
error NoCodeSubscriber();
/// @notice Thrown when a user specifies a gas limit too low to avoid valid unsubscribe notifications
error GasLimitTooLow();
/// @notice Wraps the revert message of the subscriber contract on a reverting subscription
error SubscriptionReverted(address subscriber, bytes reason);
/// @notice Wraps the revert message of the subscriber contract on a reverting modify liquidity notification
error ModifyLiquidityNotificationReverted(address subscriber, bytes reason);
/// @notice Wraps the revert message of the subscriber contract on a reverting burn notification
error BurnNotificationReverted(address subscriber, bytes reason);
/// @notice Thrown when a tokenId already has a subscriber
error AlreadySubscribed(uint256 tokenId, address subscriber);
/// @notice Emitted on a successful call to subscribe
event Subscription(uint256 indexed tokenId, address indexed subscriber);
/// @notice Emitted on a successful call to unsubscribe
event Unsubscription(uint256 indexed tokenId, address indexed subscriber);
/// @notice Returns the subscriber for a respective position
/// @param tokenId the ERC721 tokenId
/// @return subscriber the subscriber contract
function subscriber(uint256 tokenId) external view returns (ISubscriber subscriber);
/// @notice Enables the subscriber to receive notifications for a respective position
/// @param tokenId the ERC721 tokenId
/// @param newSubscriber the address of the subscriber contract
/// @param data caller-provided data that's forwarded to the subscriber contract
/// @dev Calling subscribe when a position is already subscribed will revert
/// @dev payable so it can be multicalled with NATIVE related actions
/// @dev will revert if pool manager is locked
function subscribe(uint256 tokenId, address newSubscriber, bytes calldata data) external payable;
/// @notice Removes the subscriber from receiving notifications for a respective position
/// @param tokenId the ERC721 tokenId
/// @dev Callers must specify a high gas limit (remaining gas should be higher than unsubscriberGasLimit) such that the subscriber can be notified
/// @dev payable so it can be multicalled with NATIVE related actions
/// @dev Must always allow a user to unsubscribe. In the case of a malicious subscriber, a user can always unsubscribe safely, ensuring liquidity is always modifiable.
/// @dev will revert if pool manager is locked
function unsubscribe(uint256 tokenId) external payable;
/// @notice Returns and determines the maximum allowable gas-used for notifying unsubscribe
/// @return uint256 the maximum gas limit when notifying a subscriber's `notifyUnsubscribe` function
function unsubscribeGasLimit() external view returns (uint256);
}// 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 IERC721Permit_v4
/// @notice Interface for the ERC721Permit_v4 contract
interface IERC721Permit_v4 {
error SignatureDeadlineExpired();
error NoSelfPermit();
error Unauthorized();
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param nonce a unique value, for an owner, to prevent replay attacks; an unordered nonce where the top 248 bits correspond to a word and the bottom 8 bits calculate the bit position of the word
/// @param signature Concatenated data from a valid secp256k1 signature from the holder, i.e. abi.encodePacked(r, s, v)
/// @dev payable so it can be multicalled with NATIVE related actions
function permit(address spender, uint256 tokenId, uint256 deadline, uint256 nonce, bytes calldata signature)
external
payable;
/// @notice Set an operator with full permission to an owner's tokens via signature
/// @param owner The address that is setting the operator
/// @param operator The address that will be set as an operator for the owner
/// @param approved The permission to set on the operator
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param nonce a unique value, for an owner, to prevent replay attacks; an unordered nonce where the top 248 bits correspond to a word and the bottom 8 bits calculate the bit position of the word
/// @param signature Concatenated data from a valid secp256k1 signature from the holder, i.e. abi.encodePacked(r, s, v)
/// @dev payable so it can be multicalled with NATIVE related actions
function permitForAll(
address owner,
address operator,
bool approved,
uint256 deadline,
uint256 nonce,
bytes calldata signature
) external payable;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IEIP712_v4
/// @notice Interface for the EIP712 contract
interface IEIP712_v4 {
/// @notice Returns the domain separator for the current chain.
/// @return bytes32 The domain separator
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IMulticall_v4
/// @notice Interface for the Multicall_v4 contract
interface IMulticall_v4 {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` is passed onto all subcalls, even if a previous subcall has consumed the ether.
/// Subcalls can instead use `address(this).value` to see the available ETH, and consume it using {value: x}.
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
/// @title IPoolInitializer_v4
/// @notice Interface for the PoolInitializer_v4 contract
interface IPoolInitializer_v4 {
/// @notice Initialize a Uniswap v4 Pool
/// @dev If the pool is already initialized, this function will not revert and just return type(int24).max
/// @param key The PoolKey of the pool to initialize
/// @param sqrtPriceX96 The initial starting price of the pool, expressed as a sqrtPriceX96
/// @return The current tick of the pool, or type(int24).max if the pool creation failed, or the pool already existed
function initializePool(PoolKey calldata key, uint160 sqrtPriceX96) external payable returns (int24);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IUnorderedNonce
/// @notice Interface for the UnorderedNonce contract
interface IUnorderedNonce {
error NonceAlreadyUsed();
/// @notice mapping of nonces consumed by each address, where a nonce is a single bit on the 256-bit bitmap
/// @dev word is at most type(uint248).max
function nonces(address owner, uint256 word) external view returns (uint256);
/// @notice Revoke a nonce by spending it, preventing it from being used again
/// @dev Used in cases where a valid nonce has not been broadcasted onchain, and the owner wants to revoke the validity of the nonce
/// @dev payable so it can be multicalled with native-token related actions
function revokeNonce(uint256 nonce) external payable;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol";
/// @title IPermit2Forwarder
/// @notice Interface for the Permit2Forwarder contract
interface IPermit2Forwarder {
/// @notice allows forwarding a single permit to permit2
/// @dev this function is payable to allow multicall with NATIVE based actions
/// @param owner the owner of the tokens
/// @param permitSingle the permit data
/// @param signature the signature of the permit; abi.encodePacked(r, s, v)
/// @return err the error returned by a reverting permit call, empty if successful
function permit(address owner, IAllowanceTransfer.PermitSingle calldata permitSingle, bytes calldata signature)
external
payable
returns (bytes memory err);
/// @notice allows forwarding batch permits to permit2
/// @dev this function is payable to allow multicall with NATIVE based actions
/// @param owner the owner of the tokens
/// @param _permitBatch a batch of approvals
/// @param signature the signature of the permit; abi.encodePacked(r, s, v)
/// @return err the error returned by a reverting permit call, empty if successful
function permitBatch(address owner, IAllowanceTransfer.PermitBatch calldata _permitBatch, bytes calldata signature)
external
payable
returns (bytes memory err);
}// 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: 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;
/// @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;
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;
/// @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
// OpenZeppelin Contracts (last updated v5.3.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` from `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.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}// 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: 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 = 100000;
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,
address recipient
) external payable override returns (CreateOrderResult memory) {
PoolId poolId = key.toId();
(uint160 sqrtPriceX96, int24 currentTick, , ) = StateLibrary.getSlot0(poolManager, poolId);
(int24 bottomTick, int24 topTick) = TickLibrary.getValidTickRange(
currentTick,
targetTick,
key.tickSpacing,
isToken0,
sqrtPriceX96
);
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, recipient);
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,
address recipient
) external payable returns (CreateOrderResult[] memory results) {
// Get current tick for validation
(, int24 currentTick, , ) = StateLibrary.getSlot0(poolManager, key.toId());
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, recipient);
}
/**
* @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,
address recipient
) internal whenNotPaused returns (CreateOrderResult[] memory results) {
// require(address(key.hooks) == hook);
require(isHook[address(key.hooks)], "DisabledHook");
require(totalAmount != 0);
if (recipient == address(0)) revert AddressZero();
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: recipient}))
})
)),
(BalanceDelta[])
);
bytes32 positionKey;
unchecked {
for (uint256 i; i < orders.length; i++) {
(, positionKey) = PositionManagement.getPositionKeys(
currentNonce,
poolId,
orders[i].bottomTick,
orders[i].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(orders[i].bottomTick)) << 232 |
uint256(uint24(orders[i].topTick)) << 208 |
uint256(isToken0 ? 1 : 0)
);
positionState[poolId][positionKey].currentNonce = currentNonce[poolId][baseKey];
int24 executableTick = isToken0 ? orders[i].topTick : orders[i].bottomTick;
PositionManagement.addPositionToTick(
isToken0 ? token0PositionAtTick : token1PositionAtTick,
isToken0 ? token0TickBitmap : token1TickBitmap,
key,
executableTick,
positionKey
);
}
_updateUserPosition(poolId, positionKey, orders[i].liquidity, recipient);
results[i].usedAmount = orders[i].amount;
results[i].isToken0 = isToken0;
results[i].bottomTick = orders[i].bottomTick;
results[i].topTick = orders[i].topTick;
emit OrderCreated(recipient, 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";
import {LimitOrderLensTickLogic} from "./LimitOrderLensTickLogic.sol";
import {TickInfo} from "./LimitOrderLensTickTypes.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();
__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 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];
return LimitOrderLensTickLogic.getTickInfosAroundCurrent(poolManager, poolId, poolKey, numTicks);
}
/// @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.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 {TickMath} from "v4-core/libraries/TickMath.sol";
import {SqrtPriceMath} from "v4-core/libraries/SqrtPriceMath.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 {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;
uint256 constant PRECISION = 1e18;
uint256 constant FLOOR_MIN_TOKEN0 = 1;
uint256 constant FLOOR_MIN_TOKEN1 = 1;
// Custom errors
error OutMinLengthMismatch();
error InvalidWeightSum();
error NoStrategySpecified();
error InvalidTickRange();
error DuplicatedRange(IMultiPositionManager.Range range);
error InvalidAggregator();
error StrategyDoesNotSupportWeights();
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 (must match factory allowlist)
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 (validated for length)
* @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
)
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);
}
function _processRebalance(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
IMultiPositionManager.RebalanceParams memory params
)
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 {
// Snap to tickSpacing grid using floor division (handles negatives correctly)
int24 tickSpacing = s.poolKey.tickSpacing;
ctx.center = (params.center / tickSpacing) * tickSpacing;
if (params.center < 0 && params.center % tickSpacing != 0) {
ctx.center -= tickSpacing;
}
}
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);
}
/**
* @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 {}
// If strategy doesn't support explicit weights, revert when non-default weights are provided.
if (!params.useCarpet && !supportsWeightedDist && (params.weight0 != 0.5e18 || params.weight1 != 0.5e18)) {
revert StrategyDoesNotSupportWeights();
}
}
uint256[] memory weights = ctx.strategy.calculateDensities(
params.lowerTicks,
params.upperTicks,
params.tick,
params.center,
params.tLeft,
params.tRight,
params.weight0,
params.weight1,
params.useCarpet,
params.tickSpacing,
useAssetWeights
);
return adjustWeightsForFullRangeFloor(weights, lowerTicks, upperTicks, poolKey.tickSpacing, ctx.useCarpet);
}
function adjustWeightsForFullRangeFloor(
uint256[] memory weights,
int24[] memory lowerTicks,
int24[] memory upperTicks,
int24 tickSpacing,
bool useCarpet
) public pure returns (uint256[] memory) {
if (!useCarpet || weights.length == 0 || lowerTicks.length != upperTicks.length) {
return weights;
}
int24 minUsable = TickMath.minUsableTick(tickSpacing);
int24 maxUsable = TickMath.maxUsableTick(tickSpacing);
uint256 floorIdx = _findFullRangeIndex(lowerTicks, upperTicks, minUsable, maxUsable);
if (floorIdx == type(uint256).max) {
return weights;
}
if (weights.length == 1) {
return weights;
}
_adjustWeightsForFloorIndex(weights, floorIdx);
return weights;
}
function _executeRebalance(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
StrategyContext memory ctx,
IMultiPositionManager.Range[] memory baseRanges,
uint256[] memory weights
) internal returns (IMultiPositionManager.Range[] memory, uint128[] memory, uint24) {
// Calculate liquidities from weights
uint128[] memory liquidities = new uint128[](baseRanges.length);
_calculateLiquiditiesForRebalance(s, poolManager, ctx, weights, baseRanges, liquidities, ctx.useCarpet);
// 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
});
}
function _calculateLiquiditiesForRebalance(
SharedStructs.ManagerStorage storage s,
IPoolManager poolManager,
StrategyContext memory ctx,
uint256[] memory weights,
IMultiPositionManager.Range[] memory baseRanges,
uint128[] memory liquidities,
bool useCarpet
) private view {
(uint160 sqrtPriceX96,,,) = poolManager.getSlot0(s.poolKey.toId());
(uint256 available0, uint256 available1) = _getTotalAvailable(s, poolManager);
LiquidityCalcParams memory calcParams = LiquidityCalcParams({
amount0: available0,
amount1: available1,
sqrtPriceX96: sqrtPriceX96,
useAssetWeights: ctx.useAssetWeights,
tickSpacing: s.poolKey.tickSpacing,
useCarpet: useCarpet
});
_calculateLiquiditiesFromWeightsWithParams(liquidities, weights, baseRanges, calcParams);
}
struct AllocationData {
uint256[] token0Allocations;
uint256[] token1Allocations;
uint256 totalToken0Needed;
uint256 totalToken1Needed;
uint256 currentRangeIndex;
int24 currentTick;
bool hasCurrentRange;
}
struct LiquidityCalcParams {
uint256 amount0;
uint256 amount1;
uint160 sqrtPriceX96;
bool useAssetWeights;
int24 tickSpacing;
bool useCarpet;
}
struct FloorReserveInfo {
bool active;
uint256 index;
uint256 reserve0;
uint256 reserve1;
uint128 liquidity;
}
struct FloorRangeContext {
uint256 total0;
uint256 total1;
uint160 sqrtPriceX96;
int24 tickSpacing;
int24 minUsable;
int24 maxUsable;
int24 currentTick;
}
/**
* @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,
int24 tickSpacing,
bool useCarpet
) internal pure {
FloorReserveInfo memory floorInfo;
uint256 remaining0 = total0;
uint256 remaining1 = total1;
if (useCarpet) {
(floorInfo, remaining0, remaining1) =
_reserveFloorLiquidity(baseRanges, total0, total1, sqrtPriceX96, tickSpacing, useCarpet);
if (floorInfo.active) {
_adjustWeightsForFloorIndex(weights, floorInfo.index);
}
}
if (!useAssetWeights) {
// For explicit weights, use direct liquidity calculation (old approach)
calculateLiquiditiesDirectly(liquidities, weights, baseRanges, remaining0, remaining1, sqrtPriceX96);
if (floorInfo.active && floorInfo.index < liquidities.length) {
uint256 combined = uint256(liquidities[floorInfo.index]) + floorInfo.liquidity;
liquidities[floorInfo.index] =
combined > type(uint128).max ? type(uint128).max : uint128(combined);
}
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, useCarpet, tickSpacing);
// Step 2: Scale allocations proportionally to available tokens
scaleAllocations(data, remaining0, remaining1, 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);
if (floorInfo.active && floorInfo.index < liquidities.length) {
uint256 combined = uint256(liquidities[floorInfo.index]) + floorInfo.liquidity;
liquidities[floorInfo.index] = combined > type(uint128).max ? type(uint128).max : uint128(combined);
}
}
function _calculateLiquiditiesFromWeightsWithParams(
uint128[] memory liquidities,
uint256[] memory weights,
IMultiPositionManager.Range[] memory baseRanges,
LiquidityCalcParams memory params
) internal pure {
_calculateLiquiditiesFromWeights(
liquidities,
weights,
baseRanges,
params.amount0,
params.amount1,
params.sqrtPriceX96,
params.useAssetWeights,
params.tickSpacing,
params.useCarpet
);
}
/**
* @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,
bool useCarpet,
int24 tickSpacing
) internal pure {
uint256 rangesLength = baseRanges.length;
int24 minUsable = 0;
int24 maxUsable = 0;
if (useCarpet) {
minUsable = TickMath.minUsableTick(tickSpacing);
maxUsable = TickMath.maxUsableTick(tickSpacing);
}
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) {
if (
useCarpet && rangesLength > 1 && baseRanges[i].lowerTick == minUsable
&& baseRanges[i].upperTick == maxUsable
) {
// Skip full-range floor for currentRangeIndex bookkeeping.
} else {
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))
uint256 liquidityFrom1 = 0;
if (sqrtPriceX96 > sqrtPriceLower) {
// Direct division as Python does: liquidity = amount1 / (sqrtPrice - sqrtPriceLower)
liquidityFrom1 =
FullMath.mulDiv(data.token1Allocations[idx], FixedPoint96.Q96, sqrtPriceX96 - sqrtPriceLower);
}
uint256 actualLiquidity;
if (sqrtPriceX96 <= sqrtPriceLower) {
// At the lower boundary, the range is token0-only.
if (data.token0Allocations[idx] > 0 && sqrtPriceUpper > sqrtPriceLower) {
uint256 intermediate = FullMath.mulDiv(sqrtPriceUpper, sqrtPriceLower, FixedPoint96.Q96);
actualLiquidity =
FullMath.mulDiv(data.token0Allocations[idx], intermediate, sqrtPriceUpper - sqrtPriceLower);
} else {
actualLiquidity = 0;
}
} else {
// 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
uint256 denom = FullMath.mulDiv(sqrtPriceUpper, sqrtPriceX96, FixedPoint96.Q96);
if (denom == 0) {
uint256 scaled = FullMath.mulDiv(liquidityFrom1, sqrtPriceUpper - sqrtPriceX96, sqrtPriceUpper);
token0Needed = FullMath.mulDiv(scaled, FixedPoint96.Q96, sqrtPriceX96);
} else {
token0Needed = FullMath.mulDiv(liquidityFrom1, sqrtPriceUpper - sqrtPriceX96, denom);
}
}
// Python: if x<position_x: #if token y is actually in excess
if (data.token0Allocations[idx] < token0Needed) {
// Token0 is actually limiting, recalculate
// token0Needed > 0 implies sqrtPriceX96 < sqrtPriceUpper
uint256 intermediate = FullMath.mulDiv(sqrtPriceUpper, sqrtPriceX96, FixedPoint96.Q96);
actualLiquidity =
FullMath.mulDiv(data.token0Allocations[idx], intermediate, sqrtPriceUpper - sqrtPriceX96);
} else {
// Token1 is limiting, use liquidityFrom1
actualLiquidity = liquidityFrom1;
}
}
// Calculate actual usage with the determined liquidity
(excess.actualToken0, excess.actualToken1) =
LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96,
sqrtPriceLower,
sqrtPriceUpper,
_capLiquidity(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) {
uint256 liquidity = FullMath.mulDiv(
data.token1Allocations[i],
FixedPoint96.Q96,
sqrtPriceUpper - sqrtPriceLower
);
liquidities[i] = _capLiquidity(liquidity);
} 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);
uint256 liquidity =
FullMath.mulDiv(data.token0Allocations[i], intermediate, sqrtPriceUpper - sqrtPriceLower);
liquidities[i] = _capLiquidity(liquidity);
} else {
liquidities[i] = 0;
}
} else {
// Current range - use Python's exact logic
if (sqrtPriceX96 <= sqrtPriceLower) {
// At the lower boundary, the range is token0-only.
if (data.token0Allocations[i] > 0 && sqrtPriceUpper > sqrtPriceLower) {
uint256 intermediate = FullMath.mulDiv(sqrtPriceUpper, sqrtPriceLower, FixedPoint96.Q96);
uint256 liquidity =
FullMath.mulDiv(data.token0Allocations[i], intermediate, sqrtPriceUpper - sqrtPriceLower);
liquidities[i] = _capLiquidity(liquidity);
} else {
liquidities[i] = 0;
}
} else {
// First assume token1 is limiting
uint256 liquidityFrom1 = 0;
if (sqrtPriceX96 > sqrtPriceLower && data.token1Allocations[i] > 0) {
liquidityFrom1 =
FullMath.mulDiv(data.token1Allocations[i], FixedPoint96.Q96, sqrtPriceX96 - sqrtPriceLower);
}
// Calculate token0 needed with this liquidity
uint256 token0Needed = 0;
if (sqrtPriceX96 < sqrtPriceUpper && liquidityFrom1 > 0) {
uint256 denom = FullMath.mulDiv(sqrtPriceUpper, sqrtPriceX96, FixedPoint96.Q96);
if (denom == 0) {
uint256 scaled =
FullMath.mulDiv(liquidityFrom1, sqrtPriceUpper - sqrtPriceX96, sqrtPriceUpper);
token0Needed = FullMath.mulDiv(scaled, FixedPoint96.Q96, sqrtPriceX96);
} else {
token0Needed = FullMath.mulDiv(liquidityFrom1, sqrtPriceUpper - sqrtPriceX96, denom);
}
}
// Check if token0 is actually limiting
if (data.token0Allocations[i] < token0Needed) {
// Token0 is limiting
// token0Needed > 0 implies sqrtPriceX96 < sqrtPriceUpper
uint256 intermediate = FullMath.mulDiv(sqrtPriceUpper, sqrtPriceX96, FixedPoint96.Q96);
uint256 liquidity =
FullMath.mulDiv(data.token0Allocations[i], intermediate, sqrtPriceUpper - sqrtPriceX96);
liquidities[i] = _capLiquidity(liquidity);
} else {
// Token1 is limiting
liquidities[i] = _capLiquidity(liquidityFrom1);
}
}
}
unchecked {
++i;
}
}
}
function _adjustWeightsForFloorIndex(uint256[] memory weights, uint256 floorIdx) private pure {
if (weights.length == 0) {
return;
}
uint256 sum;
for (uint256 i = 0; i < weights.length; ++i) {
if (i == floorIdx) {
continue;
}
sum += weights[i];
}
if (sum == 0) {
weights[floorIdx] = 0;
return;
}
for (uint256 i = 0; i < weights.length; ++i) {
if (i == floorIdx) {
continue;
}
weights[i] = FullMath.mulDiv(weights[i], PRECISION, sum);
}
weights[floorIdx] = 0;
}
function _findFullRangeIndex(
int24[] memory lowerTicks,
int24[] memory upperTicks,
int24 minUsable,
int24 maxUsable
) private pure returns (uint256) {
uint256 length = lowerTicks.length;
for (uint256 i = 0; i < length; ++i) {
if (lowerTicks[i] == minUsable && upperTicks[i] == maxUsable) {
return i;
}
}
return type(uint256).max;
}
function _findFullRangeIndex(
IMultiPositionManager.Range[] memory ranges,
int24 minUsable,
int24 maxUsable
) private pure returns (uint256) {
uint256 length = ranges.length;
for (uint256 i = 0; i < length; ++i) {
if (ranges[i].lowerTick == minUsable && ranges[i].upperTick == maxUsable) {
return i;
}
}
return type(uint256).max;
}
function _reserveFloorLiquidity(
IMultiPositionManager.Range[] memory baseRanges,
uint256 total0,
uint256 total1,
uint160 sqrtPriceX96,
int24 tickSpacing,
bool useCarpet
) private pure returns (FloorReserveInfo memory info, uint256 remaining0, uint256 remaining1) {
remaining0 = total0;
remaining1 = total1;
if (!useCarpet || baseRanges.length == 0) {
return (info, remaining0, remaining1);
}
FloorRangeContext memory ctx;
ctx.total0 = total0;
ctx.total1 = total1;
ctx.sqrtPriceX96 = sqrtPriceX96;
ctx.tickSpacing = tickSpacing;
ctx.minUsable = TickMath.minUsableTick(tickSpacing);
ctx.maxUsable = TickMath.maxUsableTick(tickSpacing);
uint256 floorIdx = _findFullRangeIndex(baseRanges, ctx.minUsable, ctx.maxUsable);
if (floorIdx == type(uint256).max) {
return (info, remaining0, remaining1);
}
if (baseRanges.length == 1) {
return (info, remaining0, remaining1);
}
info = _computeFloorReservation(ctx, baseRanges, floorIdx);
if (info.active) {
remaining0 = ctx.total0 - info.reserve0;
remaining1 = ctx.total1 - info.reserve1;
}
return (info, remaining0, remaining1);
}
function _computeFloorReservation(
FloorRangeContext memory ctx,
IMultiPositionManager.Range[] memory baseRanges,
uint256 floorIdx
) private pure returns (FloorReserveInfo memory info) {
info.index = floorIdx;
ctx.currentTick = TickMath.getTickAtSqrtPrice(ctx.sqrtPriceX96);
(uint128 minLiquidity, uint256 reserve0, uint256 reserve1) =
_minFloorLiquidityAndReserves(baseRanges[floorIdx], ctx.currentTick, ctx.sqrtPriceX96);
if (reserve0 <= ctx.total0 && reserve1 <= ctx.total1) {
info.active = true;
info.reserve0 = reserve0;
info.reserve1 = reserve1;
info.liquidity = minLiquidity;
return info;
}
FloorReserveInfo memory candidate = _tryOneSidedFloor(ctx, baseRanges, floorIdx);
if (candidate.active) {
info.active = true;
info.reserve0 = candidate.reserve0;
info.reserve1 = candidate.reserve1;
info.liquidity = candidate.liquidity;
}
return info;
}
function _selectOneSidedFloorRange(FloorRangeContext memory ctx)
private
pure
returns (
bool hasRange,
IMultiPositionManager.Range memory range,
uint256 reserve0,
uint256 reserve1,
uint128 liquidity
)
{
int24 alignedDown = _roundDownTick(ctx.currentTick, ctx.tickSpacing);
int24 alignedUp = _roundUpTick(ctx.currentTick, ctx.tickSpacing);
if (alignedDown < ctx.minUsable) alignedDown = ctx.minUsable;
if (alignedUp > ctx.maxUsable) alignedUp = ctx.maxUsable;
{
(bool canToken0, IMultiPositionManager.Range memory token0Range, uint256 token0Reserve, uint128 token0Liquidity)
= _evaluateToken0OneSided(ctx, alignedUp);
if (canToken0) {
return (true, token0Range, token0Reserve, 0, token0Liquidity);
}
}
{
(bool canToken1, IMultiPositionManager.Range memory token1Range, uint256 token1Reserve, uint128 token1Liquidity)
= _evaluateToken1OneSided(ctx, alignedDown);
if (canToken1) {
return (true, token1Range, 0, token1Reserve, token1Liquidity);
}
}
return (false, range, 0, 0, 0);
}
function _evaluateToken0OneSided(FloorRangeContext memory ctx, int24 alignedUp)
private
pure
returns (bool canToken0, IMultiPositionManager.Range memory range, uint256 reserve0, uint128 liquidity)
{
if (alignedUp < ctx.maxUsable) {
range = IMultiPositionManager.Range({lowerTick: alignedUp, upperTick: ctx.maxUsable});
(liquidity, reserve0,) = _minFloorLiquidityAndReserves(range, ctx.currentTick, ctx.sqrtPriceX96);
canToken0 = reserve0 <= ctx.total0;
}
}
function _evaluateToken1OneSided(FloorRangeContext memory ctx, int24 alignedDown)
private
pure
returns (bool canToken1, IMultiPositionManager.Range memory range, uint256 reserve1, uint128 liquidity)
{
if (alignedDown > ctx.minUsable) {
range = IMultiPositionManager.Range({lowerTick: ctx.minUsable, upperTick: alignedDown});
(liquidity,, reserve1) = _minFloorLiquidityAndReserves(range, ctx.currentTick, ctx.sqrtPriceX96);
canToken1 = reserve1 <= ctx.total1;
}
}
function _tryOneSidedFloor(
FloorRangeContext memory ctx,
IMultiPositionManager.Range[] memory baseRanges,
uint256 floorIdx
) private pure returns (FloorReserveInfo memory info) {
(
bool hasRange,
IMultiPositionManager.Range memory oneSided,
uint256 oneReserve0,
uint256 oneReserve1,
uint128 oneLiquidity
) = _selectOneSidedFloorRange(ctx);
if (hasRange && !_rangeExists(baseRanges, oneSided, floorIdx)) {
baseRanges[floorIdx] = oneSided;
info.active = true;
info.reserve0 = oneReserve0;
info.reserve1 = oneReserve1;
info.liquidity = oneLiquidity;
}
}
function _roundDownTick(int24 tick, int24 tickSpacing) private pure returns (int24) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) {
compressed -= 1;
}
return compressed * tickSpacing;
}
function _roundUpTick(int24 tick, int24 tickSpacing) private pure returns (int24) {
int24 roundedDown = _roundDownTick(tick, tickSpacing);
if (roundedDown < tick) {
return roundedDown + tickSpacing;
}
return roundedDown;
}
function _rangeExists(
IMultiPositionManager.Range[] memory ranges,
IMultiPositionManager.Range memory candidate,
uint256 skipIndex
) private pure returns (bool) {
uint256 length = ranges.length;
for (uint256 i = 0; i < length; ++i) {
if (i == skipIndex) {
continue;
}
if (ranges[i].lowerTick == candidate.lowerTick && ranges[i].upperTick == candidate.upperTick) {
return true;
}
}
return false;
}
function _minFloorLiquidityAndReserves(
IMultiPositionManager.Range memory range,
int24 currentTick,
uint160 sqrtPriceX96
) private pure returns (uint128 liquidity, uint256 reserve0, uint256 reserve1) {
if (range.upperTick <= range.lowerTick) {
return (0, 0, 0);
}
uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(range.lowerTick);
uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(range.upperTick);
bool needsToken0 = currentTick <= range.lowerTick || (range.lowerTick < currentTick && currentTick < range.upperTick);
bool needsToken1 = currentTick >= range.upperTick || (range.lowerTick < currentTick && currentTick < range.upperTick);
uint256 minLiquidity0;
uint256 minLiquidity1;
if (currentTick <= range.lowerTick) {
minLiquidity0 = _liquidityForAmount0RoundingUp(sqrtPriceLower, sqrtPriceUpper, FLOOR_MIN_TOKEN0);
} else if (currentTick >= range.upperTick) {
minLiquidity1 = _liquidityForAmount1RoundingUp(sqrtPriceLower, sqrtPriceUpper, FLOOR_MIN_TOKEN1);
} else {
minLiquidity0 = _liquidityForAmount0RoundingUp(sqrtPriceX96, sqrtPriceUpper, FLOOR_MIN_TOKEN0);
minLiquidity1 = _liquidityForAmount1RoundingUp(sqrtPriceLower, sqrtPriceX96, FLOOR_MIN_TOKEN1);
}
uint256 minLiquidity = minLiquidity0 > minLiquidity1 ? minLiquidity0 : minLiquidity1;
liquidity = _capLiquidity(minLiquidity);
(reserve0, reserve1) =
_getAmountsForLiquidityRoundingUp(sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, liquidity);
if (!_meetsMinAmounts(needsToken0, needsToken1, reserve0, reserve1)) {
return (0, 0, 0);
}
return (liquidity, reserve0, reserve1);
}
function _meetsMinAmounts(bool needsToken0, bool needsToken1, uint256 amount0, uint256 amount1)
private
pure
returns (bool)
{
if (needsToken0 && amount0 < FLOOR_MIN_TOKEN0) return false;
if (needsToken1 && amount1 < FLOOR_MIN_TOKEN1) return false;
return true;
}
function _liquidityForAmount0RoundingUp(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount0)
private
pure
returns (uint256)
{
if (amount0 == 0) {
return 0;
}
if (sqrtPriceAX96 > sqrtPriceBX96) {
(sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
}
if (sqrtPriceBX96 <= sqrtPriceAX96) {
return 0;
}
uint256 intermediate = FullMath.mulDivRoundingUp(uint256(sqrtPriceAX96), uint256(sqrtPriceBX96), FixedPoint96.Q96);
return FullMath.mulDivRoundingUp(amount0, intermediate, uint256(sqrtPriceBX96) - uint256(sqrtPriceAX96));
}
function _liquidityForAmount1RoundingUp(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount1)
private
pure
returns (uint256)
{
if (amount1 == 0) {
return 0;
}
if (sqrtPriceAX96 > sqrtPriceBX96) {
(sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
}
if (sqrtPriceBX96 <= sqrtPriceAX96) {
return 0;
}
return FullMath.mulDivRoundingUp(amount1, FixedPoint96.Q96, uint256(sqrtPriceBX96) - uint256(sqrtPriceAX96));
}
function _getAmountsForLiquidityRoundingUp(
uint160 sqrtPriceX96,
uint160 sqrtPriceLower,
uint160 sqrtPriceUpper,
uint128 liquidity
) private pure returns (uint256 amount0, uint256 amount1) {
if (sqrtPriceX96 <= sqrtPriceLower) {
amount0 = SqrtPriceMath.getAmount0Delta(sqrtPriceLower, sqrtPriceUpper, liquidity, true);
} else if (sqrtPriceX96 < sqrtPriceUpper) {
amount0 = SqrtPriceMath.getAmount0Delta(sqrtPriceX96, sqrtPriceUpper, liquidity, true);
amount1 = SqrtPriceMath.getAmount1Delta(sqrtPriceLower, sqrtPriceX96, liquidity, true);
} else {
amount1 = SqrtPriceMath.getAmount1Delta(sqrtPriceLower, sqrtPriceUpper, liquidity, true);
}
}
function _capLiquidity(uint256 liquidity) private pure returns (uint128) {
return liquidity > type(uint128).max ? type(uint128).max : uint128(liquidity);
}
/**
* @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 < 2;) {
IMultiPositionManager.Range memory limitRange = s.limitPositions[i];
if (limitRange.lowerTick != limitRange.upperTick) {
(, uint256 amount0, uint256 amount1, uint256 feesOwed0, uint256 feesOwed1) =
PoolManagerUtils.getAmountsOf(poolManager, poolKey, limitRange);
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) {
if (rebalanceParams.useCarpet) {
inMin = new uint256[2][](baseRanges.length);
} else {
revert InMinLengthMismatch(inMin.length, baseRanges.length);
}
}
// Mint new positions and capture position data
IMultiPositionManager.PositionData[] memory positionData =
PositionLogic.mintLiquidities(poolManager, s, liquidities, inMin, rebalanceParams.useCarpet);
// 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 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
pure
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 pure returns (uint256 totalAmount0, uint256 totalAmount1) {
uint256[] memory densities = _getDensities(params, lowerTicks, upperTicks);
densities = adjustWeightsForFullRangeFloor(densities, lowerTicks, upperTicks, params.tickSpacing, params.useCarpet);
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 pure 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 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);
}
function _generateRangesAndWeights(
PoolKey memory poolKey,
IPoolManager poolManager,
StrategyContext memory ctx,
bool useCarpet
) private view returns (IMultiPositionManager.Range[] memory baseRanges, uint256[] memory weights) {
(int24[] memory lowerTicks, int24[] memory upperTicks) =
ctx.strategy.generateRanges(ctx.center, ctx.tLeft, ctx.tRight, poolKey.tickSpacing, useCarpet);
baseRanges = new IMultiPositionManager.Range[](lowerTicks.length);
for (uint256 i = 0; i < lowerTicks.length;) {
baseRanges[i] = IMultiPositionManager.Range(lowerTicks[i], upperTicks[i]);
unchecked {
++i;
}
}
StrategyContext memory weightCtx = ctx;
weightCtx.useCarpet = useCarpet;
weights = calculateWeightsWithPoolKey(poolKey, poolManager, weightCtx, lowerTicks, upperTicks);
}
function generateRangesAndLiquiditiesWithPoolKey(
PoolKey memory poolKey,
IPoolManager poolManager,
StrategyContext memory ctx,
uint256 amount0,
uint256 amount1
) public view returns (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities) {
// Get current sqrt price
(uint160 sqrtPriceX96Current,,,) = poolManager.getSlot0(poolKey.toId());
uint256[] memory weights;
(baseRanges, weights) = _generateRangesAndWeights(poolKey, poolManager, ctx, ctx.useCarpet);
liquidities = new uint128[](baseRanges.length);
LiquidityCalcParams memory calcParams = LiquidityCalcParams({
amount0: amount0,
amount1: amount1,
sqrtPriceX96: sqrtPriceX96Current,
useAssetWeights: ctx.useAssetWeights,
tickSpacing: poolKey.tickSpacing,
useCarpet: ctx.useCarpet
});
_calculateLiquiditiesFromWeightsWithParams(liquidities, weights, baseRanges, calcParams);
}
}// 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 {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;
// Aggregator allowlist (enum index -> router)
mapping(uint8 => address) public override aggregatorAddress;
// Strategy allowlist (strategy address -> allowed)
mapping(address => bool) public override strategyAllowed;
// 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 managers by token pair (key = keccak256(currency0, currency1))
mapping(bytes32 => address[]) private _managersByTokenPair;
// Track all unique token pairs
TokenPairInfo[] private _allTokenPairs;
/// @dev Maps pairKey to index+1 in _allTokenPairs (0 = doesn't exist)
mapping(bytes32 => uint256) private _tokenPairIndex;
// Protocol fee recipient
address public feeRecipient;
// Protocol fee (denominator for fee calculation, e.g., 10 = 10%, 20 = 5%)
uint16 public protocolFee = 4;
// Pool manager for all deployments
IPoolManager public immutable poolManager;
// Deployer contract for MultiPositionManager
MultiPositionDeployer public immutable deployer;
address public orderBookFactory;
bool public orderBookFactorySet;
uint256 public lockDuration = 180 days;
uint24 public minTicksLeftInitial = 100000;
uint24 public minTicksRightInitial = 100000;
uint24 public minLimitWidthInitial = 50000;
uint24 public minTicksLeftAfter = 5000;
uint24 public minTicksRightAfter = 5000;
uint24 public minLimitWidthAfter = 1000;
uint32 public twapSeconds = 30;
uint24 public maxTwapTickDelta = 1000;
// Custom errors
error UnauthorizedAccess();
error UnauthorizedCaller();
error OrderBookFactoryAlreadySet();
error ManagerAlreadyExists();
error InvalidAddress();
error InitializationFailed();
error InvalidFee();
error InsufficientMsgValue();
error PoolNotInitialized();
error InvalidSqrtPriceX96();
error MPMAlreadyInitialized();
error InvalidAmount();
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(address(this));
}
modifier onlyOrderBookFactory() {
if (msg.sender != orderBookFactory) revert UnauthorizedCaller();
_;
}
function setOrderBookFactory(address newOrderBookFactory) external onlyOwner {
if (newOrderBookFactory == address(0)) revert InvalidAddress();
if (orderBookFactorySet) revert OrderBookFactoryAlreadySet();
orderBookFactory = newOrderBookFactory;
orderBookFactorySet = true;
}
/**
* @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
onlyOrderBookFactory
returns (address)
{
return _deployMultiPositionManager(poolKey, managerOwner, name);
}
function _deployMultiPositionManager(PoolKey memory poolKey, address managerOwner, string memory name)
internal
returns (address)
{
if (managerOwner == address(0)) revert InvalidAddress();
address predicted = _computeAddress(poolKey, managerOwner, name);
if (predicted.code.length > 0) {
_validateExistingManager(predicted, poolKey, managerOwner);
return predicted;
}
// 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 = "UNILAUNCH-LP";
// Deploy using deployer contract
address managerAddress = deployer.deploy(
poolManager,
poolKey,
managerOwner,
address(this), // factory address
name,
symbol,
protocolFee,
salt
);
// 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 (O(1) lookup via index+1 pattern)
uint256 indexPlusOne = _tokenPairIndex[pairKey];
if (indexPlusOne == 0) {
// New pair - store index+1 before pushing
_tokenPairIndex[pairKey] = _allTokenPairs.length + 1;
_allTokenPairs.push(TokenPairInfo({currency0: currency0, currency1: currency1, managerCount: 1}));
} else {
// Existing pair - direct O(1) access
_allTokenPairs[indexPlusOne - 1].managerCount++;
}
emit MultiPositionManagerDeployed(managerAddress, managerOwner, poolKey);
return managerAddress;
}
function _validateExistingManager(address managerAddress, PoolKey memory poolKey, address managerOwner)
private
view
{
IMultiPositionManager existing = IMultiPositionManager(managerAddress);
if (existing.factory() != address(this)) revert ManagerAlreadyExists();
if (!_poolKeysEqual(existing.poolKey(), poolKey)) revert ManagerAlreadyExists();
if (Ownable(managerAddress).owner() != managerOwner) revert ManagerAlreadyExists();
}
function _poolKeysEqual(PoolKey memory a, PoolKey memory b) private pure returns (bool) {
return Currency.unwrap(a.currency0) == Currency.unwrap(b.currency0)
&& Currency.unwrap(a.currency1) == Currency.unwrap(b.currency1)
&& a.fee == b.fee
&& a.tickSpacing == b.tickSpacing
&& address(a.hooks) == address(b.hooks);
}
/**
* @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 onlyOrderBookFactory returns (address mpm) {
// Input validation
if (managerOwner == address(0)) revert InvalidAddress();
if (to == address(0)) revert InvalidAddress();
address predicted = _computeAddress(poolKey, managerOwner, name);
if (predicted.code.length > 0) {
_ensureFreshManager(predicted);
}
// Deploy MPM (idempotent if already deployed at predicted address)
mpm = _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
*/
/**
* @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)
{
return _computeAddress(poolKey, managerOwner, name);
}
function _computeAddress(PoolKey memory poolKey, address managerOwner, string memory name)
private
view
returns (address)
{
// Use fixed symbol for all deployments
string memory symbol = "UNILAUNCH-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);
}
function _ensureFreshManager(address managerAddress) private view {
IMultiPositionManager existing = IMultiPositionManager(managerAddress);
if (existing.totalSupply() != 0) revert MPMAlreadyInitialized();
if (existing.basePositionsLength() != 0 || existing.limitPositionsLength() != 0) {
revert MPMAlreadyInitialized();
}
(address strategy,,,,,,,,,) = existing.lastStrategyParams();
if (strategy != address(0)) revert MPMAlreadyInitialized();
}
/**
* @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;
}
function setLockDuration(uint256 newDuration) external onlyOwner {
lockDuration = newDuration;
}
function setMinTicksInitial(uint24 left, uint24 right, uint24 limitWidth) external onlyOwner {
minTicksLeftInitial = left;
minTicksRightInitial = right;
minLimitWidthInitial = limitWidth;
}
function setMinTicksAfter(uint24 left, uint24 right, uint24 limitWidth) external onlyOwner {
minTicksLeftAfter = left;
minTicksRightAfter = right;
minLimitWidthAfter = limitWidth;
}
function setTwapConfig(uint32 newTwapSeconds, uint24 newMaxTickDelta) external onlyOwner {
if (newTwapSeconds == 0) revert InvalidAmount();
if (newMaxTickDelta == 0) revert InvalidAmount();
twapSeconds = newTwapSeconds;
maxTwapTickDelta = newMaxTickDelta;
}
/**
* @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 Set the approved router for a swap aggregator
* @param aggregator Aggregator enum index
* @param router Approved router address
*/
function setAggregatorAddress(uint8 aggregator, address router) external onlyOwner {
if (router == address(0)) revert InvalidAddress();
aggregatorAddress[aggregator] = router;
}
/**
* @notice Set whether a strategy contract is allowed for rebalances
* @param strategy Strategy contract address
* @param allowed True to allow, false to disallow
*/
function setStrategyAllowed(address strategy, bool allowed) external onlyOwner {
if (strategy == address(0)) revert InvalidAddress();
strategyAllowed[strategy] = allowed;
}
/**
* @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.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-latest/contracts/utils/TransientSlot.sol";
import {ILimitOrderManager} from "../interfaces/ILimitOrderManager.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";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
/// @title VolatilityDynamicFeeLimitOrderHook
/// @notice Singleton volatility hook for Unilaunch pools with 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;
uint256 private constant BPS_DENOMINATOR = 10_000;
uint24 private constant MAX_LP_FEE = 1_000_000;
ILimitOrderManager public immutable limitOrderManager;
VolatilityOracle public immutable volatilityOracle;
address public immutable orderBookFactory;
mapping(PoolId => bool) public managedPools;
mapping(bytes32 => bool) public poolParametersUsed;
mapping(PoolId => uint256) public tradingEnabledBlock;
struct FeeParams {
uint24 baseFee;
bool enabled;
}
mapping(PoolId => FeeParams) public feeParams;
struct SurgeState {
uint24 surgeMultiplier;
uint32 surgeDuration;
uint32 capStartTime;
bool isActive;
}
mapping(PoolId => SurgeState) public surgeStates;
uint24 public defaultMinCap = 10;
uint24 public defaultMaxCap = 1000;
uint32 public defaultStepPpm = 20000;
uint32 public defaultBudgetPpm = 1000000;
uint32 public defaultDecayWindow = 15552000;
uint32 public defaultUpdateInterval = 86400;
error TradingNotYetEnabled(uint256 enabledBlock, uint256 currentBlock);
error InvalidFeeConfiguration();
error UnauthorizedInitializer();
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
);
constructor(
IPoolManager _poolManager,
address _limitOrderManager,
address _volatilityOracle,
address _orderBookFactory
) BaseHook(_poolManager) Ownable(_orderBookFactory) {
if (_limitOrderManager == address(0)) revert("ZeroAddress");
if (_volatilityOracle == address(0)) revert("ZeroAddress");
if (_orderBookFactory == address(0)) revert("ZeroAddress");
limitOrderManager = ILimitOrderManager(_limitOrderManager);
volatilityOracle = VolatilityOracle(_volatilityOracle);
orderBookFactory = _orderBookFactory;
}
function getHookPermissions() public pure override returns (Hooks.Permissions memory) {
return Hooks.Permissions({
beforeInitialize: true,
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 _beforeInitialize(address sender, PoolKey calldata, uint160)
internal
override
returns (bytes4)
{
if (sender != orderBookFactory) revert UnauthorizedInitializer();
return this.beforeInitialize.selector;
}
function _beforeSwap(
address,
PoolKey calldata key,
SwapParams calldata,
bytes calldata
) internal override returns (bytes4, BeforeSwapDelta, uint24) {
PoolId poolId = key.toId();
uint256 enabledBlock = tradingEnabledBlock[poolId];
if (enabledBlock > 0) {
if (block.number < enabledBlock) {
revert TradingNotYetEnabled(enabledBlock, block.number);
}
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 tickBeforeSwap;
bytes32 slot = _getPreviousTickSlot(poolId);
assembly ("memory-safe") {
tickBeforeSwap := tload(slot)
}
(, int24 tickAfterSwap,,) = StateLibrary.getSlot0(poolManager, poolId);
limitOrderManager.executeOrder(key, tickBeforeSwap, tickAfterSwap, params.zeroForOne);
bool wasCapped = volatilityOracle.pushObservationAndCheckCap(poolId, tickBeforeSwap);
if (wasCapped) {
surgeStates[poolId].isActive = true;
surgeStates[poolId].capStartTime = uint32(block.timestamp);
emit CAPDetected(poolId, uint32(block.timestamp), tickAfterSwap - tickBeforeSwap);
}
return (BaseHook.afterSwap.selector, 0);
}
function _getPreviousTickSlot(PoolId poolId) private pure returns (bytes32) {
return keccak256(abi.encodePacked("unilaunch.hooks.volatility.previous-tick", poolId));
}
function _validateFeeParams(uint24 baseFee, uint24 surgeMultiplier) internal pure {
uint256 maxPossibleFee = uint256(baseFee) + (uint256(baseFee) * surgeMultiplier / BPS_DENOMINATOR);
if (maxPossibleFee > MAX_LP_FEE) revert InvalidFeeConfiguration();
}
function registerPool(
PoolKey calldata key,
uint24 baseFee,
uint24 surgeMultiplier,
uint32 surgeDuration,
uint24 initialMaxTicksPerBlock
) external {
if (msg.sender != orderBookFactory) revert("OnlyOrderBookFactory");
_validateFeeParams(baseFee, surgeMultiplier);
PoolId poolId = key.toId();
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;
feeParams[poolId] = FeeParams({baseFee: baseFee, enabled: true});
surgeStates[poolId] = SurgeState({
surgeMultiplier: surgeMultiplier,
surgeDuration: surgeDuration,
capStartTime: 0,
isActive: false
});
volatilityOracle.enableOracleForPool(
key,
initialMaxTicksPerBlock,
defaultMinCap,
defaultMaxCap,
defaultStepPpm,
defaultBudgetPpm,
defaultDecayWindow,
defaultUpdateInterval
);
tradingEnabledBlock[poolId] = block.number + 1;
emit PoolRegistered(poolId, baseFee, surgeMultiplier, surgeDuration, initialMaxTicksPerBlock);
}
function updateBaseFee(PoolKey calldata key, uint24 newBaseFee) external onlyOwner {
PoolId poolId = key.toId();
if (!managedPools[poolId]) revert("NotManagedPool");
_validateFeeParams(newBaseFee, surgeStates[poolId].surgeMultiplier);
feeParams[poolId].baseFee = newBaseFee;
emit FeeParamsUpdated(poolId, newBaseFee);
}
function updateSurgeParams(PoolKey calldata key, uint24 multiplier, uint32 duration) external onlyOwner {
PoolId poolId = key.toId();
if (!managedPools[poolId]) revert("NotManagedPool");
_validateFeeParams(feeParams[poolId].baseFee, multiplier);
surgeStates[poolId].surgeMultiplier = multiplier;
surgeStates[poolId].surgeDuration = duration;
}
function updateOraclePolicy(
PoolKey calldata key,
uint24 minCap,
uint24 maxCap,
uint32 stepPpm,
uint32 budgetPpm,
uint32 decayWindow,
uint32 updateInterval
) external onlyOwner {
volatilityOracle.refreshPolicyCache(
key.toId(),
minCap,
maxCap,
stepPpm,
budgetPpm,
decayWindow,
updateInterval
);
}
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);
}
}// 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;
}
struct ObserveContext {
uint32 time;
int24 currentTick;
uint128 liquidity;
uint16 newestLocalIdx;
uint16 newestCard;
}
/* ─────────────── 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 index = state.index;
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;
}
}
uint32 ts = uint32(block.timestamp);
TruncatedOracle.Observation storage last = _leaf(poolId, index)[index % PAGE_SIZE];
if (last.blockTimestamp != ts) {
uint16 cardinalityUpdated = state.cardinality;
uint16 cardinalityNext = state.cardinalityNext;
if (cardinalityNext == cardinalityUpdated && cardinalityNext < TruncatedOracle.MAX_CARDINALITY_ALLOWED) {
cardinalityNext = cardinalityUpdated + 1;
}
if (cardinalityNext > cardinalityUpdated && index == (cardinalityUpdated - 1)) {
cardinalityUpdated = cardinalityNext;
if (cardinalityUpdated > TruncatedOracle.MAX_CARDINALITY_ALLOWED) {
cardinalityUpdated = TruncatedOracle.MAX_CARDINALITY_ALLOWED;
}
}
unchecked {
index += 1;
}
if (index >= cardinalityUpdated) {
index = 0;
}
uint128 liquidity = StateLibrary.getLiquidity(poolManager, poolId);
uint32 delta;
unchecked {
delta = ts - last.blockTimestamp;
}
TruncatedOracle.Observation storage o = _leaf(poolId, index)[index % PAGE_SIZE];
o.blockTimestamp = ts;
o.tickCumulative = last.tickCumulative + int56(currentTick) * int56(uint56(delta));
o.secondsPerLiquidityCumulativeX128 = last.secondsPerLiquidityCumulativeX128
+ ((uint160(delta) << 128) / (liquidity > 0 ? liquidity : 1));
o.initialized = true;
state.index = index;
state.cardinality = cardinalityUpdated;
if (
state.cardinalityNext < cardinalityUpdated + 1
&& state.cardinalityNext < TruncatedOracle.MAX_CARDINALITY_ALLOWED
) {
state.cardinalityNext = cardinalityUpdated + 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
uint256 len = secondsAgos.length;
tickCumulatives = new int56[](len);
secondsPerLiquidityCumulativeX128s = new uint160[](len);
if (len == 0) return (tickCumulatives, secondsPerLiquidityCumulativeX128s);
ObserveContext memory ctx;
ctx.time = uint32(block.timestamp);
(, ctx.currentTick,,) = StateLibrary.getSlot0(poolManager, poolId);
ctx.liquidity = StateLibrary.getLiquidity(poolManager, poolId);
ctx.newestLocalIdx = uint16(gIdx % PAGE_SIZE);
{
uint16 newestBase = gIdx - ctx.newestLocalIdx;
uint16 newestCard = state.cardinality > newestBase ? state.cardinality - newestBase : 1;
if (newestCard > PAGE_SIZE) {
newestCard = PAGE_SIZE;
}
ctx.newestCard = newestCard;
}
for (uint256 i = 0; i < len; i++) {
uint32 secondsAgo = secondsAgos[i];
if (secondsAgo == 0) {
TruncatedOracle.Observation[PAGE_SIZE] storage newestPage = _leaf(poolId, gIdx);
(tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i]) =
TruncatedOracle.observeSingle(
newestPage,
ctx.time,
0,
ctx.currentTick,
ctx.newestLocalIdx,
ctx.liquidity,
ctx.newestCard
);
continue;
}
(uint16 leafCursor, uint16 idx, uint16 card) =
_resolveLeafForSecondsAgo(poolId, state, gIdx, ctx.newestLocalIdx, ctx.time, secondsAgo);
TruncatedOracle.Observation[PAGE_SIZE] storage obs = _leaf(poolId, leafCursor);
(tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i]) =
TruncatedOracle.observeSingle(obs, ctx.time, secondsAgo, ctx.currentTick, idx, ctx.liquidity, card);
}
return (tickCumulatives, secondsPerLiquidityCumulativeX128s);
}
function _resolveLeafForSecondsAgo(
PoolId poolId,
ObservationState storage state,
uint16 gIdx,
uint16 newestLocalIdx,
uint32 time,
uint32 secondsAgo
) internal view returns (uint16 leafCursor, uint16 idx, uint16 card) {
uint32 target;
unchecked {
target = time >= secondsAgo ? time - secondsAgo : time + (type(uint32).max - secondsAgo) + 1;
}
uint16 newestBase = gIdx - newestLocalIdx;
uint16 pageCursor = newestBase;
if (state.cardinality == TruncatedOracle.MAX_CARDINALITY_ALLOWED) {
uint16 pageCount = TruncatedOracle.MAX_CARDINALITY_ALLOWED / PAGE_SIZE;
for (uint16 i = 0; i < pageCount; i++) {
TruncatedOracle.Observation[PAGE_SIZE] storage page = _leaf(poolId, pageCursor);
uint16 pageNewestIdx = pageCursor == newestBase ? newestLocalIdx : PAGE_SIZE - 1;
uint16 firstSlot = (pageNewestIdx + 1) % PAGE_SIZE;
uint32 firstTs = page[firstSlot].blockTimestamp;
if (target >= firstTs || i + 1 == pageCount) {
idx = pageNewestIdx;
card = PAGE_SIZE;
return (pageCursor, idx, card);
}
if (pageCursor >= PAGE_SIZE) {
pageCursor -= PAGE_SIZE;
} else {
pageCursor = TruncatedOracle.MAX_CARDINALITY_ALLOWED - PAGE_SIZE;
}
}
}
while (true) {
TruncatedOracle.Observation[PAGE_SIZE] storage page = _leaf(poolId, pageCursor);
uint16 pageCardinality = state.cardinality > pageCursor ? state.cardinality - pageCursor : 1;
if (pageCardinality > PAGE_SIZE) {
pageCardinality = PAGE_SIZE;
}
uint16 pageNewestIdx = pageCursor == newestBase ? newestLocalIdx : pageCardinality - 1;
uint16 firstSlot = pageCardinality == PAGE_SIZE ? (pageNewestIdx + 1) % PAGE_SIZE : 0;
uint32 firstTs = page[firstSlot].blockTimestamp;
if (target >= firstTs || pageCursor == 0) {
idx = pageNewestIdx;
card = pageCardinality;
return (pageCursor, idx, card);
}
pageCursor -= PAGE_SIZE;
}
}
/* ────────────────────── 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: BUSL-1.1
pragma solidity 0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ERC165Checker} from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {LPFeeLibrary} from "@uniswap/v4-core/src/libraries/LPFeeLibrary.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {IPositionManager} from "@uniswap/v4-periphery/src/interfaces/IPositionManager.sol";
import {ActionConstants} from "@uniswap/v4-periphery/src/libraries/ActionConstants.sol";
import {LiquidityAmounts} from "@uniswap/v4-periphery/src/libraries/LiquidityAmounts.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import {BlockNumberish} from "blocknumberish/src/BlockNumberish.sol";
import {SelfInitializerHook} from "ll/periphery/hooks/SelfInitializerHook.sol";
import {IDistributionContract} from "ll/interfaces/IDistributionContract.sol";
import {IDistributionStrategy} from "ll/interfaces/IDistributionStrategy.sol";
import {
ILBPInitializer,
LBPInitializationParams,
ILBP_INITIALIZER_INTERFACE_ID
} from "ll/interfaces/ILBPInitializer.sol";
import {ILBPStrategyBase} from "ll/interfaces/ILBPStrategyBase.sol";
import {MigrationData} from "ll/types/MigrationData.sol";
import {MigratorParameters} from "ll/types/MigratorParameters.sol";
import {BasePositionParams, FullRangeParams} from "ll/types/PositionTypes.sol";
import {Plan, StrategyPlanner} from "ll/libraries/StrategyPlanner.sol";
import {TokenDistribution} from "ll/libraries/TokenDistribution.sol";
import {TokenPricing} from "ll/libraries/TokenPricing.sol";
/// @title LBPStrategyBasic
/// @notice Basic Strategy to distribute tokens and raise funds from an initializer to a v4 pool
/// @custom:security-contact [email protected]
contract LBPStrategyBasic is ILBPStrategyBase, SelfInitializerHook, BlockNumberish {
using CurrencyLibrary for Currency;
using StrategyPlanner for *;
using TokenDistribution for uint128;
using TokenPricing for uint256;
/// @notice The token that is being distributed
address public immutable token;
/// @notice The currency that the initializer raised funds in
address public immutable currency;
/// @notice The LP fee that the v4 pool will use expressed in hundredths of a bip (1e6 = 100%)
uint24 public immutable poolLPFee;
/// @notice The tick spacing that the v4 pool will use
int24 public immutable poolTickSpacing;
/// @notice The supply of the token that was sent to this contract to be distributed
uint128 public immutable totalSupply;
/// @notice The remaining supply of the token that was not sent to the initializer
uint128 public immutable reserveTokenAmount;
/// @notice The maximum amount of currency that can be used to mint the initial liquidity position
uint128 public immutable maxCurrencyAmountForLP;
/// @notice The address that will receive the position
address public immutable positionRecipient;
/// @notice The block number at which migration is allowed
uint64 public immutable migrationBlock;
/// @notice The initializer factory that will be used to create the initializer
address public immutable initializerFactory;
/// @notice The operator that can sweep currency and tokens from the pool after sweepBlock
address public immutable operator;
/// @notice The block number at which the operator can sweep currency and tokens from the pool
uint64 public immutable sweepBlock;
/// @notice The position manager that will be used to create the position
IPositionManager public immutable positionManager;
/// @notice The initializer of the pool
ILBPInitializer public initializer;
/// @notice The initializer parameters used to initialize the initializer via the factory
bytes public initializerParameters;
constructor(
address _token,
uint128 _totalSupply,
MigratorParameters memory _migratorParams,
bytes memory _initializerParams,
IPositionManager _positionManager,
IPoolManager _poolManager
) SelfInitializerHook(_poolManager) {
_validateMigratorParams(_totalSupply, _migratorParams);
initializerParameters = _initializerParams;
token = _token;
currency = _migratorParams.currency;
totalSupply = _totalSupply;
// Calculate tokens reserved for liquidity by subtracting tokens allocated for initializer
// e.g. if tokenSplit = 5e6 (50%), then half goes to initializer and half is reserved
reserveTokenAmount = _totalSupply.calculateReserveSupply(_migratorParams.tokenSplit);
maxCurrencyAmountForLP = _migratorParams.maxCurrencyAmountForLP;
positionManager = _positionManager;
positionRecipient = _migratorParams.positionRecipient;
migrationBlock = _migratorParams.migrationBlock;
initializerFactory = _migratorParams.initializerFactory;
poolLPFee = _migratorParams.poolLPFee;
poolTickSpacing = _migratorParams.poolTickSpacing;
operator = _migratorParams.operator;
sweepBlock = _migratorParams.sweepBlock;
}
/// @notice Gets the address of the token that will be used to create the pool
/// @return The address of the token that will be used to create the pool
function _getPoolToken() internal view virtual returns (address) {
return token;
}
/// @inheritdoc IDistributionContract
function onTokensReceived() external {
if (IERC20(token).balanceOf(address(this)) < totalSupply) {
revert InvalidAmountReceived(totalSupply, IERC20(token).balanceOf(address(this)));
}
if (address(initializer) != address(0)) {
revert InitializerAlreadyCreated();
}
// Calculate the supply of tokens to be distributed to the initializer
uint128 supply = totalSupply - reserveTokenAmount;
// Deploy the initializer contract via factory
ILBPInitializer _initializer = ILBPInitializer(
address(
IDistributionStrategy(initializerFactory)
.initializeDistribution(token, supply, initializerParameters, bytes32(0))
)
);
_validateInitializerParams(_initializer);
if (!ERC165Checker.supportsInterface(address(_initializer), ILBP_INITIALIZER_INTERFACE_ID)) {
revert InitializerMustImplementInterface(address(_initializer));
}
// Transfer the tokens to the initializer contract
Currency.wrap(token).transfer(address(_initializer), supply);
initializer = _initializer;
_initializer.onTokensReceived();
emit InitializerCreated(address(_initializer));
}
/// @inheritdoc ILBPStrategyBase
function migrate() external {
LBPInitializationParams memory lbpParams = initializer.lbpInitializationParams();
_validateMigration(lbpParams);
MigrationData memory data = _prepareMigrationData(lbpParams);
PoolKey memory key = _initializePool(data);
bytes memory plan = _createPositionPlan(data);
_transferAssetsAndExecutePlan(data, plan);
emit Migrated(key, data.sqrtPriceX96);
}
/// @inheritdoc ILBPStrategyBase
function sweepToken() external {
if (_getBlockNumberish() < sweepBlock) revert SweepNotAllowed(sweepBlock, _getBlockNumberish());
if (msg.sender != operator) revert NotOperator(msg.sender, operator);
uint256 tokenBalance = Currency.wrap(token).balanceOf(address(this));
if (tokenBalance > 0) {
Currency.wrap(token).transfer(operator, tokenBalance);
emit TokensSwept(operator, tokenBalance);
}
}
/// @inheritdoc ILBPStrategyBase
function sweepCurrency() external {
if (_getBlockNumberish() < sweepBlock) revert SweepNotAllowed(sweepBlock, _getBlockNumberish());
if (msg.sender != operator) revert NotOperator(msg.sender, operator);
uint256 currencyBalance = Currency.wrap(currency).balanceOf(address(this));
if (currencyBalance > 0) {
Currency.wrap(currency).transfer(operator, currencyBalance);
emit CurrencySwept(operator, currencyBalance);
}
}
/// @notice Returns true if the currency is currency0 of the pool
function _currencyIsCurrency0() internal view returns (bool) {
return currency < _getPoolToken();
}
/// @notice Get the currency0 of the pool
function _currency0() internal view returns (Currency) {
return Currency.wrap(_currencyIsCurrency0() ? currency : _getPoolToken());
}
/// @notice Get the currency1 of the pool
function _currency1() internal view returns (Currency) {
return Currency.wrap(_currencyIsCurrency0() ? _getPoolToken() : currency);
}
/// @notice Validates the migrator parameters and reverts if any are invalid. Continues if all are valid
/// @param _totalSupply The total supply of the token that was sent to this contract to be distributed
/// @param _migratorParams The migrator parameters that will be used to create the v4 pool and position
function _validateMigratorParams(uint128 _totalSupply, MigratorParameters memory _migratorParams) internal pure {
// sweep block validation (cannot be before or equal to the migration block)
if (_migratorParams.sweepBlock <= _migratorParams.migrationBlock) {
revert InvalidSweepBlock(_migratorParams.sweepBlock, _migratorParams.migrationBlock);
}
// max currency amount for LP validation cannot be zero
else if (_migratorParams.maxCurrencyAmountForLP == 0) {
revert MaxCurrencyAmountForLPIsZero();
}
// token split validation (cannot be greater than or equal to 100%)
else if (_migratorParams.tokenSplit >= TokenDistribution.MAX_TOKEN_SPLIT) {
revert TokenSplitTooHigh(_migratorParams.tokenSplit, TokenDistribution.MAX_TOKEN_SPLIT);
}
// tick spacing validation (cannot be greater than the v4 max tick spacing or less than the v4 min tick spacing)
else if (
_migratorParams.poolTickSpacing > TickMath.MAX_TICK_SPACING
|| _migratorParams.poolTickSpacing < TickMath.MIN_TICK_SPACING
) {
revert InvalidTickSpacing(
_migratorParams.poolTickSpacing, TickMath.MIN_TICK_SPACING, TickMath.MAX_TICK_SPACING
);
}
// fee validation (cannot be greater than the v4 max fee)
else if (_migratorParams.poolLPFee > LPFeeLibrary.MAX_LP_FEE) {
revert InvalidFee(_migratorParams.poolLPFee, LPFeeLibrary.MAX_LP_FEE);
}
// position recipient validation (cannot be zero address, address(1), or address(2) which are reserved addresses on the position manager)
else if (
_migratorParams.positionRecipient == address(0)
|| _migratorParams.positionRecipient == ActionConstants.MSG_SENDER
|| _migratorParams.positionRecipient == ActionConstants.ADDRESS_THIS
) {
revert InvalidPositionRecipient(_migratorParams.positionRecipient);
}
// Require the split of tokens to the initializer to be greater than zero
else if (_totalSupply.calculateTokenSplit(_migratorParams.tokenSplit) == 0) {
revert InitializerTokenSplitIsZero();
}
}
/// @notice Validates that the deployed initializer parameters are valid for this strategy implementation
/// @dev MUST be called in the same transaction as the deployment of the initializer
function _validateInitializerParams(ILBPInitializer _initializer) internal view virtual {
// Require this contract to receive the raised currency from the initializer
if (_initializer.fundsRecipient() != address(this)) {
revert InvalidFundsRecipient(_initializer.fundsRecipient(), address(this));
}
// Require `migrationBlock` to be after the conclusion of the initialization step
else if (_initializer.endBlock() >= migrationBlock) {
revert InvalidEndBlock(_initializer.endBlock(), migrationBlock);
}
// Require the currency used by the initializer to be the same as the currency used by this strategy
else if (_initializer.currency() != currency) {
revert InvalidCurrency(_initializer.currency(), currency);
}
}
/// @notice Validates migration timing and currency balance
/// @param _lbpParams The LBP initialization parameters
function _validateMigration(LBPInitializationParams memory _lbpParams) internal view {
if (_getBlockNumberish() < migrationBlock) {
revert MigrationNotAllowed(migrationBlock, _getBlockNumberish());
}
uint256 currencyAmount = _lbpParams.currencyRaised;
// cannot create a v4 pool with more than type(uint128).max currency amount
if (currencyAmount > type(uint128).max) {
revert CurrencyAmountTooHigh(currencyAmount, type(uint128).max);
}
// cannot create a v4 pool with no currency raised
if (currencyAmount == 0) {
revert NoCurrencyRaised();
}
if (Currency.wrap(currency).balanceOf(address(this)) < currencyAmount) {
revert InsufficientCurrency(currencyAmount, Currency.wrap(currency).balanceOf(address(this)));
}
}
/// @notice Prepares all migration data including prices, amounts, and liquidity calculations
/// @param _lbpParams The LBP initialization parameters
/// @return data MigrationData struct containing all calculated values
function _prepareMigrationData(LBPInitializationParams memory _lbpParams)
internal
view
returns (MigrationData memory data)
{
// Both currencyRaised and maxCurrencyAmountForLP are validated to be less than or equal to type(uint128).max
uint128 currencyAmount = uint128(FixedPointMathLib.min(_lbpParams.currencyRaised, maxCurrencyAmountForLP));
bool currencyIsCurrency0 = _currencyIsCurrency0();
uint256 priceX192 = _lbpParams.initialPriceX96.convertToPriceX192(currencyIsCurrency0);
data.sqrtPriceX96 = priceX192.convertToSqrtPriceX96();
(data.fullRangeTokenAmount, data.fullRangeCurrencyAmount) =
priceX192.calculateAmounts(currencyAmount, currencyIsCurrency0, reserveTokenAmount);
data.leftoverCurrency = currencyAmount - data.fullRangeCurrencyAmount;
data.liquidity = LiquidityAmounts.getLiquidityForAmounts(
data.sqrtPriceX96,
TickMath.getSqrtPriceAtTick(TickMath.minUsableTick(poolTickSpacing)),
TickMath.getSqrtPriceAtTick(TickMath.maxUsableTick(poolTickSpacing)),
currencyIsCurrency0 ? data.fullRangeCurrencyAmount : data.fullRangeTokenAmount,
currencyIsCurrency0 ? data.fullRangeTokenAmount : data.fullRangeCurrencyAmount
);
return data;
}
/// @notice Initializes the pool with the calculated price
/// @param data Migration data containing the sqrt price
/// @return key The pool key for the initialized pool
function _initializePool(MigrationData memory data) internal virtual returns (PoolKey memory key) {
key = PoolKey({
currency0: _currency0(),
currency1: _currency1(),
fee: poolLPFee,
tickSpacing: poolTickSpacing,
hooks: IHooks(address(this))
});
// Initialize the pool with the returned initial price
// Will revert if:
// - Pool is already initialized
// - Initial price is not set (sqrtPriceX96 = 0)
poolManager.initialize(key, data.sqrtPriceX96);
return key;
}
/// @notice Transfers assets to position manager and executes the position plan
/// @param data Migration data with amounts and flags
/// @param plan The encoded position plan to execute
function _transferAssetsAndExecutePlan(MigrationData memory data, bytes memory plan) internal virtual {
// Transfer tokens to position manager
Currency.wrap(token).transfer(address(positionManager), _getTokenTransferAmount(data));
uint128 currencyTransferAmount = _getCurrencyTransferAmount(data);
if (Currency.wrap(currency).isAddressZero()) {
// Native currency: send as value with modifyLiquidities call
positionManager.modifyLiquidities{value: currencyTransferAmount}(plan, block.timestamp);
} else {
// Non-native currency: transfer first, then call modifyLiquidities
Currency.wrap(currency).transfer(address(positionManager), currencyTransferAmount);
positionManager.modifyLiquidities(plan, block.timestamp);
}
}
/// @notice Creates the base position parameters
/// @param data Migration data with all necessary parameters
/// @return baseParams The base position parameters
function _basePositionParams(MigrationData memory data) internal view virtual returns (BasePositionParams memory) {
return BasePositionParams({
currency: currency,
poolToken: _getPoolToken(),
poolLPFee: poolLPFee,
poolTickSpacing: poolTickSpacing,
initialSqrtPriceX96: data.sqrtPriceX96,
liquidity: data.liquidity,
positionRecipient: positionRecipient,
hooks: IHooks(address(this))
});
}
/// @notice Creates the position plan based on migration data
/// @param data Migration data with all necessary parameters
/// @return plan The encoded position plan
function _createPositionPlan(MigrationData memory data) internal view virtual returns (bytes memory plan) {
Plan memory positionPlan = StrategyPlanner.init();
BasePositionParams memory baseParams = _basePositionParams(data);
positionPlan = positionPlan.planFullRangePosition(
baseParams,
FullRangeParams({tokenAmount: data.fullRangeTokenAmount, currencyAmount: data.fullRangeCurrencyAmount})
);
positionPlan = positionPlan.planTakePair(baseParams);
return positionPlan.encode();
}
/// @notice Calculates the amount of tokens to transfer
/// @param data Migration data
/// @return The amount of tokens to transfer to the position manager
function _getTokenTransferAmount(MigrationData memory data) internal view virtual returns (uint128) {
return data.fullRangeTokenAmount;
}
/// @notice Calculates the amount of currency to transfer
/// @param data Migration data
/// @return The amount of currency to transfer to the position manager
function _getCurrencyTransferAmount(MigrationData memory data) internal view virtual returns (uint128) {
return data.fullRangeCurrencyAmount;
}
/// @notice Receives native currency
receive() external payable {}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title MigrationData
/// @notice Data for the migration of the pool
struct MigrationData {
uint160 sqrtPriceX96; // the initial sqrt price of the pool
uint128 fullRangeTokenAmount; // the initial token amount for the full range position
uint128 fullRangeCurrencyAmount; // the initial currency amount for the full range position
uint128 leftoverCurrency; // the leftover currency (if any) after creating the full range position
uint128 liquidity; // the liquidity for the full range position
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {ILBPStrategyBasic} from "./ILBPStrategyBasic.sol";
import {IMultiPositionManager} from "../../MultiPositionManager/interfaces/IMultiPositionManager.sol";
import {IOrderBookFactory} from "../../LimitOrderBook/interfaces/IOrderBookFactory.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
/// @title ISuperchainLBPStrategy
/// @notice Interface for SuperchainLBPStrategy that migrates auction liquidity to MultiPositionManager
interface ISuperchainLBPStrategy is ILBPStrategyBasic {
/// @notice Emitted when MultiPositionManager is deployed and liquidity is migrated
/// @param mpm The address of the deployed MultiPositionManager
/// @param shares The number of shares minted to the position recipient
event MPMDeployed(address indexed mpm, uint256 shares);
event MigrationPoolCreated(PoolKey poolKey, uint160 sqrtPriceX96, address mpm);
/// @notice Error thrown when OrderBookFactory address is zero
error InvalidOrderBookFactory();
/// @notice Error thrown when strategy address is zero
error InvalidStrategy();
/// @notice Gets the OrderBookFactory used to deploy pools and MPMs
/// @return The OrderBookFactory contract
function orderBookFactory() external view returns (IOrderBookFactory);
/// @notice Gets the strategy contract address
/// @return The strategy contract address
function strategy() external view returns (address);
/// @notice Gets the encoded strategy parameters
/// @return The encoded strategy parameters
function strategyData() external view returns (bytes memory);
}// 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.24;
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {CallOption} from "./CallOption.sol";
/// @title CallOptionFactory
/// @notice Holds option allocation and deploys per-member call options sharing a global strike.
contract CallOptionFactory is AccessControl {
using SafeERC20 for IERC20;
bytes32 public constant SCHEDULER_ROLE = keccak256("SCHEDULER_ROLE");
struct OptionInfo {
address option;
address beneficiary;
uint256 amount;
uint256 vestingEnd;
uint256 createdAt;
}
address public immutable token;
address public immutable treasury;
address public immutable buybackAddress;
address public immutable strategySetter;
address public strategy;
bool public strategySet;
uint160 public strikePriceX96;
bool public strikeSet;
OptionInfo[] internal _allOptions;
mapping(address => uint256[]) internal _beneficiaryToIndices;
event StrategySet(address indexed strategy);
event StrikeSet(uint160 sqrtPriceX96);
event OptionCreated(address indexed option, address indexed beneficiary, uint256 amount, uint256 vestingEnd);
error InvalidAddress();
error InvalidAmount();
error Unauthorized();
error StrategyAlreadySet();
error StrikeAlreadySet();
error InsufficientBalance();
constructor(address _token, address _treasury, address _buybackAddress, address _strategySetter, address admin) {
if (_token == address(0) || _treasury == address(0) || _buybackAddress == address(0)) revert InvalidAddress();
if (_strategySetter == address(0) || admin == address(0)) revert InvalidAddress();
token = _token;
treasury = _treasury;
buybackAddress = _buybackAddress;
strategySetter = _strategySetter;
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_grantRole(SCHEDULER_ROLE, admin);
}
function setStrategy(address newStrategy) external {
if (msg.sender != strategySetter) revert Unauthorized();
if (newStrategy == address(0)) revert InvalidAddress();
if (strategySet) revert StrategyAlreadySet();
strategy = newStrategy;
strategySet = true;
emit StrategySet(newStrategy);
}
function setStrike(uint160 sqrtPriceX96) external {
if (!strategySet || msg.sender != strategy) revert Unauthorized();
if (strikeSet) revert StrikeAlreadySet();
if (sqrtPriceX96 == 0) revert InvalidAmount();
strikePriceX96 = sqrtPriceX96;
strikeSet = true;
emit StrikeSet(sqrtPriceX96);
}
function createOption(address beneficiary, uint256 amount, uint256 vestingEnd)
external
onlyRole(SCHEDULER_ROLE)
returns (address option)
{
if (beneficiary == address(0)) revert InvalidAddress();
if (amount == 0) revert InvalidAmount();
if (IERC20(token).balanceOf(address(this)) < amount) revert InsufficientBalance();
option = address(
new CallOption(token, beneficiary, amount, buybackAddress, treasury, address(this), vestingEnd)
);
IERC20(token).safeTransfer(option, amount);
_allOptions.push(
OptionInfo({
option: option,
beneficiary: beneficiary,
amount: amount,
vestingEnd: vestingEnd,
createdAt: block.timestamp
})
);
_beneficiaryToIndices[beneficiary].push(_allOptions.length - 1);
emit OptionCreated(option, beneficiary, amount, vestingEnd);
}
function createOptions(
address[] calldata beneficiaries,
uint256[] calldata amounts,
uint256[] calldata vestingEnds
) external onlyRole(SCHEDULER_ROLE) returns (address[] memory options) {
uint256 count = beneficiaries.length;
if (count == 0) revert InvalidAmount();
if (amounts.length != count || vestingEnds.length != count) revert InvalidAmount();
options = new address[](count);
for (uint256 i = 0; i < count; i++) {
address beneficiary = beneficiaries[i];
uint256 amount = amounts[i];
uint256 vestingEnd = vestingEnds[i];
if (beneficiary == address(0)) revert InvalidAddress();
if (amount == 0) revert InvalidAmount();
if (IERC20(token).balanceOf(address(this)) < amount) revert InsufficientBalance();
address option = address(
new CallOption(token, beneficiary, amount, buybackAddress, treasury, address(this), vestingEnd)
);
IERC20(token).safeTransfer(option, amount);
_allOptions.push(
OptionInfo({
option: option,
beneficiary: beneficiary,
amount: amount,
vestingEnd: vestingEnd,
createdAt: block.timestamp
})
);
_beneficiaryToIndices[beneficiary].push(_allOptions.length - 1);
options[i] = option;
emit OptionCreated(option, beneficiary, amount, vestingEnd);
}
}
function getOptionsPaginated(uint256 offset, uint256 limit)
external
view
returns (OptionInfo[] memory options, uint256 totalCount)
{
totalCount = _allOptions.length;
if (offset == 0 && limit == 0) {
options = _allOptions;
return (options, totalCount);
}
if (limit == 0) limit = totalCount;
if (offset >= totalCount) return (new OptionInfo[](0), totalCount);
uint256 count = (offset + limit > totalCount) ? (totalCount - offset) : limit;
options = new OptionInfo[](count);
for (uint256 i = 0; i < count; i++) {
options[i] = _allOptions[offset + i];
}
}
function getOptionsByBeneficiaryPaginated(address beneficiary, uint256 offset, uint256 limit)
external
view
returns (OptionInfo[] memory options, uint256 totalCount)
{
uint256[] storage indices = _beneficiaryToIndices[beneficiary];
totalCount = indices.length;
if (offset == 0 && limit == 0) {
options = new OptionInfo[](totalCount);
for (uint256 i = 0; i < totalCount; i++) {
options[i] = _allOptions[indices[i]];
}
return (options, totalCount);
}
if (limit == 0) limit = totalCount;
if (offset >= totalCount) return (new OptionInfo[](0), totalCount);
uint256 count = (offset + limit > totalCount) ? (totalCount - offset) : limit;
options = new OptionInfo[](count);
for (uint256 i = 0; i < count; i++) {
options[i] = _allOptions[indices[offset + i]];
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {BalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
interface ISwapRouter {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
bool zeroForOne,
PoolKey calldata poolKey,
bytes calldata hookData,
address receiver,
uint256 deadline
) external payable returns (BalanceDelta balanceDelta);
}
/// @title Buyback
/// @notice Executes ETH buybacks and burns tokens
contract Buyback is AccessControl {
using SafeERC20 for IERC20;
bytes32 public constant BUYBACK_EXECUTOR_ROLE = keccak256("BUYBACK_EXECUTOR_ROLE");
IERC20 public immutable token;
address public strategy;
bool public strategySet;
address public immutable strategySetter;
address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;
address public router;
PoolKey public poolKey;
bool public poolKeySet;
uint256 public totalETHUsed;
uint256 public totalTokenBurned;
event PoolKeySet();
event RouterUpdated(address indexed newRouter);
event BuybackExecuted(uint256 ethUsed, uint256 tokensBurned, uint256 totalETHUsed, uint256 totalTokenBurned);
error InvalidAddress();
error PoolKeyAlreadySet();
error PoolKeyNotSet();
error InvalidPercentage();
error InsufficientBalance();
error SwapFailed();
constructor(address admin, address _token, address _router, address _strategySetter) {
if (admin == address(0) || _token == address(0) || _router == address(0)) {
revert InvalidAddress();
}
token = IERC20(_token);
router = _router;
strategySetter = _strategySetter;
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_grantRole(BUYBACK_EXECUTOR_ROLE, admin);
}
function setStrategy(address newStrategy) external {
if (msg.sender != strategySetter) revert InvalidAddress();
if (newStrategy == address(0)) revert InvalidAddress();
if (strategySet) revert InvalidAddress();
strategy = newStrategy;
strategySet = true;
}
function setPoolKey(PoolKey calldata key) external {
if (msg.sender != strategy) revert InvalidAddress();
if (poolKeySet) revert PoolKeyAlreadySet();
poolKey = key;
poolKeySet = true;
emit PoolKeySet();
}
function setRouter(address newRouter) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (newRouter == address(0)) revert InvalidAddress();
router = newRouter;
emit RouterUpdated(newRouter);
}
function executeBuyback(uint24 percentageToUse, uint256 amountOutMin) external onlyRole(BUYBACK_EXECUTOR_ROLE) {
if (!poolKeySet) revert PoolKeyNotSet();
if (percentageToUse == 0 || percentageToUse > 10000) revert InvalidPercentage();
uint256 contractBalance = address(this).balance;
if (contractBalance == 0) revert InsufficientBalance();
uint256 ethToUse = (contractBalance * percentageToUse) / 10000;
if (ethToUse == 0) revert InsufficientBalance();
try ISwapRouter(router).swapExactTokensForTokens{value: ethToUse}(
ethToUse,
amountOutMin,
true,
poolKey,
"",
address(this),
block.timestamp + 1000
) {
uint256 tokenBalance = token.balanceOf(address(this));
if (tokenBalance == 0) revert SwapFailed();
token.safeTransfer(BURN_ADDRESS, tokenBalance);
totalETHUsed += ethToUse;
totalTokenBurned += tokenBalance;
emit BuybackExecuted(ethToUse, tokenBalance, totalETHUsed, totalTokenBurned);
} catch {
revert SwapFailed();
}
}
receive() external payable {}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IDistributionContract} from "./IDistributionContract.sol";
/// @title IDistributionStrategy
/// @notice Interface for token distribution strategies.
interface IDistributionStrategy {
/// @notice Emitted when a distribution is initialized
/// @param distributionContract The contract that was created that will handle or manage the distribution.
/// @param token The token that is being distributed.
/// @param totalSupply The supply of the token that is being distributed.
event DistributionInitialized(address indexed distributionContract, address indexed token, uint256 totalSupply);
/// @notice Error thrown when the amount to be distributed is invalid
/// @param amount The invalid amount
/// @param maxAmount The maximum valid amount to be distributed
error InvalidAmount(uint256 amount, uint256 maxAmount);
/// @notice Initialize a distribution of tokens under this strategy.
/// @dev Contracts can choose to deploy an instance with a factory-model or handle all distributions within the
/// implementing contract. For some strategies this function will handle the entire distribution, for others it
/// could merely set up initial state and provide additional entrypoints to handle the distribution logic.
/// @param token The token that is being distributed.
/// @param totalSupply The supply of the token that is being distributed.
/// @param configData Arbitrary, strategy-specific parameters.
/// @param salt The optional salt for deterministic deployment.
/// @return distributionContract The contract that will handle or manage the distribution.
/// (Could be `address(this)` if the strategy is handled in-place, or a newly deployed instance).
function initializeDistribution(address token, uint256 totalSupply, bytes calldata configData, bytes32 salt)
external
returns (IDistributionContract distributionContract);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {PositionInfo} from "../libraries/PositionInfoLibrary.sol";
/// @title ISubscriber
/// @notice Interface that a Subscriber contract should implement to receive updates from the v4 position manager
interface ISubscriber {
/// @notice Called when a position subscribes to this subscriber contract
/// @param tokenId the token ID of the position
/// @param data additional data passed in by the caller
function notifySubscribe(uint256 tokenId, bytes memory data) external;
/// @notice Called when a position unsubscribes from the subscriber
/// @dev This call's gas is capped at `unsubscribeGasLimit` (set at deployment)
/// @dev Because of EIP-150, solidity may only allocate 63/64 of gasleft()
/// @param tokenId the token ID of the position
function notifyUnsubscribe(uint256 tokenId) external;
/// @notice Called when a position is burned
/// @param tokenId the token ID of the position
/// @param owner the current owner of the tokenId
/// @param info information about the position
/// @param liquidity the amount of liquidity decreased in the position, may be 0
/// @param feesAccrued the fees accrued by the position if liquidity was decreased
function notifyBurn(uint256 tokenId, address owner, PositionInfo info, uint256 liquidity, BalanceDelta feesAccrued)
external;
/// @notice Called when a position modifies its liquidity or collects fees
/// @param tokenId the token ID of the position
/// @param liquidityChange the change in liquidity on the underlying position
/// @param feesAccrued the fees to be collected from the position as a result of the modifyLiquidity call
/// @dev Note that feesAccrued can be artificially inflated by a malicious user
/// Pools with a single liquidity position can inflate feeGrowthGlobal (and consequently feesAccrued) by donating to themselves;
/// atomically donating and collecting fees within the same unlockCallback may further inflate feeGrowthGlobal/feesAccrued
function notifyModifyLiquidity(uint256 tokenId, int256 liquidityChange, BalanceDelta feesAccrued) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IEIP712} from "./IEIP712.sol";
/// @title AllowanceTransfer
/// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
/// @dev Requires user's token approval on the Permit2 contract
interface IAllowanceTransfer is IEIP712 {
/// @notice Thrown when an allowance on a token has expired.
/// @param deadline The timestamp at which the allowed amount is no longer valid
error AllowanceExpired(uint256 deadline);
/// @notice Thrown when an allowance on a token has been depleted.
/// @param amount The maximum amount allowed
error InsufficientAllowance(uint256 amount);
/// @notice Thrown when too many nonces are invalidated.
error ExcessiveInvalidation();
/// @notice Emits an event when the owner successfully invalidates an ordered nonce.
event NonceInvalidation(
address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce
);
/// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
event Approval(
address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration
);
/// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
event Permit(
address indexed owner,
address indexed token,
address indexed spender,
uint160 amount,
uint48 expiration,
uint48 nonce
);
/// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
event Lockdown(address indexed owner, address token, address spender);
/// @notice The permit data for a token
struct PermitDetails {
// ERC20 token address
address token;
// the maximum amount allowed to spend
uint160 amount;
// timestamp at which a spender's token allowances become invalid
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice The permit message signed for a single token allowance
struct PermitSingle {
// the permit data for a single token alownce
PermitDetails details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The permit message signed for multiple token allowances
struct PermitBatch {
// the permit data for multiple token allowances
PermitDetails[] details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The saved permissions
/// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
/// @dev Setting amount to type(uint160).max sets an unlimited approval
struct PackedAllowance {
// amount allowed
uint160 amount;
// permission expiry
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice A token spender pair.
struct TokenSpenderPair {
// the token the spender is approved
address token;
// the spender address
address spender;
}
/// @notice Details for a token transfer.
struct AllowanceTransferDetails {
// the owner of the token
address from;
// the recipient of the token
address to;
// the amount of the token
uint160 amount;
// the token to be transferred
address token;
}
/// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
/// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
/// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
function allowance(address user, address token, address spender)
external
view
returns (uint160 amount, uint48 expiration, uint48 nonce);
/// @notice Approves the spender to use up to amount of the specified token up until the expiration
/// @param token The token to approve
/// @param spender The spender address to approve
/// @param amount The approved amount of the token
/// @param expiration The timestamp at which the approval is no longer valid
/// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
/// @dev Setting amount to type(uint160).max sets an unlimited approval
function approve(address token, address spender, uint160 amount, uint48 expiration) external;
/// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitSingle Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;
/// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitBatch Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external;
/// @notice Transfer approved tokens from one address to another
/// @param from The address to transfer from
/// @param to The address of the recipient
/// @param amount The amount of the token to transfer
/// @param token The token address to transfer
/// @dev Requires the from address to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(address from, address to, uint160 amount, address token) external;
/// @notice Transfer approved tokens in a batch
/// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
/// @dev Requires the from addresses to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external;
/// @notice Enables performing a "lockdown" of the sender's Permit2 identity
/// by batch revoking approvals
/// @param approvals Array of approvals to revoke.
function lockdown(TokenSpenderPair[] calldata approvals) external;
/// @notice Invalidate nonces for a given (token, spender) pair
/// @param token The token to invalidate nonces for
/// @param spender The spender to invalidate nonces for
/// @param newNonce The new nonce to set. Invalidates all nonces less than it.
/// @dev Can't invalidate more than 2**16 nonces per transaction.
function invalidateNonces(address token, address spender, uint48 newNonce) external;
}// 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: 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;
// 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
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.3.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC-165 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 to signal 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. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
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.1.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 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 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.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}// 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,
address recipient
) external payable returns (CreateOrderResult memory);
function createScaleOrders(
bool isToken0,
int24 bottomTick,
int24 topTick,
uint256 totalAmount,
uint256 totalOrders,
uint256 sizeSkew,
PoolKey calldata key,
address recipient
) 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 {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: MIT
// OpenZeppelin Contracts (last updated v5.1.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 EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract 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.3.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
import {Arrays} from "../Arrays.sol";
/**
* @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.
* - Set can be cleared (all elements removed) in O(n).
*
* ```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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function _clear(Set storage set) private {
uint256 len = _length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(Bytes32Set storage set) internal {
_clear(set._inner);
}
/**
* @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;
assembly ("memory-safe") {
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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(AddressSet storage set) internal {
_clear(set._inner);
}
/**
* @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;
assembly ("memory-safe") {
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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(UintSet storage set) internal {
_clear(set._inner);
}
/**
* @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;
assembly ("memory-safe") {
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.3.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 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
/// @param sqrtPriceX96 Current sqrt price from the pool slot0
/// @return bottomTick The calculated lower tick boundary
/// @return topTick The calculated upper tick boundary
function getValidTickRange(
int24 currentTick,
int24 targetTick,
int24 tickSpacing,
bool isToken0,
uint160 sqrtPriceX96
) 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);
if (isToken0 && currentTick % tickSpacing == 0) {
if (sqrtPriceX96 == TickMath.getSqrtPriceAtTick(currentTick)) {
roundedCurrentTick = currentTick;
}
}
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 OR Apache-2.0
pragma solidity >=0.8.13 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = 0x000000000000000000636F6e736F6c652e6c6f67;
function _sendLogPayloadImplementation(bytes memory payload) internal view {
address consoleAddress = CONSOLE_ADDRESS;
assembly ("memory-safe") {
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;
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;
/// @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 v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../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.
*
* By default, the owner account will be the one that deploys the contract. 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 {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @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 {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_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);
}
/**
* @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[49] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../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, IAccessControlUpgradeable, ERC165Upgradeable {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
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(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(account),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @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 override 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 override 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 override 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 `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @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 Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
/**
* @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[49] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```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 Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.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.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @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 ERC1967) 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 ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @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() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC1822 {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 override notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeTo(address newImplementation) public virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
}
/**
* @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, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @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[50] private __gap;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId} from "v4-core/types/PoolId.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 {TickInfo, PopulatedTick} from "./LimitOrderLensTickTypes.sol";
library LimitOrderLensTickLogic {
function getTickInfosAroundCurrent(
IPoolManager poolManager,
PoolId poolId,
PoolKey memory poolKey,
uint24 numTicks
) external view returns (int24 currentTick, uint160 sqrtPriceX96, TickInfo[] memory tickInfos) {
(sqrtPriceX96, currentTick, , ) = StateLibrary.getSlot0(poolManager, poolId);
(int24 startTick, int24 endTick) = _calculateTickRange(currentTick, poolKey.tickSpacing, numTicks);
int24 broadStartTick = TickMath.minUsableTick(poolKey.tickSpacing);
PopulatedTick[] memory populatedTicks =
_getPopulatedTicksInRange(poolManager, poolId, poolKey.tickSpacing, broadStartTick, endTick);
tickInfos = _calculateOrderbookLiquidity(
populatedTicks, startTick, endTick, poolKey.tickSpacing, currentTick, sqrtPriceX96
);
return (currentTick, sqrtPriceX96, tickInfos);
}
function _calculateTickRange(
int24 currentTick,
int24 tickSpacing,
uint24 numTicks
) private 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);
}
function _getPopulatedTicksInRange(
IPoolManager poolManager,
PoolId poolId,
int24 tickSpacing,
int24 startTick,
int24 endTick
) private view returns (PopulatedTick[] memory populatedTicks) {
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) {
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);
}
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) {
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;
}
function _calculateOrderbookLiquidity(
PopulatedTick[] memory populatedTicks,
int24 startTick,
int24 endTick,
int24 tickSpacing,
int24 currentTick,
uint160 sqrtPriceX96
) private pure returns (TickInfo[] memory tickInfos) {
uint256 totalTicks = uint256(int256((endTick - startTick) / tickSpacing)) + 1;
tickInfos = new TickInfo[](totalTicks);
for (uint256 i = 0; i < totalTicks;) {
int24 tick = startTick + int24(int256(i) * int256(tickSpacing));
uint128 liquidityAtTick = _calculateLiquidityAtTickFromPopulated(populatedTicks, tick);
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);
}
if (liquidityAtTick > 0) {
_calculateTokenAmountsFromLiquidity(
tickInfos[i], liquidityAtTick, tick, tickSpacing, currentTick, sqrtPriceX96
);
}
unchecked {
i++;
}
}
return tickInfos;
}
function _calculateLiquidityAtTickFromPopulated(
PopulatedTick[] memory populatedTicks,
int24 targetTick
) private pure returns (uint128 activeLiquidity) {
for (uint256 i = 0; i < populatedTicks.length;) {
if (populatedTicks[i].tick <= targetTick) {
int128 liquidityNet = populatedTicks[i].liquidityNet;
unchecked {
if (liquidityNet < 0) {
activeLiquidity = activeLiquidity - uint128(-liquidityNet);
} else {
activeLiquidity = activeLiquidity + uint128(liquidityNet);
}
}
}
unchecked {
i++;
}
}
return activeLiquidity;
}
function _calculateTokenAmountsFromLiquidity(
TickInfo memory tickInfo,
uint128 liquidity,
int24 tick,
int24 tickSpacing,
int24 currentTick,
uint160 sqrtPriceX96
) private pure {
uint160 sqrtPriceLowerX96 = TickMath.getSqrtPriceAtTick(tick);
uint160 sqrtPriceUpperX96 = TickMath.getSqrtPriceAtTick(tick + tickSpacing);
if (currentTick < tick) {
tickInfo.token0Amount =
LiquidityAmounts.getAmount0ForLiquidity(sqrtPriceLowerX96, sqrtPriceUpperX96, liquidity);
} else if (currentTick >= tick + tickSpacing) {
tickInfo.token1Amount =
LiquidityAmounts.getAmount1ForLiquidity(sqrtPriceLowerX96, sqrtPriceUpperX96, liquidity);
} else {
(tickInfo.token0Amount, tickInfo.token1Amount) = LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96, sqrtPriceLowerX96, sqrtPriceUpperX96, liquidity
);
}
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;
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
/// @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;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "./SafeCast.sol";
import {FullMath} from "./FullMath.sol";
import {UnsafeMath} from "./UnsafeMath.sol";
import {FixedPoint96} from "./FixedPoint96.sol";
/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
using SafeCast for uint256;
error InvalidPriceOrLiquidity();
error InvalidPrice();
error NotEnoughLiquidity();
error PriceOverflow();
/// @notice Gets the next sqrt price given a delta of currency0
/// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
/// price less in order to not send too much output.
/// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
/// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
/// @param sqrtPX96 The starting price, i.e. before accounting for the currency0 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of currency0 to add or remove from virtual reserves
/// @param add Whether to add or remove the amount of currency0
/// @return The price after adding or removing amount, depending on add
function getNextSqrtPriceFromAmount0RoundingUp(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)
internal
pure
returns (uint160)
{
// we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
if (amount == 0) return sqrtPX96;
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
if (add) {
unchecked {
uint256 product = amount * sqrtPX96;
if (product / amount == sqrtPX96) {
uint256 denominator = numerator1 + product;
if (denominator >= numerator1) {
// always fits in 160 bits
return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
}
}
}
// denominator is checked for overflow
return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount));
} else {
unchecked {
uint256 product = amount * sqrtPX96;
// if the product overflows, we know the denominator underflows
// in addition, we must check that the denominator does not underflow
// equivalent: if (product / amount != sqrtPX96 || numerator1 <= product) revert PriceOverflow();
assembly ("memory-safe") {
if iszero(
and(
eq(div(product, amount), and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
gt(numerator1, product)
)
) {
mstore(0, 0xf5c787f1) // selector for PriceOverflow()
revert(0x1c, 0x04)
}
}
uint256 denominator = numerator1 - product;
return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
}
}
}
/// @notice Gets the next sqrt price given a delta of currency1
/// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
/// price less in order to not send too much output.
/// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
/// @param sqrtPX96 The starting price, i.e., before accounting for the currency1 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of currency1 to add, or remove, from virtual reserves
/// @param add Whether to add, or remove, the amount of currency1
/// @return The price after adding or removing `amount`
function getNextSqrtPriceFromAmount1RoundingDown(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)
internal
pure
returns (uint160)
{
// if we're adding (subtracting), rounding down requires rounding the quotient down (up)
// in both cases, avoid a mulDiv for most inputs
if (add) {
uint256 quotient = (
amount <= type(uint160).max
? (amount << FixedPoint96.RESOLUTION) / liquidity
: FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
);
return (uint256(sqrtPX96) + quotient).toUint160();
} else {
uint256 quotient = (
amount <= type(uint160).max
? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
: FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
);
// equivalent: if (sqrtPX96 <= quotient) revert NotEnoughLiquidity();
assembly ("memory-safe") {
if iszero(gt(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff), quotient)) {
mstore(0, 0x4323a555) // selector for NotEnoughLiquidity()
revert(0x1c, 0x04)
}
}
// always fits 160 bits
unchecked {
return uint160(sqrtPX96 - quotient);
}
}
}
/// @notice Gets the next sqrt price given an input amount of currency0 or currency1
/// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
/// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
/// @param liquidity The amount of usable liquidity
/// @param amountIn How much of currency0, or currency1, is being swapped in
/// @param zeroForOne Whether the amount in is currency0 or currency1
/// @return uint160 The price after adding the input amount to currency0 or currency1
function getNextSqrtPriceFromInput(uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne)
internal
pure
returns (uint160)
{
// equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
assembly ("memory-safe") {
if or(
iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
) {
mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
revert(0x1c, 0x04)
}
}
// round to make sure that we don't pass the target price
return zeroForOne
? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
: getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
}
/// @notice Gets the next sqrt price given an output amount of currency0 or currency1
/// @dev Throws if price or liquidity are 0 or the next price is out of bounds
/// @param sqrtPX96 The starting price before accounting for the output amount
/// @param liquidity The amount of usable liquidity
/// @param amountOut How much of currency0, or currency1, is being swapped out
/// @param zeroForOne Whether the amount out is currency1 or currency0
/// @return uint160 The price after removing the output amount of currency0 or currency1
function getNextSqrtPriceFromOutput(uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne)
internal
pure
returns (uint160)
{
// equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
assembly ("memory-safe") {
if or(
iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
) {
mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
revert(0x1c, 0x04)
}
}
// round to make sure that we pass the target price
return zeroForOne
? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
: getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
}
/// @notice Gets the amount0 delta between two prices
/// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
/// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up or down
/// @return uint256 Amount of currency0 required to cover a position of size liquidity between the two passed prices
function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)
internal
pure
returns (uint256)
{
unchecked {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
// equivalent: if (sqrtPriceAX96 == 0) revert InvalidPrice();
assembly ("memory-safe") {
if iszero(and(sqrtPriceAX96, 0xffffffffffffffffffffffffffffffffffffffff)) {
mstore(0, 0x00bfc921) // selector for InvalidPrice()
revert(0x1c, 0x04)
}
}
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
uint256 numerator2 = sqrtPriceBX96 - sqrtPriceAX96;
return roundUp
? UnsafeMath.divRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtPriceBX96), sqrtPriceAX96)
: FullMath.mulDiv(numerator1, numerator2, sqrtPriceBX96) / sqrtPriceAX96;
}
}
/// @notice Equivalent to: `a >= b ? a - b : b - a`
function absDiff(uint160 a, uint160 b) internal pure returns (uint256 res) {
assembly ("memory-safe") {
let diff :=
sub(and(a, 0xffffffffffffffffffffffffffffffffffffffff), and(b, 0xffffffffffffffffffffffffffffffffffffffff))
// mask = 0 if a >= b else -1 (all 1s)
let mask := sar(255, diff)
// if a >= b, res = a - b = 0 ^ (a - b)
// if a < b, res = b - a = ~~(b - a) = ~(-(b - a) - 1) = ~(a - b - 1) = (-1) ^ (a - b - 1)
// either way, res = mask ^ (a - b + mask)
res := xor(mask, add(mask, diff))
}
}
/// @notice Gets the amount1 delta between two prices
/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up, or down
/// @return amount1 Amount of currency1 required to cover a position of size liquidity between the two passed prices
function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)
internal
pure
returns (uint256 amount1)
{
uint256 numerator = absDiff(sqrtPriceAX96, sqrtPriceBX96);
uint256 denominator = FixedPoint96.Q96;
uint256 _liquidity = uint256(liquidity);
/**
* Equivalent to:
* amount1 = roundUp
* ? FullMath.mulDivRoundingUp(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96)
* : FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);
* Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`.
*/
amount1 = FullMath.mulDiv(_liquidity, numerator, denominator);
assembly ("memory-safe") {
amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp))
}
}
/// @notice Helper that gets signed currency0 delta
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount0 delta
/// @return int256 Amount of currency0 corresponding to the passed liquidityDelta between the two prices
function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
internal
pure
returns (int256)
{
unchecked {
return liquidity < 0
? getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
: -getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
}
}
/// @notice Helper that gets signed currency1 delta
/// @param sqrtPriceAX96 A sqrt price
/// @param sqrtPriceBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount1 delta
/// @return int256 Amount of currency1 corresponding to the passed liquidityDelta between the two prices
function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
internal
pure
returns (int256)
{
unchecked {
return liquidity < 0
? getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
: -getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
}
}
}// 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 full-range floor position
* @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 a full-range floor position (min/max usable ticks)
* @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 optional full-range floor
* @dev Comprehensive function that supports both token weights and full-range floor ranges
* @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 a full-range floor position is present
* @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 (full-range floor flag)
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 {SqrtPriceMath} from "v4-core/libraries/SqrtPriceMath.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,
bool useCarpet
) 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;
bool useFloorRounding = useCarpet && baseRanges.length > 1;
int24 minUsable = 0;
int24 maxUsable = 0;
if (useFloorRounding) {
minUsable = TickMath.minUsableTick(poolKey.tickSpacing);
maxUsable = TickMath.maxUsableTick(poolKey.tickSpacing);
}
for (uint8 i = 0; i < baseRanges.length;) {
positionData[positionCount] = _mintBasePosition(
poolManager,
poolKey,
baseRanges[i],
liquidities[i],
inMin[i],
useFloorRounding,
minUsable,
maxUsable
);
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;
}
function _mintBasePosition(
IPoolManager poolManager,
PoolKey memory poolKey,
IMultiPositionManager.Range memory range,
uint128 liquidity,
uint256[2] memory inMin,
bool useFloorRounding,
int24 minUsable,
int24 maxUsable
) private returns (IMultiPositionManager.PositionData memory) {
(uint256 currencyDelta0, uint256 currencyDelta1) =
_getCurrencyDeltas(poolManager, poolKey.currency0, poolKey.currency1);
(uint256 amount0, uint256 amount1) =
_getAmountsForLiquidityForMint(poolManager, poolKey, range, liquidity, useFloorRounding, minUsable, maxUsable);
if (amount0 > currencyDelta0) {
amount0 = currencyDelta0;
}
if (amount1 > currencyDelta1) {
amount1 = currencyDelta1;
}
return _mintLiquidityForAmounts(poolManager, poolKey, range, amount0, amount1, inMin);
}
// 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);
uint256 limitIndex = 0;
for (uint8 i = 0; i < 2;) {
// Skip empty limit positions
if (limitRanges[i].lowerTick != limitRanges[i].upperTick) {
uint256 outMinIndex = baseRangesLength + limitIndex;
// 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;
++limitIndex;
}
}
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, BalanceDelta feesAccrued) = 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`)
// Slippage checks should only apply to principal (exclude accrued fees).
BalanceDelta principalDelta = callerDelta - feesAccrued;
uint256 principalOut0 = principalDelta.amount0().toUint128();
uint256 principalOut1 = principalDelta.amount1().toUint128();
amountOut0 = callerDelta.amount0().toUint128();
amountOut1 = callerDelta.amount1().toUint128();
if (principalOut0 < outMin[0] || principalOut1 < 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 getTotalFeesOwed(
IPoolManager poolManager,
PoolKey memory poolKey,
IMultiPositionManager.Range[] memory baseRanges,
IMultiPositionManager.Range[2] memory limitRanges
) internal view returns (uint256 totalFee0, uint256 totalFee1) {
uint256 baseRangesLength = baseRanges.length;
for (uint8 i = 0; i < baseRangesLength;) {
if (baseRanges[i].lowerTick != baseRanges[i].upperTick) {
(uint256 fee0, uint256 fee1) = _getFeesOwed(poolManager, poolKey, baseRanges[i]);
unchecked {
totalFee0 = totalFee0 + fee0;
totalFee1 = totalFee1 + fee1;
}
}
unchecked {
++i;
}
}
if (limitRanges[0].lowerTick != limitRanges[0].upperTick) {
(uint256 fee0, uint256 fee1) = _getFeesOwed(poolManager, poolKey, limitRanges[0]);
unchecked {
totalFee0 = totalFee0 + fee0;
totalFee1 = totalFee1 + fee1;
}
}
if (limitRanges[1].lowerTick != limitRanges[1].upperTick) {
(uint256 fee0, uint256 fee1) = _getFeesOwed(poolManager, poolKey, limitRanges[1]);
unchecked {
totalFee0 = totalFee0 + fee0;
totalFee1 = totalFee1 + fee1;
}
}
}
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 _getAmountsForLiquidityForMint(
IPoolManager poolManager,
PoolKey memory poolKey,
IMultiPositionManager.Range memory range,
uint128 liquidity,
bool useFloorRounding,
int24 minUsable,
int24 maxUsable
) private view returns (uint256 amount0, uint256 amount1) {
if (useFloorRounding && (range.lowerTick == minUsable || range.upperTick == maxUsable)) {
return _getAmountsForLiquidityRoundedUp(poolManager, poolKey, range, liquidity);
}
return getAmountsForLiquidity(poolManager, poolKey, range, liquidity);
}
function _getAmountsForLiquidityRoundedUp(
IPoolManager poolManager,
PoolKey memory poolKey,
IMultiPositionManager.Range memory range,
uint128 liquidity
) private view returns (uint256 amount0, uint256 amount1) {
(uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolKey.toId());
uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(range.lowerTick);
uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(range.upperTick);
if (sqrtPriceX96 <= sqrtPriceLower) {
amount0 = SqrtPriceMath.getAmount0Delta(sqrtPriceLower, sqrtPriceUpper, liquidity, true);
} else if (sqrtPriceX96 < sqrtPriceUpper) {
amount0 = SqrtPriceMath.getAmount0Delta(sqrtPriceX96, sqrtPriceUpper, liquidity, true);
amount1 = SqrtPriceMath.getAmount1Delta(sqrtPriceLower, sqrtPriceX96, liquidity, true);
} else {
amount1 = SqrtPriceMath.getAmount1Delta(sqrtPriceLower, sqrtPriceUpper, liquidity, true);
}
}
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)
// Use do-while to handle consecutive width collisions
uint256 baseRangesLength = baseRanges.length;
bool collision;
do {
collision = false;
for (uint256 i = 0; i < baseRangesLength;) {
int24 rangeWidth = baseRanges[i].upperTick - baseRanges[i].lowerTick;
if (rangeWidth == int24(limitWidth)) {
limitWidth = uint24(int24(limitWidth) + tickSpacing);
collision = true;
break;
}
unchecked {
++i;
}
}
} while (collision);
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)
// Use do-while to handle consecutive width collisions
uint256 baseRangesLength = baseRanges.length;
bool collision;
do {
collision = false;
for (uint256 i = 0; i < baseRangesLength;) {
int24 rangeWidth = baseRanges[i].upperTick - baseRanges[i].lowerTick;
if (rangeWidth == int24(limitWidth)) {
limitWidth = uint24(int24(limitWidth) + tickSpacing);
collision = true;
break;
}
unchecked {
++i;
}
}
} while (collision);
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,
bool useCarpet
) 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, useCarpet
);
}
/**
* @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: 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);
// Aggregator allowlist
function aggregatorAddress(uint8 aggregator) external view returns (address);
// Strategy allowlist
function strategyAllowed(address strategy) external view returns (bool);
// 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
contract MultiPositionDeployer {
address public immutable authorizedFactory;
error UnauthorizedCaller();
constructor(address _authorizedFactory) {
authorizedFactory = _authorizedFactory;
}
function deploy(
IPoolManager poolManager,
PoolKey memory poolKey,
address owner,
address factory,
string memory name,
string memory symbol,
uint16 fee,
bytes32 salt
) external returns (address) {
if (msg.sender != authorizedFactory) revert UnauthorizedCaller();
return address(new MultiPositionManager{salt: salt}(poolManager, poolKey, owner, factory, name, symbol, fee));
}
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)
)
);
assembly {
let ptr := mload(0x40)
mstore(ptr, 0xff00000000000000000000000000000000000000000000000000000000000000)
mstore(add(ptr, 0x01), shl(96, address()))
mstore(add(ptr, 0x15), salt)
mstore(add(ptr, 0x35), hash)
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 {RebalanceSwapLogic} from "./libraries/RebalanceSwapLogic.sol";
import {WithdrawLogic} from "./libraries/WithdrawLogic.sol";
import {DepositLogic} from "./libraries/DepositLogic.sol";
import {PositionLogic} from "./libraries/PositionLogic.sol";
import {MultiPositionFactory} from "./MultiPositionFactory.sol";
import {VolatilityDynamicFeeLimitOrderHook} from "../LimitOrderBook/hooks/VolatilityDynamicFeeLimitOrderHook.sol";
import {VolatilityOracle} from "../LimitOrderBook/libraries/VolatilityOracle.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;
event RelayerGranted(address indexed account);
event RelayerRevoked(address indexed account);
SharedStructs.ManagerStorage internal s;
uint256 public immutable deployedAt;
address public immutable unilaunchFactory;
error UnauthorizedCaller();
error InvalidAction();
error OnlyOneNativeDepositPerMulticall();
error WithdrawalsDisabled();
error CompoundingDisabled();
error RebalanceSwapLocked(uint256 unlockTimestamp);
error InvalidRebalanceParams();
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;
deployedAt = block.timestamp;
unilaunchFactory = _factory;
}
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
nonReentrant
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 {
inMin;
revert CompoundingDisabled();
}
/**
* @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
{
swapParams;
inMin;
revert CompoundingDisabled();
}
/**
* @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)
{
shares;
outMin;
withdrawToWallet;
amount0;
amount1;
revert WithdrawalsDisabled();
}
/**
* @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)
{
amount0Desired;
amount1Desired;
outMin;
amount0Out;
amount1Out;
sharesBurned;
revert WithdrawalsDisabled();
}
/**
* @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 {
_enforceRebalanceParams(params, false);
// First call ZERO_BURN to collect fees (like compound does)
if (s.basePositionsLength > 0 || s.limitPositionsLength > 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);
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 {
_enforceRebalanceParams(params.rebalanceParams, true);
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) =
RebalanceSwapLogic.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));
require(newFee != 0, "Fee cannot be zero");
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) {
revert WithdrawalsDisabled();
} 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) {
revert CompoundingDisabled();
} else {
revert InvalidAction();
}
}
function _enforceRebalanceParams(IMultiPositionManager.RebalanceParams calldata params, bool isSwap) private view {
bool isProportional = (params.weight0 == 0 && params.weight1 == 0);
bool isFiftyFifty = (params.weight0 == 0.5e18 && params.weight1 == 0.5e18);
if (!isProportional && !isFiftyFifty) revert InvalidRebalanceParams();
if (!params.useCarpet) revert InvalidRebalanceParams();
MultiPositionFactory factoryContract = MultiPositionFactory(unilaunchFactory);
uint256 unlockAt = deployedAt + factoryContract.lockDuration();
bool locked = block.timestamp < unlockAt;
if (isSwap && locked) revert RebalanceSwapLocked(unlockAt);
if (locked) {
if (params.tLeft < factoryContract.minTicksLeftInitial()) revert InvalidRebalanceParams();
if (params.tRight < factoryContract.minTicksRightInitial()) revert InvalidRebalanceParams();
if (isFiftyFifty && params.limitWidth < factoryContract.minLimitWidthInitial()) {
revert InvalidRebalanceParams();
}
} else {
if (params.tLeft < factoryContract.minTicksLeftAfter()) revert InvalidRebalanceParams();
if (params.tRight < factoryContract.minTicksRightAfter()) revert InvalidRebalanceParams();
if (isFiftyFifty && params.limitWidth < factoryContract.minLimitWidthAfter()) {
revert InvalidRebalanceParams();
}
}
address resolvedStrategy = params.strategy != address(0) ? params.strategy : s.lastStrategyParams.strategy;
if (resolvedStrategy == address(0) || !factoryContract.strategyAllowed(resolvedStrategy)) {
revert InvalidRebalanceParams();
}
uint24 maxDelta = factoryContract.maxTwapTickDelta();
if (maxDelta != 0) {
uint32 twapSeconds = factoryContract.twapSeconds();
address hookAddress = address(s.poolKey.hooks);
if (hookAddress == address(0)) revert InvalidRebalanceParams();
VolatilityOracle oracle = VolatilityDynamicFeeLimitOrderHook(hookAddress).volatilityOracle();
(, uint32 latestTimestamp) = oracle.getLatestObservation(s.poolKey.toId());
if (block.timestamp >= latestTimestamp + twapSeconds) {
(int24 twapTick,) = oracle.consult(s.poolKey, twapSeconds);
int256 delta = int256(params.center) - int256(twapTick);
if (delta < 0) {
delta = -delta;
}
if (uint256(delta) > maxDelta) revert InvalidRebalanceParams();
}
}
}
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()) {
// In multicall: only allow ONE native deposit to prevent msg.value double-spend
if (_inMulticallContext()) {
if (_isNativeDepositDone()) revert OnlyOneNativeDepositPerMulticall();
_markNativeDepositDone();
}
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
* Uses transient storage to track multicall context and prevent native ETH double-spend
*/
abstract contract Multicall is IMulticall {
error MulticallFailed(uint256 index, bytes reason);
/// @dev Transient storage slot for multicall context flag: keccak256("multicall.context")
bytes32 private constant _MULTICALL_CONTEXT_SLOT =
0x2e40f768ac3179109b141c8c4ebd71d79ff175997abe8aa5bd1bbfe613dc9f1f;
/// @dev Transient storage slot for tracking if native deposit already done: keccak256("multicall.nativeDepositDone")
bytes32 private constant _NATIVE_DEPOSIT_DONE_SLOT =
0x11ac6ef1c72502e61aa6ad82b1888cc53ee565c9bcc98d36d57afcf87daa78d4;
/**
* @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) {
// Set multicall context flag
assembly {
tstore(_MULTICALL_CONTEXT_SLOT, 1)
}
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) {
// Clear flags before reverting
assembly {
tstore(_MULTICALL_CONTEXT_SLOT, 0)
tstore(_NATIVE_DEPOSIT_DONE_SLOT, 0)
}
// 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;
}
// Clear flags at end of multicall
assembly {
tstore(_MULTICALL_CONTEXT_SLOT, 0)
tstore(_NATIVE_DEPOSIT_DONE_SLOT, 0)
}
}
/// @notice Check if currently executing within a multicall
/// @return inContext True if in multicall context
function _inMulticallContext() internal view returns (bool inContext) {
assembly {
inContext := tload(_MULTICALL_CONTEXT_SLOT)
}
}
/// @notice Mark that a native ETH deposit has been done in this multicall
function _markNativeDepositDone() internal {
assembly {
tstore(_NATIVE_DEPOSIT_DONE_SLOT, 1)
}
}
/// @notice Check if a native ETH deposit has already been done in this multicall
/// @return done True if native deposit already done
function _isNativeDepositDone() internal view returns (bool done) {
assembly {
done := tload(_NATIVE_DEPOSIT_DONE_SLOT)
}
}
}// 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
// OpenZeppelin Contracts (last updated v5.3.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 represents a slot holding an 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 represents 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 represents 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 represents 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 represents 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: 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: MIT
// OpenZeppelin Contracts (last updated v5.1.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/bool 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);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}// 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[(index + 1) % cardinality];
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 index,
uint16 cardinality
) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
unchecked {
uint256 l = (uint256(index) + 1) % cardinality; // oldest observation
uint256 r = l + cardinality - 1; // newest observation (virtual index)
uint256 i;
while (true) {
i = (l + r) / 2;
beforeOrAt = self[i % cardinality];
// we've landed on an uninitialized tick, keep searching higher (more recently)
if (!beforeOrAt.initialized) {
l = i + 1;
continue;
}
atOrAfter = self[(i + 1) % cardinality];
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.1.0) (utils/introspection/ERC165Checker.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the ERC-165 spec, no interface should ever match 0xffffffff
bytes4 private constant INTERFACE_ID_INVALID = 0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface.
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC-165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return
supportsERC165InterfaceUnchecked(account, type(IERC165).interfaceId) &&
!supportsERC165InterfaceUnchecked(account, INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC-165 as per the spec and support of _interfaceId
return supportsERC165(account) && supportsERC165InterfaceUnchecked(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*/
function getSupportedInterfaces(
address account,
bytes4[] memory interfaceIds
) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC-165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC-165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC-165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC-165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
*
* Some precompiled contracts will falsely indicate support for a given interface, so caution
* should be exercised when using this function.
*
* Interface identification is specified in ERC-165.
*/
function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) internal view returns (bool) {
// prepare call
bytes memory encodedParams = abi.encodeCall(IERC165.supportsInterface, (interfaceId));
// perform static call
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20)
returnSize := returndatasize()
returnValue := mload(0x00)
}
return success && returnSize >= 0x20 && returnValue > 0;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Action Constants
/// @notice Common constants used in actions
/// @dev Constants are gas efficient alternatives to their literal values
library ActionConstants {
/// @notice used to signal that an action should use the input value of the open delta on the pool manager
/// or of the balance that the contract holds
uint128 internal constant OPEN_DELTA = 0;
/// @notice used to signal that an action should use the contract's entire balance of a currency
/// This value is equivalent to 1<<255, i.e. a singular 1 in the most significant bit.
uint256 internal constant CONTRACT_BALANCE = 0x8000000000000000000000000000000000000000000000000000000000000000;
/// @notice used to signal that the recipient of an action should be the msgSender
address internal constant MSG_SENDER = address(1);
/// @notice used to signal that the recipient of an action should be the address(this)
address internal constant ADDRESS_THIS = address(2);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {FixedPoint96} from "@uniswap/v4-core/src/libraries/FixedPoint96.sol";
import {SafeCast} from "@uniswap/v4-core/src/libraries/SafeCast.sol";
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
using SafeCast for uint256;
/// @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)
{
unchecked {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
uint256 intermediate = FullMath.mulDiv(sqrtPriceAX96, sqrtPriceBX96, FixedPoint96.Q96);
return FullMath.mulDiv(amount0, intermediate, sqrtPriceBX96 - sqrtPriceAX96).toUint128();
}
}
/// @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)
{
unchecked {
if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
return FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtPriceBX96 - sqrtPriceAX96).toUint128();
}
}
/// @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);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error ExpOverflow();
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error FactorialOverflow();
/// @dev The operation failed, due to an overflow.
error RPowOverflow();
/// @dev The mantissa is too big to fit.
error MantissaOverflow();
/// @dev The operation failed, due to an multiplication overflow.
error MulWadFailed();
/// @dev The operation failed, due to an multiplication overflow.
error SMulWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error DivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error SDivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error MulDivFailed();
/// @dev The division failed, as the denominator is zero.
error DivFailed();
/// @dev The full precision multiply-divide operation failed, either due
/// to the result being larger than 256 bits, or a division by a zero.
error FullMulDivFailed();
/// @dev The output is undefined, as the input is less-than-or-equal to zero.
error LnWadUndefined();
/// @dev The input outside the acceptable domain.
error OutOfDomain();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The scalar of ETH and most ERC20s.
uint256 internal constant WAD = 1e18;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIMPLIFIED FIXED POINT OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if gt(x, div(not(0), y)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up.
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if iszero(eq(div(z, y), x)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, WAD)
// Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
if iszero(mul(y, eq(sdiv(z, WAD), x))) {
mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up.
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `x` to the power of `y`.
/// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
/// Note: This function is an approximation.
function powWad(int256 x, int256 y) internal pure returns (int256) {
// Using `ln(x)` means `x` must be greater than 0.
return expWad((lnWad(x) * y) / int256(WAD));
}
/// @dev Returns `exp(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function expWad(int256 x) internal pure returns (int256 r) {
unchecked {
// When the result is less than 0.5 we return zero.
// This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
if (x <= -41446531673892822313) return r;
/// @solidity memory-safe-assembly
assembly {
// When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
// an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
if iszero(slt(x, 135305999368893231589)) {
mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
revert(0x1c, 0x04)
}
}
// `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
// for more intermediate precision and a binary basis. This base conversion
// is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
x = (x << 78) / 5 ** 18;
// Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
// of two such that exp(x) = exp(x') * 2**k, where k is an integer.
// Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
x = x - k * 54916777467707473351141471128;
// `k` is in the range `[-61, 195]`.
// Evaluate using a (6, 7)-term rational approximation.
// `p` is made monic, we'll multiply by a scale factor later.
int256 y = x + 1346386616545796478920950773328;
y = ((y * x) >> 96) + 57155421227552351082224309758442;
int256 p = y + x - 94201549194550492254356042504812;
p = ((p * y) >> 96) + 28719021644029726153956944680412240;
p = p * x + (4385272521454847904659076985693276 << 96);
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
int256 q = x - 2855989394907223263936484059900;
q = ((q * x) >> 96) + 50020603652535783019961831881945;
q = ((q * x) >> 96) - 533845033583426703283633433725380;
q = ((q * x) >> 96) + 3604857256930695427073651918091429;
q = ((q * x) >> 96) - 14423608567350463180887372962807573;
q = ((q * x) >> 96) + 26449188498355588339934803723976023;
/// @solidity memory-safe-assembly
assembly {
// Div in assembly because solidity adds a zero check despite the unchecked.
// The q polynomial won't have zeros in the domain as all its roots are complex.
// No scaling is necessary because p is already `2**96` too large.
r := sdiv(p, q)
}
// r should be in the range `(0.09, 0.25) * 2**96`.
// We now need to multiply r by:
// - The scale factor `s ≈ 6.031367120`.
// - The `2**k` factor from the range reduction.
// - The `1e18 / 2**96` factor for base conversion.
// We do this all at once, with an intermediate result in `2**213`
// basis, so the final right shift is always by a positive amount.
r = int256(
(uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
);
}
}
/// @dev Returns `ln(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function lnWad(int256 x) internal pure returns (int256 r) {
/// @solidity memory-safe-assembly
assembly {
// We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
// We do this by multiplying by `2**96 / 10**18`. But since
// `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
// and add `ln(2**96 / 10**18)` at the end.
// Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
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))))
// We place the check here for more optimal stack operations.
if iszero(sgt(x, 0)) {
mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
revert(0x1c, 0x04)
}
// forgefmt: disable-next-item
r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
// Reduce range of x to (1, 2) * 2**96
// ln(2^k * x) = k * ln(2) + ln(x)
x := shr(159, shl(r, x))
// Evaluate using a (8, 8)-term rational approximation.
// `p` is made monic, we will multiply by a scale factor later.
// forgefmt: disable-next-item
let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
sar(96, mul(add(43456485725739037958740375743393,
sar(96, mul(add(24828157081833163892658089445524,
sar(96, mul(add(3273285459638523848632254066296,
x), x))), x))), x)), 11111509109440967052023855526967)
p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
// `q` is monic by convention.
let q := add(5573035233440673466300451813936, x)
q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
q := add(909429971244387300277376558375, sar(96, mul(x, q)))
// `p / q` is in the range `(0, 0.125) * 2**96`.
// Finalization, we need to:
// - Multiply by the scale factor `s = 5.549…`.
// - Add `ln(2**96 / 10**18)`.
// - Add `k * ln(2)`.
// - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
// The q polynomial is known not to have zeros in the domain.
// No scaling required because p is already `2**96` too large.
p := sdiv(p, q)
// Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
p := mul(1677202110996718588342820967067443963516166, p)
// Add `ln(2) * k * 5**18 * 2**192`.
// forgefmt: disable-next-item
p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
// Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
// Base conversion: mul `2**18 / 2**192`.
r := sar(174, p)
}
}
/// @dev Returns `W_0(x)`, denominated in `WAD`.
/// See: https://en.wikipedia.org/wiki/Lambert_W_function
/// a.k.a. Product log function. This is an approximation of the principal branch.
/// Note: This function is an approximation. Monotonically increasing.
function lambertW0Wad(int256 x) internal pure returns (int256 w) {
// forgefmt: disable-next-item
unchecked {
if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
(int256 wad, int256 p) = (int256(WAD), x);
uint256 c; // Whether we need to avoid catastrophic cancellation.
uint256 i = 4; // Number of iterations.
if (w <= 0x1ffffffffffff) {
if (-0x4000000000000 <= w) {
i = 1; // Inputs near zero only take one step to converge.
} else if (w <= -0x3ffffffffffffff) {
i = 32; // Inputs near `-1/e` take very long to converge.
}
} else if (uint256(w >> 63) == uint256(0)) {
/// @solidity memory-safe-assembly
assembly {
// Inline log2 for more performance, since the range is small.
let v := shr(49, w)
let l := shl(3, lt(0xff, v))
l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
c := gt(l, 60)
i := add(2, add(gt(l, 53), c))
}
} else {
int256 ll = lnWad(w = lnWad(w));
/// @solidity memory-safe-assembly
assembly {
// `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
i := add(3, iszero(shr(68, x)))
c := iszero(shr(143, x))
}
if (c == uint256(0)) {
do { // If `x` is big, use Newton's so that intermediate values won't overflow.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := mul(w, div(e, wad))
w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
}
if (p <= w) break;
p = w;
} while (--i != uint256(0));
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
return w;
}
}
do { // Otherwise, use Halley's for faster convergence.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := add(w, wad)
let s := sub(mul(w, e), mul(x, wad))
w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
}
if (p <= w) break;
p = w;
} while (--i != c);
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
// For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
// R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
if (c == uint256(0)) return w;
int256 t = w | 1;
/// @solidity memory-safe-assembly
assembly {
x := sdiv(mul(x, wad), t)
}
x = (t * (wad + lnWad(x)));
/// @solidity memory-safe-assembly
assembly {
w := sdiv(x, add(wad, t))
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* GENERAL NUMBER UTILITIES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `a * b == x * y`, with full precision.
function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// 512-bit multiply `[p1 p0] = x * y`.
// 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 = p1 * 2**256 + p0`.
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`.
for {} 1 {} {
// If overflows.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
/*------------------- 512 by 256 division --------------------*/
// Make division exact by subtracting the remainder from `[p1 p0]`.
let r := mulmod(x, y, d) // Compute remainder using mulmod.
let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
// Make sure `z` is less than `2**256`. Also prevents `d == 0`.
// Placing the check here seems to give more optimal stack operations.
if iszero(gt(d, p1)) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
d := div(d, t) // Divide `d` by `t`, which is a power of two.
// Invert `d mod 2**256`
// Now that `d` is an odd number, it has an inverse
// modulo `2**256` such that `d * inv = 1 mod 2**256`.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, `d * inv = 1 mod 2**4`.
let inv := xor(2, mul(3, d))
// 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 := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
z :=
mul(
// Divide [p1 p0] by the factors of two.
// Shift in bits from `p1` into `p0`. For this we need
// to flip `t` such that it is `2**256 / t`.
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
)
break
}
z := div(z, d)
break
}
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
/// Performs the full 512 bit calculation regardless.
function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z)))
let t := and(d, sub(0, d))
let r := mulmod(x, y, d)
d := div(d, t)
let inv := xor(2, mul(3, d))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
z :=
mul(
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv)
)
}
}
/// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Uniswap-v3-core under MIT license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
z = fullMulDiv(x, y, d);
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, d) {
z := add(z, 1)
if iszero(z) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
/// Throws if result overflows a uint256.
/// Credit to Philogy under MIT license:
/// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
for {} 1 {} {
if iszero(or(iszero(x), eq(div(z, x), y))) {
let k := and(n, 0xff) // `n`, cleaned.
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
// | p1 | z |
// Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 |
// Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 |
// Check that final `z` doesn't overflow by checking that p1_0 = 0.
if iszero(shr(k, p1)) {
z := add(shl(sub(256, k), p1), shr(k, z))
break
}
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
z := shr(and(n, 0xff), z)
break
}
}
}
/// @dev Returns `floor(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := div(z, d)
}
}
/// @dev Returns `ceil(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(z, d))), div(z, d))
}
}
/// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
/// @solidity memory-safe-assembly
assembly {
let g := n
let r := mod(a, n)
for { let y := 1 } 1 {} {
let q := div(g, r)
let t := g
g := r
r := sub(t, mul(r, q))
let u := x
x := y
y := sub(u, mul(y, q))
if iszero(r) { break }
}
x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
}
}
/// @dev Returns `ceil(x / d)`.
/// Reverts if `d` is zero.
function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
if iszero(d) {
mstore(0x00, 0x65244e4e) // `DivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(x, d))), div(x, d))
}
}
/// @dev Returns `max(0, x - y)`. Alias for `saturatingSub`.
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `max(0, x - y)`.
function saturatingSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x + y)`.
function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(0, lt(add(x, y), x)), add(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x * y)`.
function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `x != 0 ? x : y`, without branching.
function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != bytes32(0) ? x : y`, without branching.
function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != address(0) ? x : y`, without branching.
function coalesce(address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(shl(96, x))))
}
}
/// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
/// Reverts if the computation overflows.
function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
if x {
z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
let half := shr(1, b) // Divide `b` by 2.
// Divide `y` by 2 every iteration.
for { y := shr(1, y) } y { y := shr(1, y) } {
let xx := mul(x, x) // Store x squared.
let xxRound := add(xx, half) // Round to the nearest number.
// Revert if `xx + half` overflowed, or if `x ** 2` overflows.
if or(lt(xxRound, xx), shr(128, x)) {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
x := div(xxRound, b) // Set `x` to scaled `xxRound`.
// If `y` is odd:
if and(y, 1) {
let zx := mul(z, x) // Compute `z * x`.
let zxRound := add(zx, half) // Round to the nearest number.
// If `z * x` overflowed or `zx + half` overflowed:
if or(xor(div(zx, x), z), lt(zxRound, zx)) {
// Revert if `x` is non-zero.
if x {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
}
z := div(zxRound, b) // Return properly scaled `zxRound`.
}
}
}
}
}
/// @dev Returns the square root of `x`, rounded down.
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
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.
// Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
// but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffffff, shr(r, x))))
z := shl(shr(1, r), 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(shr(r, x), 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
z := sub(z, lt(div(x, z), z))
}
}
/// @dev Returns the cube root of `x`, rounded down.
/// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
/// https://github.com/pcaversaccio/snekmate/blob/main/src/snekmate/utils/math.vy
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let 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))))
// Makeshift lookup table to nudge the approximate log2 result.
z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
// Newton-Raphson's.
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
// Round down.
z := sub(z, lt(div(x, mul(z, z)), z))
}
}
/// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
function sqrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
z = (1 + sqrt(x)) * 10 ** 9;
z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
}
/// @solidity memory-safe-assembly
assembly {
z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
}
}
/// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
z = (1 + cbrt(x)) * 10 ** 12;
z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
}
/// @solidity memory-safe-assembly
assembly {
let p := x
for {} 1 {} {
if iszero(shr(229, p)) {
if iszero(shr(199, p)) {
p := mul(p, 100000000000000000) // 10 ** 17.
break
}
p := mul(p, 100000000) // 10 ** 8.
break
}
if iszero(shr(249, p)) { p := mul(p, 100) }
break
}
let t := mulmod(mul(z, z), z, p)
z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
}
}
/// @dev Returns `sqrt(x * y)`. Also called the geometric mean.
function mulSqrt(uint256 x, uint256 y) internal pure returns (uint256 z) {
if (x == y) return x;
uint256 p = rawMul(x, y);
if (y == rawDiv(p, x)) return sqrt(p);
for (z = saturatingMul(rawAdd(sqrt(x), 1), rawAdd(sqrt(y), 1));; z = avg(z, p)) {
if ((p = fullMulDivUnchecked(x, y, z)) >= z) break;
}
}
/// @dev Returns the factorial of `x`.
function factorial(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := 1
if iszero(lt(x, 58)) {
mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
revert(0x1c, 0x04)
}
for {} x { x := sub(x, 1) } { z := mul(z, x) }
}
}
/// @dev Returns the log2 of `x`.
/// Equivalent to computing the index of the most significant bit (MSB) of `x`.
/// Returns 0 if `x` is zero.
function log2(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
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)),
0x0706060506020504060203020504030106050205030304010505030400000000))
}
}
/// @dev Returns the log2 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log2Up(uint256 x) internal pure returns (uint256 r) {
r = log2(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(r, 1), x))
}
}
/// @dev Returns the log10 of `x`.
/// Returns 0 if `x` is zero.
function log10(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(x, 100000000000000000000000000000000000000)) {
x := div(x, 100000000000000000000000000000000000000)
r := 38
}
if iszero(lt(x, 100000000000000000000)) {
x := div(x, 100000000000000000000)
r := add(r, 20)
}
if iszero(lt(x, 10000000000)) {
x := div(x, 10000000000)
r := add(r, 10)
}
if iszero(lt(x, 100000)) {
x := div(x, 100000)
r := add(r, 5)
}
r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
}
}
/// @dev Returns the log10 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log10Up(uint256 x) internal pure returns (uint256 r) {
r = log10(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(exp(10, r), x))
}
}
/// @dev Returns the log256 of `x`.
/// Returns 0 if `x` is zero.
function log256(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
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(shr(3, r), lt(0xff, shr(r, x)))
}
}
/// @dev Returns the log256 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log256Up(uint256 x) internal pure returns (uint256 r) {
r = log256(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(shl(3, r), 1), x))
}
}
/// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
/// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
/// @solidity memory-safe-assembly
assembly {
mantissa := x
if mantissa {
if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
mantissa := div(mantissa, 1000000000000000000000000000000000)
exponent := 33
}
if iszero(mod(mantissa, 10000000000000000000)) {
mantissa := div(mantissa, 10000000000000000000)
exponent := add(exponent, 19)
}
if iszero(mod(mantissa, 1000000000000)) {
mantissa := div(mantissa, 1000000000000)
exponent := add(exponent, 12)
}
if iszero(mod(mantissa, 1000000)) {
mantissa := div(mantissa, 1000000)
exponent := add(exponent, 6)
}
if iszero(mod(mantissa, 10000)) {
mantissa := div(mantissa, 10000)
exponent := add(exponent, 4)
}
if iszero(mod(mantissa, 100)) {
mantissa := div(mantissa, 100)
exponent := add(exponent, 2)
}
if iszero(mod(mantissa, 10)) {
mantissa := div(mantissa, 10)
exponent := add(exponent, 1)
}
}
}
}
/// @dev Convenience function for packing `x` into a smaller number using `sci`.
/// The `mantissa` will be in bits [7..255] (the upper 249 bits).
/// The `exponent` will be in bits [0..6] (the lower 7 bits).
/// Use `SafeCastLib` to safely ensure that the `packed` number is small
/// enough to fit in the desired unsigned integer type:
/// ```
/// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
/// ```
function packSci(uint256 x) internal pure returns (uint256 packed) {
(x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
/// @solidity memory-safe-assembly
assembly {
if shr(249, x) {
mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
revert(0x1c, 0x04)
}
packed := or(shl(7, x), packed)
}
}
/// @dev Convenience function for unpacking a packed number from `packSci`.
function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
unchecked {
unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards zero.
function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = (x & y) + ((x ^ y) >> 1);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
function avg(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
/// @dev Returns the absolute value of `x`.
function abs(int256 x) internal pure returns (uint256 z) {
unchecked {
z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(int256 x, int256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), slt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), gt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), sgt(y, x)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(uint256 x, uint256 minValue, uint256 maxValue)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
}
}
/// @dev Returns greatest common divisor of `x` and `y`.
function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
for { z := x } y {} {
let t := y
y := mod(z, y)
z := t
}
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
internal
pure
returns (uint256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
unchecked {
if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
return a - fullMulDiv(a - b, t - begin, end - begin);
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
internal
pure
returns (int256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
// forgefmt: disable-next-item
unchecked {
if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
uint256(t - begin), uint256(end - begin)));
return int256(uint256(a) - fullMulDiv(uint256(a - b),
uint256(t - begin), uint256(end - begin)));
}
}
/// @dev Returns if `x` is an even number. Some people may need this.
function isEven(uint256 x) internal pure returns (bool) {
return x & uint256(1) == uint256(0);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RAW NUMBER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(x, y)
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mod(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := smod(x, y)
}
}
/// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := addmod(x, y, d)
}
}
/// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mulmod(x, y, d)
}
}
}// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title BlockNumberish /// A helper contract to get the current block number on different chains /// inspired by https://github.com/ProjectOpenSea/tstorish/blob/main/src/Tstorish.sol /// @custom:security-contact [email protected] contract BlockNumberish { // Arbitrum One chain ID. uint256 private constant ARB_CHAIN_ID = 42_161; // Unichain chain ID. uint256 private constant UNICHAIN_CHAIN_ID = 130; /// @dev Function selector for arbBlockNumber() from: https://github.com/OffchainLabs/nitro-precompile-interfaces/blob/f49a4889b486fd804a7901203f5f663cfd1581c8/ArbSys.sol#L17 uint32 private constant ARB_SYS_SELECTOR = 0xa3b1b31d; /// @dev Arbitrum system contract address (address(100)) uint8 private constant ARB_SYS_ADDRESS = 0x64; /// @dev Function selector for getFlashblockNumber() from: https://github.com/Uniswap/flashblocks_number_contract/blob/a667d57f0055de80b9909c8837e872c4364853c3/src/IFlashblockNumber.sol#L70 uint32 private constant UNICHAIN_FLASHBLOCK_NUMBER_SELECTOR = 0xe5b37c5d; /// @dev Unichain flashblock number address address private constant UNICHAIN_FLASHBLOCK_NUMBER_ADDRESS = 0x3c3A8a41E095C76b03f79f70955fFf3b03cf753E; /// @notice Internal view function to get the current block number. /// @dev Returns Arbitrum block number on Arbitrum One, standard block number elsewhere. function _getBlockNumberish() internal view returns (uint256 blockNumber) { if (block.chainid == ARB_CHAIN_ID) { assembly { mstore(0x00, ARB_SYS_SELECTOR) // staticcall(gas, address, argsOffset, argsSize, retOffset, retSize) let success := staticcall(gas(), ARB_SYS_ADDRESS, 0x1c, 0x04, 0x00, 0x20) // revert if the call fails from OOG or returns malformed data if or(iszero(success), iszero(eq(returndatasize(), 0x20))) { revert(0, 0) } // load the stored block number from memory blockNumber := mload(0x00) } } else { blockNumber = block.number; } } /// @notice Internal view function to get the current flashblock number. /// @dev Returns Unichain flashblock number on Unichain, 0 elsewhere. function _getFlashblockNumberish() internal view returns (uint256 flashblockNumber) { if (block.chainid == UNICHAIN_CHAIN_ID) { assembly { mstore(0x00, UNICHAIN_FLASHBLOCK_NUMBER_SELECTOR) // staticcall(gas, address, argsOffset, argsSize, retOffset, retSize) let success := staticcall(gas(), UNICHAIN_FLASHBLOCK_NUMBER_ADDRESS, 0x1c, 0x04, 0x00, 0x20) // revert if the call fails from OOG or returns malformed data if or(iszero(success), iszero(eq(returndatasize(), 0x20))) { revert(0, 0) } // load the stored block number from memory flashblockNumber := mload(0x00) } } } }
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {BaseHook} from "@uniswap/v4-periphery/src/utils/BaseHook.sol";
/// @title SelfInitializerHook
/// @notice Hook contract that only allows itself to initialize the pool
abstract contract SelfInitializerHook is BaseHook {
/// @notice Error thrown when the caller of `initializePool` is not address(this)
/// @param caller The invalid address attempting to initialize the pool
/// @param expected address(this)
error InvalidInitializer(address caller, address expected);
constructor(IPoolManager _poolManager) BaseHook(_poolManager) {}
/// @inheritdoc BaseHook
function getHookPermissions() public pure virtual override returns (Hooks.Permissions memory) {
return Hooks.Permissions({
beforeInitialize: true,
beforeAddLiquidity: false,
beforeSwap: false,
beforeSwapReturnDelta: false,
afterSwap: false,
afterInitialize: false,
beforeRemoveLiquidity: false,
afterAddLiquidity: false,
afterRemoveLiquidity: false,
beforeDonate: false,
afterDonate: false,
afterSwapReturnDelta: false,
afterAddLiquidityReturnDelta: false,
afterRemoveLiquidityReturnDelta: false
});
}
/// @inheritdoc BaseHook
function _beforeInitialize(address sender, PoolKey calldata, uint160) internal view override returns (bytes4) {
// This check is only hit when another address tries to initialize the pool, since hooks cannot call themselves.
// Therefore this will always revert, ensuring only this contract can initialize pools
if (sender != address(this)) revert InvalidInitializer(sender, address(this));
return IHooks.beforeInitialize.selector;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IDistributionContract} from "./IDistributionContract.sol";
/// @dev The interface id of the ILBPInitializer interface
/// @dev Per ERC165, the interface selector is the XOR of the selectors of the interfaces implemented by the contract
bytes4 constant ILBP_INITIALIZER_INTERFACE_ID = type(ILBPInitializer).interfaceId;
/// @notice General parameters for initializing an LBP strategy
struct LBPInitializationParams {
uint256 initialPriceX96; // the price discovered by the contract
uint256 tokensSold; // the number of tokens sold by the contract
uint256 currencyRaised; // the amount of currency raised by the contract
}
/// @title ILBPInitializer
/// @notice Generic interface for contracts used for initializing an LBP strategy
interface ILBPInitializer is IDistributionContract, IERC165 {
/// @notice Returns the LBP initialization parameters as determined by the implementing contract
/// @dev The implementing contract MUST ensure that these values are correct at the time of calling
/// @return params The LBP initialization parameters
function lbpInitializationParams() external view returns (LBPInitializationParams memory params);
/// @notice Returns the token used by the initializer
function token() external view returns (address);
/// @notice Returns the currency used by the initializer
function currency() external view returns (address);
/// @notice Returns the total supply of the token used by the initializer
function totalSupply() external view returns (uint128);
/// @notice Returns the address which will receive the unsold tokens
function tokensRecipient() external view returns (address);
/// @notice Returns the address which will receive the raised currency
function fundsRecipient() external view returns (address);
/// @notice Returns the start block of the initializer
function startBlock() external view returns (uint64);
/// @notice Returns the end block of the initializer
function endBlock() external view returns (uint64);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {IDistributionContract} from "./IDistributionContract.sol";
import {IPositionManager} from "@uniswap/v4-periphery/src/interfaces/IPositionManager.sol";
import {ILBPInitializer} from "./ILBPInitializer.sol";
/// @title ILBPStrategyBase
/// @notice Base interface for derived LBPStrategy contracts
interface ILBPStrategyBase is IDistributionContract {
/// @notice Emitted when a v4 pool is created and the liquidity is migrated to it
/// @param key The key of the pool that was created
/// @param initialSqrtPriceX96 The initial sqrt price of the pool
event Migrated(PoolKey indexed key, uint160 initialSqrtPriceX96);
/// @notice Emitted when the initializer is created
/// @param initializer The address of the initializer contract
event InitializerCreated(address indexed initializer);
/// @notice Error thrown when migration to a v4 pool is not allowed yet
/// @param migrationBlock The block number at which migration is allowed
/// @param currentBlock The current block number
error MigrationNotAllowed(uint256 migrationBlock, uint256 currentBlock);
/// @notice Emitted when the tokens are swept
event TokensSwept(address indexed operator, uint256 amount);
/// @notice Emitted when the currency is swept
event CurrencySwept(address indexed operator, uint256 amount);
/// @notice Error thrown when the initializer does not implement the ILBPInitializer interface
/// @param initializer The deployed initializer address
error InitializerMustImplementInterface(address initializer);
/// @notice Error thrown when the sweep block is before or at the migration block
error InvalidSweepBlock(uint256 sweepBlock, uint256 migrationBlock);
/// @notice Error thrown when the end block is at orafter the migration block
/// @param endBlock The invalid end block
/// @param migrationBlock The migration block
error InvalidEndBlock(uint256 endBlock, uint256 migrationBlock);
/// @notice Error thrown when the initializer currency is not the same as the strategy currency
/// @param actual The initializer currency
/// @param expected The actual currency
error InvalidCurrency(address actual, address expected);
/// @notice Error thrown when the floor price is invalid
/// @param floorPrice The invalid floor price
error InvalidFloorPrice(uint256 floorPrice);
/// @notice Error thrown when the max currency amount for LP is zero
error MaxCurrencyAmountForLPIsZero();
/// @notice Error thrown when the token split is too high
/// @param tokenSplit The invalid token split percentage
error TokenSplitTooHigh(uint24 tokenSplit, uint24 maxTokenSplit);
/// @notice Error thrown when the tick spacing is greater than the max tick spacing or less than the min tick spacing
/// @param tickSpacing The invalid tick spacing
error InvalidTickSpacing(int24 tickSpacing, int24 minTickSpacing, int24 maxTickSpacing);
/// @notice Error thrown when the fee is greater than the max fee
/// @param fee The invalid fee
error InvalidFee(uint24 fee, uint24 maxFee);
/// @notice Error thrown when the position recipient is the zero address, address(1), or address(2)
/// @param positionRecipient The invalid position recipient
error InvalidPositionRecipient(address positionRecipient);
/// @notice Error thrown when the funds recipient is not set to the strategy
/// @param invalidFundsRecipient The invalid funds recipient
/// @param expectedFundsRecipient The expected funds recipient
error InvalidFundsRecipient(address invalidFundsRecipient, address expectedFundsRecipient);
/// @notice Error thrown when the reserve supply is too high
/// @param reserveTokenAmount The invalid reserve supply
/// @param maxReserveSupply The maximum reserve supply (type(uint128).max)
error ReserveSupplyIsTooHigh(uint256 reserveTokenAmount, uint256 maxReserveSupply);
/// @notice Error thrown when the liquidity is invalid
/// @param liquidity The invalid liquidity
/// @param maxLiquidity The max liquidity
error InvalidLiquidity(uint128 liquidity, uint128 maxLiquidity);
/// @notice Error thrown when the caller is not the operator
error NotOperator(address caller, address operator);
/// @notice Error thrown when the sweep is not allowed yet
error SweepNotAllowed(uint256 sweepBlock, uint256 currentBlock);
/// @notice Error thrown when the token amount is invalid
/// @param tokenAmount The invalid token amount
/// @param reserveTokenAmount The reserve supply
error InvalidTokenAmount(uint128 tokenAmount, uint128 reserveTokenAmount);
/// @notice Error thrown when the token split to the initializer is zero. This is possible due to rounding.
error InitializerTokenSplitIsZero();
/// @notice Error thrown when the currency amount is greater than type(uint128).max
/// @param currencyAmount The invalid currency amount
/// @param maxCurrencyAmount The maximum currency amount (type(uint128).max)
error CurrencyAmountTooHigh(uint256 currencyAmount, uint256 maxCurrencyAmount);
/// @notice Error thrown when the currency amount is invalid
/// @param amountNeeded The currency amount needed
/// @param amountAvailable The balance of the currency in the contract
error InsufficientCurrency(uint256 amountNeeded, uint256 amountAvailable);
/// @notice Error thrown when the auction has already been created
error InitializerAlreadyCreated();
/// @notice Error thrown when no currency was raised
error NoCurrencyRaised();
/// @notice Error thrown when the token amount is too high
/// @param tokenAmount The invalid token amount
error AmountOverflow(uint256 tokenAmount);
/// @notice Migrates the raised funds and tokens to a v4 pool
function migrate() external;
/// @notice Allows the operator to sweep tokens from the contract
/// @dev Can only be called after sweepBlock by the operator
function sweepToken() external;
/// @notice Allows the operator to sweep currency from the contract
/// @dev Can only be called after sweepBlock by the operator
function sweepCurrency() external;
/// Getters
function token() external view returns (address);
function currency() external view returns (address);
function totalSupply() external view returns (uint128);
function reserveTokenAmount() external view returns (uint128);
function positionManager() external view returns (IPositionManager);
function positionRecipient() external view returns (address);
function migrationBlock() external view returns (uint64);
function sweepBlock() external view returns (uint64);
function operator() external view returns (address);
function initializer() external view returns (ILBPInitializer);
function initializerParameters() external view returns (bytes memory);
function poolLPFee() external view returns (uint24);
function poolTickSpacing() external view returns (int24);
function maxCurrencyAmountForLP() external view returns (uint128);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
/// @notice Base parameters shared by all position types
struct BasePositionParams {
address currency;
address poolToken;
uint24 poolLPFee;
int24 poolTickSpacing;
uint160 initialSqrtPriceX96;
uint128 liquidity;
address positionRecipient;
IHooks hooks;
}
/// @notice Parameters specific to full-range positions
struct FullRangeParams {
uint128 tokenAmount;
uint128 currencyAmount;
}
/// @notice Parameters specific to one-sided positions
struct OneSidedParams {
uint128 amount;
bool inToken;
}
/// @notice Tick boundaries for a position
struct TickBounds {
int24 lowerTick;
int24 upperTick;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {LiquidityAmounts} from "@uniswap/v4-periphery/src/libraries/LiquidityAmounts.sol";
import {BasePositionParams, FullRangeParams, OneSidedParams, TickBounds} from "../types/PositionTypes.sol";
import {ParamsBuilder} from "./ParamsBuilder.sol";
import {ActionsBuilder} from "./ActionsBuilder.sol";
import {TickCalculations} from "./TickCalculations.sol";
import {DynamicArray} from "./DynamicArray.sol";
/// @notice Struct containing encoded actions and parameters for calls to Uniswap v4 PositionManager
struct Plan {
bytes actions;
bytes[] params;
}
/// @title StrategyPlanner
/// @notice Simplified library that orchestrates position planning using helper libraries
library StrategyPlanner {
using StrategyPlanner for Plan;
using TickCalculations for int24;
using ActionsBuilder for *;
using ParamsBuilder for *;
using DynamicArray for bytes[];
/// @notice Initializes empty plan
/// @return plan The empty plan
function init() internal pure returns (Plan memory plan) {
return Plan({actions: ActionsBuilder.init(), params: ParamsBuilder.init()});
}
/// @notice Encodes the plan into a bytes array, truncating the parameters array
/// @param plan The plan to encode
/// @return The encoded plan
function encode(Plan memory plan) internal pure returns (bytes memory) {
return abi.encode(plan.actions, plan.params);
}
/// @notice Creates the actions and parameters needed to mint a full range position on the position manager
/// @param plan The plan to extend with the new actions and parameters
/// @param baseParams The base parameters for the position
/// @param fullRangeParams The amounts of currency and token that will be used to mint the position
function planFullRangePosition(
Plan memory plan,
BasePositionParams memory baseParams,
FullRangeParams memory fullRangeParams
) internal pure returns (Plan memory) {
bool currencyIsCurrency0 = baseParams.currency < baseParams.poolToken;
// Get tick bounds for full range
TickBounds memory bounds = TickBounds({
lowerTick: TickMath.minUsableTick(baseParams.poolTickSpacing),
upperTick: TickMath.maxUsableTick(baseParams.poolTickSpacing)
});
PoolKey memory poolKey = PoolKey({
currency0: Currency.wrap(currencyIsCurrency0 ? baseParams.currency : baseParams.poolToken),
currency1: Currency.wrap(currencyIsCurrency0 ? baseParams.poolToken : baseParams.currency),
fee: baseParams.poolLPFee,
tickSpacing: baseParams.poolTickSpacing,
hooks: baseParams.hooks
});
return Plan({
actions: plan.actions.addMint().addSettle().addSettle(),
params: plan.params
.addFullRangeParams(
fullRangeParams,
poolKey,
bounds,
currencyIsCurrency0,
baseParams.positionRecipient,
baseParams.liquidity
)
});
}
/// @notice Creates the actions and parameters needed to mint a one-sided position on the position manager
/// @param plan The plan to extend with the new actions and parameters
/// @param baseParams The base parameters for the position
/// @param oneSidedParams The amounts of token that will be used to mint the position
function planOneSidedPosition(
Plan memory plan,
BasePositionParams memory baseParams,
OneSidedParams memory oneSidedParams
) internal pure returns (Plan memory) {
bool currencyIsCurrency0 = baseParams.currency < baseParams.poolToken;
// Get tick bounds based on position side
TickBounds memory bounds = currencyIsCurrency0 == oneSidedParams.inToken
? getLeftSideBounds(baseParams.initialSqrtPriceX96, baseParams.poolTickSpacing)
: getRightSideBounds(baseParams.initialSqrtPriceX96, baseParams.poolTickSpacing);
// If the tick bounds are 0,0 (which means the current tick is too close to MIN_TICK or MAX_TICK), return the existing actions and parameters
// that will build a full range position
if (bounds.lowerTick == 0 && bounds.upperTick == 0) {
return plan;
}
// If this overflows, the transaction will revert and no position will be created
uint128 newLiquidity = LiquidityAmounts.getLiquidityForAmounts(
baseParams.initialSqrtPriceX96,
TickMath.getSqrtPriceAtTick(bounds.lowerTick),
TickMath.getSqrtPriceAtTick(bounds.upperTick),
currencyIsCurrency0 == oneSidedParams.inToken ? 0 : oneSidedParams.amount,
currencyIsCurrency0 == oneSidedParams.inToken ? oneSidedParams.amount : 0
);
if (
newLiquidity == 0
|| baseParams.liquidity + newLiquidity > baseParams.poolTickSpacing.tickSpacingToMaxLiquidityPerTick()
) {
return plan;
}
return Plan({
actions: plan.actions.addMint(),
params: plan.params
.addOneSidedParams(
oneSidedParams,
PoolKey({
currency0: Currency.wrap(currencyIsCurrency0 ? baseParams.currency : baseParams.poolToken),
currency1: Currency.wrap(currencyIsCurrency0 ? baseParams.poolToken : baseParams.currency),
fee: baseParams.poolLPFee,
tickSpacing: baseParams.poolTickSpacing,
hooks: baseParams.hooks
}),
bounds,
currencyIsCurrency0,
baseParams.positionRecipient,
newLiquidity
)
});
}
/// @notice Plans the final take pair action and parameters
/// @param plan The plan to extend with the new actions and parameters
/// @param baseParams The base parameters for the position
function planTakePair(Plan memory plan, BasePositionParams memory baseParams) internal view returns (Plan memory) {
bool currencyIsCurrency0 = baseParams.currency < baseParams.poolToken;
return Plan({
actions: plan.actions.addTakePair(),
params: plan.params
.addTakePairParams(
currencyIsCurrency0 ? baseParams.currency : baseParams.poolToken,
currencyIsCurrency0 ? baseParams.poolToken : baseParams.currency
)
});
}
/// @notice Gets tick bounds for a left-side position (below current tick)
/// @param initialSqrtPriceX96 The initial sqrt price of the position
/// @param poolTickSpacing The tick spacing of the pool
/// @return bounds The tick bounds for the left-side position (returns 0,0 if the current tick is too close to MIN_TICK)
function getLeftSideBounds(uint160 initialSqrtPriceX96, int24 poolTickSpacing)
internal
pure
returns (TickBounds memory bounds)
{
int24 initialTick = TickMath.getTickAtSqrtPrice(initialSqrtPriceX96);
// Check if position is too close to MIN_TICK. If so, return a lower tick and upper tick of 0
// Require there to be at least 2 ticks between the initial tick and MIN_TICK, since `tickFloor` rounds down
if (initialTick - TickMath.MIN_TICK < poolTickSpacing * 2) {
return bounds;
}
bounds = TickBounds({
lowerTick: TickMath.minUsableTick(poolTickSpacing), // Rounds to the nearest multiple of tick spacing (rounds towards 0 since MIN_TICK is negative)
upperTick: initialTick.tickFloor(poolTickSpacing) // Rounds to the nearest multiple of tick spacing if needed (rounds toward -infinity)
});
return bounds;
}
/// @notice Gets tick bounds for a right-side position (above current tick)
/// @param initialSqrtPriceX96 The initial sqrt price of the position
/// @param poolTickSpacing The tick spacing of the pool
/// @return bounds The tick bounds for the right-side position (returns 0,0 if the current tick is too close to MAX_TICK)
function getRightSideBounds(uint160 initialSqrtPriceX96, int24 poolTickSpacing)
internal
pure
returns (TickBounds memory bounds)
{
int24 initialTick = TickMath.getTickAtSqrtPrice(initialSqrtPriceX96);
// Check if position is too close to MAX_TICK. If so, return a lower tick and upper tick of 0
// Require there to be at least 2 ticks between the initial tick and MAX_TICK, since `tickStrictCeil` rounds up
if (TickMath.MAX_TICK - initialTick < poolTickSpacing * 2) {
return bounds;
}
bounds = TickBounds({
lowerTick: initialTick.tickStrictCeil(poolTickSpacing), // Rounds toward +infinity to the nearest multiple of tick spacing
upperTick: TickMath.maxUsableTick(poolTickSpacing) // Rounds to the nearest multiple of tick spacing (rounds toward 0 since MAX_TICK is positive)
});
return bounds;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title TokenDistribution
/// @notice Library for calculating token distribution splits between auction and reserves
/// @dev Handles the splitting of total token supply based on percentage allocations
library TokenDistribution {
/// @notice Maximum value for token split percentage (100% in basis points)
/// @dev 1e7 = 10,000,000 basis points = 100%
uint24 public constant MAX_TOKEN_SPLIT = 1e7;
/// @notice Calculates the token split based on the split ratio
/// @param _totalSupply The total token supply
/// @param _splitMps The percentage to split (in basis points, max 1e7)
/// @return the split amount of tokens
function calculateTokenSplit(uint128 _totalSupply, uint24 _splitMps) internal pure returns (uint128) {
// Safe: totalSupply <= uint128.max and _splitMps <= MAX_TOKEN_SPLIT (1e7)
// uint256(totalSupply) * _splitMps will never overflow type(uint256).max
return uint128(uint256(_totalSupply) * _splitMps / MAX_TOKEN_SPLIT);
}
/// @notice Calculates the reserve supply (remainder after auction allocation)
/// @param _totalSupply The total token supply
/// @param _splitMps The percentage to split (in basis points, max 1e7)
/// @return the amount of tokens reserved for liquidity
function calculateReserveSupply(uint128 _totalSupply, uint24 _splitMps) internal pure returns (uint128) {
return _totalSupply - calculateTokenSplit(_totalSupply, _splitMps);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {FixedPoint96} from "@uniswap/v4-core/src/libraries/FixedPoint96.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
/// @title TokenPricing
/// @notice Library for pricing operations including price conversions and token amount calculations
/// @dev Handles conversions between different price representations and calculates swap amounts
library TokenPricing {
/// @notice Thrown when price is invalid (0 or out of bounds)
/// @param price The invalid price in Q96 format in terms of currency1/currency0
error PriceIsZero(uint256 price);
/// @notice Thrown when price is too high
/// @param price The invalid price in Q96 format in terms of currency1/currency0
/// @param maxPrice The maximum price (type(uint160).max)
error PriceTooHigh(uint256 price, uint256 maxPrice);
/// @notice Thrown when price is out of bounds
/// @param sqrtPriceX96 The invalid sqrt price in Q96 format
/// @param minSqrtPriceX96 The minimum sqrt price (TickMath.MIN_SQRT_PRICE)
/// @param maxSqrtPriceX96 The maximum sqrt price (TickMath.MAX_SQRT_PRICE)
error SqrtPriceX96OutOfBounds(uint160 sqrtPriceX96, uint160 minSqrtPriceX96, uint160 maxSqrtPriceX96);
/// @notice Thrown when calculated amount exceeds uint128 max value
/// @param currencyAmount The invalid currency amount
error AmountOverflow(uint256 currencyAmount);
/// @notice Q192 format: 192-bit fixed-point number representation
/// @dev Used for intermediate calculations to maintain precision
uint256 public constant Q192 = 1 << 192;
/// @notice Converts a Q96 price to Uniswap v4 X192 format in terms of currency1/currency0
/// @dev Converts price from Q96 to X192 format
/// @param price The price in Q96 fixed-point format (96 bits of fractional precision)
/// @param currencyIsCurrency0 True if the currency is currency0 (lower address)
/// @return priceX192 The price in Q192 fixed-point format
function convertToPriceX192(uint256 price, bool currencyIsCurrency0) internal pure returns (uint256 priceX192) {
// Prevent division by zero
if (price == 0) {
revert PriceIsZero(price);
}
// If currency is currency0, we need to invert the price (price = currency1/currency0)
if (currencyIsCurrency0) {
// If the inverted price is greater than uint160.max it will revert in FullMath
// Catch it explicitly here and revert with PriceTooHigh
if ((Q192 / price) >> 160 != 0) {
revert PriceTooHigh(Q192 / price, type(uint160).max);
}
// Invert the Q96 price using FullMath with 512 bits of precision
// Equivalent to finding the inverse then shifting left 96 bits
priceX192 = FullMath.mulDiv(Q192, FixedPoint96.Q96, price);
} else {
// Otherwise, revert if the price exceeds uint160.max
if (price >> 160 != 0) {
revert PriceTooHigh(price, type(uint160).max);
}
priceX192 = price << FixedPoint96.RESOLUTION;
}
}
/// @notice Converts a Q192 price to Uniswap v4 sqrtPriceX96 format
/// @dev Converts price from Q192 to sqrtPriceX96 format
/// @param priceX192 The price in Q192 fixed-point format
/// @return sqrtPriceX96 The square root price in Q96 fixed-point format
function convertToSqrtPriceX96(uint256 priceX192) internal pure returns (uint160 sqrtPriceX96) {
// Calculate square root for Uniswap v4's sqrtPriceX96 format
// This will lose some precision and be rounded down
sqrtPriceX96 = uint160(Math.sqrt(priceX192));
if (sqrtPriceX96 < TickMath.MIN_SQRT_PRICE || sqrtPriceX96 > TickMath.MAX_SQRT_PRICE) {
revert SqrtPriceX96OutOfBounds(sqrtPriceX96, TickMath.MIN_SQRT_PRICE, TickMath.MAX_SQRT_PRICE);
}
return sqrtPriceX96;
}
/// @notice Calculates token amount based on currency amount and price
/// @dev Uses Q192 fixed-point arithmetic for precision
/// @param priceX192 The price in Q192 fixed-point format
/// @param currencyAmount The amount of currency to convert
/// @param currencyIsCurrency0 True if the currency is currency0 (lower address)
/// @param reserveTokenAmount The reserve supply of the token
/// @return tokenAmount The calculated token amount
/// @return correspondingCurrencyAmount The corresponding currency amount
function calculateAmounts(
uint256 priceX192,
uint128 currencyAmount,
bool currencyIsCurrency0,
uint128 reserveTokenAmount
) internal pure returns (uint128 tokenAmount, uint128 correspondingCurrencyAmount) {
// calculates corresponding token amount based on currency amount and price
uint256 tokenAmountUint256 = currencyIsCurrency0
? FullMath.mulDiv(priceX192, currencyAmount, Q192)
: FullMath.mulDiv(currencyAmount, Q192, priceX192);
// if token amount is greater than reserve supply, there is leftover currency. we need to find new currency amount based on reserve supply and price.
if (tokenAmountUint256 > reserveTokenAmount) {
uint256 correspondingCurrencyAmountUint256 = currencyIsCurrency0
? FullMath.mulDiv(reserveTokenAmount, Q192, priceX192)
: FullMath.mulDiv(priceX192, reserveTokenAmount, Q192);
if (correspondingCurrencyAmountUint256 > type(uint128).max) {
revert AmountOverflow(correspondingCurrencyAmountUint256);
}
correspondingCurrencyAmount = uint128(correspondingCurrencyAmountUint256);
tokenAmount = reserveTokenAmount; // tokenAmount will never be greater than reserveTokenAmount
} else {
correspondingCurrencyAmount = currencyAmount;
// tokenAmountUint256 is less than or equal to reserveTokenAmount which is less than or equal to type(uint128).max
tokenAmount = uint128(tokenAmountUint256);
}
return (tokenAmount, correspondingCurrencyAmount);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ILBPStrategyBase} from "ll/interfaces/ILBPStrategyBase.sol";
/// @title ILBPStrategyBasic
/// @notice Legacy alias for ILBPStrategyBase
interface ILBPStrategyBasic is ILBPStrategyBase {}// 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: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
interface ICallOptionFactory {
function strikePriceX96() external view returns (uint160);
function strikeSet() external view returns (bool);
}
/// @title CallOption
/// @notice European-style call option with factory-set strike price
contract CallOption {
using SafeERC20 for IERC20;
uint256 public constant MIN_VESTING = 365 days;
address public immutable token;
address public immutable treasury;
address public immutable buybackAddress;
address public immutable factory;
address public team;
uint256 public immutable totalAmount;
uint256 public immutable vestingStart;
uint256 public vestingEnd;
uint256 public exercised;
event HolderChanged(address indexed oldHolder, address indexed newHolder);
event Exercised(address indexed holder, uint256 tokenAmount, uint256 ethPaid);
error InvalidAddress();
error InvalidAmount();
error Unauthorized();
error StrikeNotSet();
error VestingTooShort();
constructor(
address _token,
address _team,
uint256 _totalAmount,
address _buybackAddress,
address _treasury,
address _factory,
uint256 _vestingEnd
) {
if (_token == address(0) || _team == address(0)) revert InvalidAddress();
if (_buybackAddress == address(0) || _treasury == address(0) || _factory == address(0)) {
revert InvalidAddress();
}
if (_totalAmount == 0) revert InvalidAmount();
token = _token;
team = _team;
totalAmount = _totalAmount;
buybackAddress = _buybackAddress;
treasury = _treasury;
factory = _factory;
vestingStart = block.timestamp;
if (_vestingEnd < vestingStart + MIN_VESTING) revert VestingTooShort();
vestingEnd = _vestingEnd;
}
function updateTeam(address newTeam) external {
if (msg.sender != team) revert Unauthorized();
if (newTeam == address(0)) revert InvalidAddress();
address old = team;
team = newTeam;
emit HolderChanged(old, newTeam);
}
function getExercisableAmount() public view returns (uint256) {
if (block.timestamp >= vestingEnd) {
return totalAmount - exercised;
}
uint256 elapsed = block.timestamp - vestingStart;
uint256 duration = vestingEnd - vestingStart;
uint256 vested = (totalAmount * elapsed) / duration;
return vested > exercised ? vested - exercised : 0;
}
function exercise(uint256 tokenAmount) external payable {
if (msg.sender != team) revert Unauthorized();
if (!ICallOptionFactory(factory).strikeSet()) revert StrikeNotSet();
if (tokenAmount == 0) revert InvalidAmount();
if (tokenAmount > getExercisableAmount()) revert InvalidAmount();
uint160 strikePriceX96 = ICallOptionFactory(factory).strikePriceX96();
uint256 sqrtPriceSquared = uint256(strikePriceX96) * uint256(strikePriceX96);
uint256 ethRequired = FullMath.mulDiv(tokenAmount, sqrtPriceSquared, 1 << 192);
if (msg.value < ethRequired) revert InvalidAmount();
exercised += tokenAmount;
uint256 treasuryAmount = ethRequired / 100;
uint256 buybackAmount = ethRequired - treasuryAmount;
(bool success1,) = treasury.call{value: treasuryAmount}("");
if (!success1) revert InvalidAmount();
(bool success2,) = buybackAddress.call{value: buybackAmount}("");
if (!success2) revert InvalidAmount();
IERC20(token).safeTransfer(team, tokenAmount);
if (msg.value > ethRequired) {
(bool refund,) = msg.sender.call{value: msg.value - ethRequired}("");
if (!refund) revert InvalidAmount();
}
emit Exercised(team, tokenAmount, ethRequired);
}
receive() external payable {}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IEIP712 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}// 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) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";// 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: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Arrays.sol)
// This file was procedurally generated from scripts/generate/templates/Arrays.js.
pragma solidity ^0.8.20;
import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
using SlotDerivation for bytes32;
using StorageSlot for bytes32;
/**
* @dev Sort an array of uint256 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
uint256[] memory array,
function(uint256, uint256) pure returns (bool) comp
) internal pure returns (uint256[] memory) {
_quickSort(_begin(array), _end(array), comp);
return array;
}
/**
* @dev Variant of {sort} that sorts an array of uint256 in increasing order.
*/
function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
sort(array, Comparators.lt);
return array;
}
/**
* @dev Sort an array of address (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
address[] memory array,
function(address, address) pure returns (bool) comp
) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of address in increasing order.
*/
function sort(address[] memory array) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Sort an array of bytes32 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
bytes32[] memory array,
function(bytes32, bytes32) pure returns (bool) comp
) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
*/
function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
* at end (exclusive). Sorting follows the `comp` comparator.
*
* Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
*
* IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
* be used only if the limits are within a memory array.
*/
function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
unchecked {
if (end - begin < 0x40) return;
// Use first element as pivot
uint256 pivot = _mload(begin);
// Position where the pivot should be at the end of the loop
uint256 pos = begin;
for (uint256 it = begin + 0x20; it < end; it += 0x20) {
if (comp(_mload(it), pivot)) {
// If the value stored at the iterator's position comes before the pivot, we increment the
// position of the pivot and move the value there.
pos += 0x20;
_swap(pos, it);
}
}
_swap(begin, pos); // Swap pivot into place
_quickSort(begin, pos, comp); // Sort the left side of the pivot
_quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
}
}
/**
* @dev Pointer to the memory location of the first element of `array`.
*/
function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
assembly ("memory-safe") {
ptr := add(array, 0x20)
}
}
/**
* @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
* that comes just after the last element of the array.
*/
function _end(uint256[] memory array) private pure returns (uint256 ptr) {
unchecked {
return _begin(array) + array.length * 0x20;
}
}
/**
* @dev Load memory word (as a uint256) at location `ptr`.
*/
function _mload(uint256 ptr) private pure returns (uint256 value) {
assembly {
value := mload(ptr)
}
}
/**
* @dev Swaps the elements memory location `ptr1` and `ptr2`.
*/
function _swap(uint256 ptr1, uint256 ptr2) private pure {
assembly {
let value1 := mload(ptr1)
let value2 := mload(ptr2)
mstore(ptr1, value2)
mstore(ptr2, value1)
}
}
/// @dev Helper: low level cast address memory array to uint256 memory array
function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 memory array to uint256 memory array
function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast address comp function to uint256 comp function
function _castToUint256Comp(
function(address, address) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 comp function to uint256 comp function
function _castToUint256Comp(
function(bytes32, bytes32) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* NOTE: The `array` is expected to be sorted in ascending order, and to
* contain no repeated elements.
*
* IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
* support for repeated elements in the array. The {lowerBound} function should
* be used instead.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && unsafeAccess(array, low - 1).value == element) {
return low - 1;
} else {
return low;
}
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value greater or equal than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
*/
function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value strictly greater than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
*/
function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Same as {lowerBound}, but with an array in memory.
*/
function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Same as {upperBound}, but with an array in memory.
*/
function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getAddressSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytes32Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getUint256Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes[] storage arr, uint256 pos) internal pure returns (StorageSlot.BytesSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytesSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(string[] storage arr, uint256 pos) internal pure returns (StorageSlot.StringSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getStringSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes[] memory arr, uint256 pos) internal pure returns (bytes memory res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(string[] memory arr, uint256 pos) internal pure returns (string memory res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(address[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(uint256[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(bytes[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(string[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
}// 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: 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
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
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;
}
/**
* @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[50] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @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.
*
* _Available since v3.1._
*/
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 `account`.
*/
function renounceRole(bytes32 role, address account) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/MathUpgradeable.sol";
import "./math/SignedMathUpgradeable.sol";
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = MathUpgradeable.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMathUpgradeable.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, MathUpgradeable.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import {Initializable} from "../../proxy/utils/Initializable.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);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @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[50] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @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 IERC1822ProxiableUpgradeable {
/**
* @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 v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/IERC1967Upgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import {Initializable} from "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable, IERC1967Upgradeable {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
function __ERC1967Upgrade_init() internal onlyInitializing {
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
AddressUpgradeable.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {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 bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
AddressUpgradeable.functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @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[50] private __gap;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
/// @notice Returns ceil(x / y)
/// @dev division by 0 will return 0, and should be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly ("memory-safe") {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
/// @notice Calculates floor(a×b÷denominator)
/// @dev division by 0 will return 0, and should be checked externally
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result, floor(a×b÷denominator)
function simpleMulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
assembly ("memory-safe") {
result := div(mul(a, b), denominator)
}
}
}// 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.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
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(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 {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}// 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 via unlock callback, then transfer
poolManager.unlock(abi.encode(IMultiPositionManager.Action.ZERO_BURN, ""));
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 < 2;) {
IMultiPositionManager.Range memory limitRange = s.limitPositions[i];
if (limitRange.lowerTick != limitRange.upperTick) {
(, uint256 amount0, uint256 amount1, uint256 feesOwed0, uint256 feesOwed1) =
PoolManagerUtils.getAmountsOf(poolManager, s.poolKey, limitRange);
unchecked {
total0 += amount0;
total1 += amount1;
totalFee0 += feesOwed0;
totalFee1 += feesOwed1;
}
}
unchecked {
++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][]));
// Calculate fees owed before burning liquidity (burning clears fee growth state)
uint256 totalFee0;
uint256 totalFee1;
{
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;
}
}
IMultiPositionManager.Range[2] memory limitRangesArray;
limitRangesArray[0] = s.limitPositions[0];
limitRangesArray[1] = s.limitPositions[1];
(totalFee0, totalFee1) =
PoolManagerUtils.getTotalFeesOwed(poolManager, s.poolKey, baseRangesArray, limitRangesArray);
}
// Burn all positions
(uint256 amount0, uint256 amount1) =
PositionLogic.burnLiquidities(poolManager, s, totalSupply, totalSupply, outMin);
// Mint protocol fee claims based on total fees collected
uint256 treasuryFee0 = totalFee0 / s.fee;
uint256 treasuryFee1 = totalFee1 / s.fee;
if (treasuryFee0 != 0) {
poolManager.mint(address(this), uint256(uint160(Currency.unwrap(s.currency0))), treasuryFee0);
}
if (treasuryFee1 != 0) {
poolManager.mint(address(this), uint256(uint160(Currency.unwrap(s.currency1))), treasuryFee1);
}
// 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: MIT
// OpenZeppelin Contracts (last updated v5.3.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 ERC-20
* applications.
*/
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}.
*
* Both 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}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* 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:
*
* ```solidity
* 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 {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 {IMultiPositionFactory} from "../interfaces/IMultiPositionFactory.sol";
import {ILiquidityStrategy} from "../strategies/ILiquidityStrategy.sol";
import {SharedStructs} from "../base/SharedStructs.sol";
import {RebalanceLogic} from "./RebalanceLogic.sol";
/**
* @title RebalanceSwapLogic
* @notice Swap execution and swap-based rebalance helpers split from RebalanceLogic to reduce byte size.
*/
library RebalanceSwapLogic {
using PoolIdLibrary for PoolKey;
using StateLibrary for IPoolManager;
using SafeERC20 for IERC20;
error InvalidAggregator();
error InsufficientTokensForSwap();
error InsufficientOutput();
error NoStrategySpecified();
event SwapExecuted(address indexed aggregator, uint256 amountIn, uint256 amountOut, bool swapToken0);
/**
* @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, RebalanceLogic.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 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,
RebalanceLogic.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, s.factory);
emit SwapExecuted(
IMultiPositionFactory(s.factory).aggregatorAddress(uint8(swapParams.aggregator)),
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 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(
RebalanceLogic.SwapParams calldata params,
uint256 amount0,
uint256 amount1,
address currency0,
address currency1,
address factory
) private returns (uint256 amountOut) {
// Validate aggregator type and address (prevents arbitrary contract calls)
if (uint8(params.aggregator) > 3) revert InvalidAggregator();
address approvedAggregator = IMultiPositionFactory(factory).aggregatorAddress(uint8(params.aggregator));
if (approvedAggregator == address(0) || params.aggregatorAddress != approvedAggregator) {
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(approvedAggregator, 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,) = approvedAggregator.call{value: ethValue}(params.swapData);
// Reset approval for security (skip if native ETH)
if (!isETHIn) {
IERC20(inputToken).forceApprove(approvedAggregator, 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());
RebalanceLogic.StrategyContext memory ctx =
_buildStrategyContext(s, params, amount0, amount1, sqrtPriceX96, currentTick);
(baseRanges, liquidities) = RebalanceLogic.generateRangesAndLiquidities(s, poolManager, ctx, amount0, amount1);
RebalanceLogic._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 (RebalanceLogic.StrategyContext memory ctx) {
ctx.useAssetWeights = (params.weight0 == 0 && params.weight1 == 0);
if (ctx.useAssetWeights) {
(ctx.weight0, ctx.weight1) = RebalanceLogic.calculateWeightsFromAmounts(amount0, amount1, sqrtPriceX96);
} else {
ctx.weight0 = params.weight0;
ctx.weight1 = params.weight1;
}
if (!ctx.useAssetWeights && ctx.weight0 + ctx.weight1 != 1e18) {
revert RebalanceLogic.InvalidWeightSum();
}
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 {
// Snap to tickSpacing grid using floor division (handles negatives correctly)
int24 tickSpacing = s.poolKey.tickSpacing;
ctx.center = (params.center / tickSpacing) * tickSpacing;
if (params.center < 0 && params.center % tickSpacing != 0) {
ctx.center -= tickSpacing;
}
}
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 (ctx.useAssetWeights) {
ctx.limitWidth = 0;
} else {
ctx.limitWidth = params.limitWidth;
}
if (ctx.resolvedStrategy == address(0)) revert NoStrategySpecified();
ctx.strategy = ILiquidityStrategy(ctx.resolvedStrategy);
}
}// 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;
uint256 limitPositionsLength;
uint256 totalPositions;
}
/**
* @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,
limitPositionsLength: s.limitPositionsLength,
totalPositions: s.basePositionsLength + s.limitPositionsLength
});
// Get current token amounts in each position
uint256[] memory positionToken0 = new uint256[](params.totalPositions);
uint256[] memory positionToken1 = new uint256[](params.totalPositions);
(uint256 totalToken0InPositions, uint256 totalToken1InPositions) =
_populatePositionTokens(s, params, positionToken0, positionToken1);
// If no tokens in positions, fall back to liquidity-based distribution
if (totalToken0InPositions == 0 && totalToken1InPositions == 0) {
// Get total liquidity for fallback
uint256 totalLiquidity = _getTotalLiquidityForFallback(s, params);
if (totalLiquidity == 0) {
// No positions to add to
amounts0 = new uint256[](params.totalPositions);
amounts1 = new uint256[](params.totalPositions);
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.totalPositions);
amounts1 = new uint256[](params.totalPositions);
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
(amount0, amount1) = DepositRatioLib.getRatioAmounts(
totalToken0InPositions, totalToken1InPositions, params.amount0, params.amount1
);
// Now distribute these amounts proportionally based on current holdings
amounts0 = new uint256[](params.totalPositions);
amounts1 = new uint256[](params.totalPositions);
// Distribute token0 to positions that hold token0
if (totalToken0InPositions != 0 && amount0 != 0) {
for (uint256 i = 0; i < params.totalPositions;) {
if (positionToken0[i] != 0) {
amounts0[i] = FullMath.mulDiv(amount0, positionToken0[i], totalToken0InPositions);
}
unchecked {
++i;
}
}
}
// Distribute token1 to positions that hold token1
if (totalToken1InPositions != 0 && amount1 != 0) {
for (uint256 i = 0; i < params.totalPositions;) {
if (positionToken1[i] != 0) {
amounts1[i] = FullMath.mulDiv(amount1, positionToken1[i], totalToken1InPositions);
}
unchecked {
++i;
}
}
}
}
function _populatePositionTokens(
SharedStructs.ManagerStorage storage s,
DepositAmountsParams memory params,
uint256[] memory positionToken0,
uint256[] memory positionToken1
) private view returns (uint256 totalToken0InPositions, uint256 totalToken1InPositions) {
// 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
uint256 limitIndex;
for (uint8 i = 0; i < 2;) {
IMultiPositionManager.Range memory limitRange = s.limitPositions[i];
if (limitRange.lowerTick != limitRange.upperTick) {
uint256 idx = params.basePositionsLength + limitIndex;
(, uint256 amount0InPos, uint256 amount1InPos,,) =
PoolManagerUtils.getAmountsOf(params.poolManager, params.poolKey, limitRange);
positionToken0[idx] = amount0InPos;
positionToken1[idx] = amount1InPos;
unchecked {
totalToken0InPositions += amount0InPos;
totalToken1InPositions += amount1InPos;
++limitIndex;
}
}
unchecked {
++i;
}
}
}
function _getTotalLiquidityForFallback(SharedStructs.ManagerStorage storage s, DepositAmountsParams memory params)
private
view
returns (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;
}
}
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;
}
}
}
/**
* @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 limitIndex;
for (uint8 i = 0; i < 2;) {
if (s.limitPositions[i].lowerTick != s.limitPositions[i].upperTick) {
uint256 idx = baseLength + limitIndex;
if (amounts0[idx] != 0 || amounts1[idx] != 0) {
PoolManagerUtils._mintLiquidityForAmounts(
poolManager, s.poolKey, s.limitPositions[i], amounts0[idx], amounts1[idx], inMin[idx]
);
}
unchecked {
++limitIndex;
}
}
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: 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: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {ActionConstants} from "@uniswap/v4-periphery/src/libraries/ActionConstants.sol";
import {FullRangeParams, OneSidedParams, TickBounds} from "../types/PositionTypes.sol";
import {DynamicArray} from "./DynamicArray.sol";
/// @title ParamsBuilder
/// @notice Library for building position parameters
library ParamsBuilder {
using DynamicArray for bytes[];
/// @notice Empty bytes used as hook data when minting positions since no hook data is needed
bytes constant ZERO_BYTES = new bytes(0);
/// @notice Initializes the parameters, allocating memory for maximum number of params
function init() internal pure returns (bytes[] memory params) {
return DynamicArray.init();
}
/// @notice Builds the parameters needed to mint a full range position using the position manager
/// @param params The parameters array to populate
/// @param fullRangeParams The amounts of currency and token that will be used to mint the position
/// @param poolKey The pool key
/// @param bounds The tick bounds for the full range position
/// @param currencyIsCurrency0 Whether the currency address is less than the token address
/// @param positionRecipient The recipient of the position
/// @return params The parameters needed to mint a full range position using the position manager
function addFullRangeParams(
bytes[] memory params,
FullRangeParams memory fullRangeParams,
PoolKey memory poolKey,
TickBounds memory bounds,
bool currencyIsCurrency0,
address positionRecipient,
uint128 liquidity
) internal pure returns (bytes[] memory) {
uint128 amount0 = currencyIsCurrency0 ? fullRangeParams.currencyAmount : fullRangeParams.tokenAmount;
uint128 amount1 = currencyIsCurrency0 ? fullRangeParams.tokenAmount : fullRangeParams.currencyAmount;
// Set up mint
params = params.append(
abi.encode(
poolKey, bounds.lowerTick, bounds.upperTick, liquidity, amount0, amount1, positionRecipient, ZERO_BYTES
)
);
// Send the position manager's full balance of both currencies to cover both positions
// This includes any pre-existing tokens in the position manager, which will be sent to the pool manager
// and ultimately transferred to the LBP contract at the end.
// Set up settlement for currency0
params = params.append(abi.encode(poolKey.currency0, ActionConstants.CONTRACT_BALANCE, false)); // payerIsUser is false because position manager will be the payer
// Set up settlement for currency1
params = params.append(abi.encode(poolKey.currency1, ActionConstants.CONTRACT_BALANCE, false)); // payerIsUser is false because position manager will be the payer
return params;
}
/// @notice Builds the parameters needed to mint a one-sided position using the position manager
/// @param params The parameters array to populate
/// @param oneSidedParams The data specific to creating the one-sided position
/// @param poolKey The pool key
/// @param bounds The tick bounds for the one-sided position
/// @param currencyIsCurrency0 Whether the currency address is less than the token address
/// @param positionRecipient The recipient of the position
/// @return params The parameters needed to mint a one-sided position using the position manager
function addOneSidedParams(
bytes[] memory params,
OneSidedParams memory oneSidedParams,
PoolKey memory poolKey,
TickBounds memory bounds,
bool currencyIsCurrency0,
address positionRecipient,
uint128 liquidity
) internal pure returns (bytes[] memory) {
// Determine which currency (0 or 1) receives the one-sided liquidity amount
// XOR logic: position uses currency1 when:
// - currencyIsCurrency0=true AND inToken=true (currency is 0, position in token which is 1)
// - currencyIsCurrency0=false AND inToken=false (currency is 1, position in currency which is 1)
bool useAmountInCurrency1 = currencyIsCurrency0 == oneSidedParams.inToken;
// Set the amount to the appropriate currency slot
uint256 amount0 = useAmountInCurrency1 ? 0 : oneSidedParams.amount;
uint256 amount1 = useAmountInCurrency1 ? oneSidedParams.amount : 0;
// Set up mint for token
return params.append(
abi.encode(
poolKey, bounds.lowerTick, bounds.upperTick, liquidity, amount0, amount1, positionRecipient, ZERO_BYTES
)
);
}
/// @notice Builds the parameters needed to take the pair using the position manager
/// @param params The parameters array to populate
/// @param currency0 The currency0 address
/// @param currency1 The currency1 address
/// @return params The parameters needed to take the pair using the position manager
function addTakePairParams(bytes[] memory params, address currency0, address currency1)
internal
view
returns (bytes[] memory)
{
// Take any open deltas from the pool manager and send back to the lbp
return params.append(abi.encode(Currency.wrap(currency0), Currency.wrap(currency1), address(this)));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Actions} from "@uniswap/v4-periphery/src/libraries/Actions.sol";
/// @title ActionsBuilder
/// @notice Library for building position actions and parameters
library ActionsBuilder {
/// @notice Initializes an empty actions byte array
function init() internal pure returns (bytes memory actions) {
actions = new bytes(0);
}
/// @notice Add mint action to actions byte array
function addMint(bytes memory actions) internal pure returns (bytes memory) {
return abi.encodePacked(actions, uint8(Actions.MINT_POSITION));
}
/// @notice Add settle action to actions byte array
function addSettle(bytes memory actions) internal pure returns (bytes memory) {
return abi.encodePacked(actions, uint8(Actions.SETTLE));
}
/// @notice Add take pair action to actions byte array
function addTakePair(bytes memory actions) internal pure returns (bytes memory) {
return abi.encodePacked(actions, uint8(Actions.TAKE_PAIR));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
/// @title TickCalculations
/// @notice Library for tick calculations
library TickCalculations {
/// @notice Derives max liquidity per tick from given tick spacing
/// @dev Taken directly from Pool.sol
/// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing` (cannot be 0)
/// e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ...
/// @return result The max liquidity per tick
function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) internal pure returns (uint128 result) {
int24 MAX_TICK = TickMath.MAX_TICK;
int24 MIN_TICK = TickMath.MIN_TICK;
assembly ("memory-safe") {
tickSpacing := signextend(2, tickSpacing)
let minTick := sub(sdiv(MIN_TICK, tickSpacing), slt(smod(MIN_TICK, tickSpacing), 0))
let maxTick := sdiv(MAX_TICK, tickSpacing)
let numTicks := add(sub(maxTick, minTick), 1)
result := div(sub(shl(128, 1), 1), numTicks)
}
}
/// @notice Rounds down to the nearest tick spacing if needed
/// @param tick The tick to round down
/// @param tickSpacing The tick spacing to round down to (cannot be 0)
/// @return The rounded down tick
function tickFloor(int24 tick, int24 tickSpacing) internal pure returns (int24) {
unchecked {
int24 remainder = tick % tickSpacing;
return remainder >= 0 ? tick - remainder : tick - remainder - tickSpacing;
}
}
/// @notice Rounds up to the next tick spacing
/// @param tick The tick to round up
/// @param tickSpacing The tick spacing to round up to (cannot be 0)
/// @return The rounded up tick
function tickStrictCeil(int24 tick, int24 tickSpacing) internal pure returns (int24) {
unchecked {
int24 remainder = tick % tickSpacing;
return remainder >= 0 ? tick + tickSpacing - remainder : tick - remainder;
}
}
}// // SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// @title DynamicArray
/// @notice Library for building dynamic byte arrays. Increase the `MAX_PARAMS_SIZE` to support more parameters.
library DynamicArray {
/// @notice Error thrown when the array length overflows the maximum size
error LengthOverflow();
/// @notice The maximum number of parameters that can be stored in the array
uint24 constant MAX_PARAMS_SIZE = 6;
/// @notice Initializes a new array in memory with the maximum size
function init() internal pure returns (bytes[] memory params) {
params = new bytes[](MAX_PARAMS_SIZE);
assembly {
mstore(params, 0) // Set initial length to 0
}
}
/// @notice Appends a new parameter to the array
/// @param params The existing array created via `init`
/// @param param The new parameter to append
function append(bytes[] memory params, bytes memory param) internal pure returns (bytes[] memory) {
assembly {
// Always read length via assembly to avoid optimizer assumptions
let length := mload(params)
if iszero(lt(length, MAX_PARAMS_SIZE)) {
mstore(0x00, 0x8ecbb27e) // LengthOverflow() selector
revert(0x1c, 0x04)
}
let slot := add(add(params, 0x20), mul(length, 0x20))
mstore(slot, param)
mstore(params, add(length, 1)) // Increment length
}
return params;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(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.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* 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 {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 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 low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, 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 ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
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⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// 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²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev 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) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @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 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @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: 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.1.0) (utils/Comparators.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides a set of functions to compare values.
*
* _Available since v5.1._
*/
library Comparators {
function lt(uint256 a, uint256 b) internal pure returns (bool) {
return a < b;
}
function gt(uint256 a, uint256 b) internal pure returns (bool) {
return a > b;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/SlotDerivation.sol)
// This file was procedurally generated from scripts/generate/templates/SlotDerivation.js.
pragma solidity ^0.8.20;
/**
* @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
* corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
* the solidity language / compiler.
*
* See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
*
* Example usage:
* ```solidity
* contract Example {
* // Add the library methods
* using StorageSlot for bytes32;
* using SlotDerivation for bytes32;
*
* // Declare a namespace
* string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
*
* function setValueInNamespace(uint256 key, address newValue) internal {
* _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
* }
*
* function getValueInNamespace(uint256 key) internal view returns (address) {
* return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
* }
* }
* ```
*
* TIP: Consider using this library along with {StorageSlot}.
*
* NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
* upgrade safety will ignore the slots accessed through this library.
*
* _Available since v5.1._
*/
library SlotDerivation {
/**
* @dev Derive an ERC-7201 slot from a string (namespace).
*/
function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
assembly ("memory-safe") {
mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
slot := and(keccak256(0x00, 0x20), not(0xff))
}
}
/**
* @dev Add an offset to a slot to get the n-th element of a structure or an array.
*/
function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
unchecked {
return bytes32(uint256(slot) + pos);
}
}
/**
* @dev Derive the location of the first element in an array from the slot where the length is stored.
*/
function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, slot)
result := keccak256(0x00, 0x20)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, and(key, shr(96, not(0))))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, iszero(iszero(key)))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* 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;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 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) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
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) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
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) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}// 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
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// 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.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 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 + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMathUpgradeable {
/**
* @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 v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @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 v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*
* _Available since v4.8.3._
*/
interface IERC1967Upgradeable {
/**
* @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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.0;
/**
* @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(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
* _Available since v4.9 for `string`, `bytes`._
*/
library StorageSlotUpgradeable {
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.1.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 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 ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-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 ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 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: 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);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Library to define different pool actions.
/// @dev These are suggested common commands, however additional commands should be defined as required
/// Some of these actions are not supported in the Router contracts or Position Manager contracts, but are left as they may be helpful commands for other peripheral contracts.
library Actions {
// pool actions
// liquidity actions
uint256 internal constant INCREASE_LIQUIDITY = 0x00;
uint256 internal constant DECREASE_LIQUIDITY = 0x01;
uint256 internal constant MINT_POSITION = 0x02;
uint256 internal constant BURN_POSITION = 0x03;
uint256 internal constant INCREASE_LIQUIDITY_FROM_DELTAS = 0x04;
uint256 internal constant MINT_POSITION_FROM_DELTAS = 0x05;
// swapping
uint256 internal constant SWAP_EXACT_IN_SINGLE = 0x06;
uint256 internal constant SWAP_EXACT_IN = 0x07;
uint256 internal constant SWAP_EXACT_OUT_SINGLE = 0x08;
uint256 internal constant SWAP_EXACT_OUT = 0x09;
// donate
// note this is not supported in the position manager or router
uint256 internal constant DONATE = 0x0a;
// closing deltas on the pool manager
// settling
uint256 internal constant SETTLE = 0x0b;
uint256 internal constant SETTLE_ALL = 0x0c;
uint256 internal constant SETTLE_PAIR = 0x0d;
// taking
uint256 internal constant TAKE = 0x0e;
uint256 internal constant TAKE_ALL = 0x0f;
uint256 internal constant TAKE_PORTION = 0x10;
uint256 internal constant TAKE_PAIR = 0x11;
uint256 internal constant CLOSE_CURRENCY = 0x12;
uint256 internal constant CLEAR_OR_TAKE = 0x13;
uint256 internal constant SWEEP = 0x14;
uint256 internal constant WRAP = 0x15;
uint256 internal constant UNWRAP = 0x16;
// minting/burning 6909s to close deltas
// note this is not supported in the position manager or router
uint256 internal constant MINT_6909 = 0x17;
uint256 internal constant BURN_6909 = 0x18;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}{
"remappings": [
"@ensdomains/=lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin/=lib/liquidity-launcher/lib/openzeppelin-contracts/",
"@openzeppelin/contracts/=lib/liquidity-launcher/lib/openzeppelin-contracts/contracts/",
"@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-core/=lib/v4-periphery/lib/v4-core/",
"@uniswap/v4-periphery/=lib/v4-periphery/",
"@uniswap/uerc20-factory/=lib/liquidity-launcher/lib/uerc20-factory/src/",
"blocknumberish/=lib/liquidity-launcher/lib/blocknumberish/",
"ds-test/=lib/v4-periphery/lib/v4-core/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/liquidity-launcher/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/liquidity-launcher/lib/openzeppelin-contracts/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"permit2/=lib/v4-periphery/lib/permit2/",
"solady/=lib/liquidity-launcher/lib/solady/src/",
"solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
"v4-core/=lib/v4-periphery/lib/v4-core/src/",
"v4-periphery/=lib/v4-periphery/",
"scripts/=lib/liquidity-launcher/lib/optimism/packages/contracts-bedrock/scripts/",
"liquidity-launcher/src/token-factories/uerc20-factory/=lib/liquidity-launcher/lib/uerc20-factory/src/",
"liquidity-launcher/src/=lib/liquidity-launcher/src/",
"liquidity-launcher/=lib/liquidity-launcher/",
"periphery/=lib/liquidity-launcher/src/periphery/",
"continuous-clearing-auction/=lib/liquidity-launcher/lib/continuous-clearing-auction/",
"ll/=lib/liquidity-launcher/src/"
],
"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":"contract OrderBookFactory","name":"_orderBookFactory","type":"address"},{"internalType":"contract IPoolManager","name":"_poolManager","type":"address"},{"internalType":"address","name":"_liquidityLauncher","type":"address"},{"internalType":"address","name":"_ccaFactory","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"maxAmount","type":"uint256"}],"name":"InvalidAmount","type":"error"},{"inputs":[],"name":"InvalidConfigData","type":"error"},{"inputs":[],"name":"UnauthorizedCaller","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"distributionContract","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"totalSupply","type":"uint256"}],"name":"DistributionInitialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"strategy","type":"address"},{"indexed":true,"internalType":"address","name":"hookOwner","type":"address"}],"name":"PoolReservedForStrategy","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"strategy","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"SuperchainLBPStrategyCreated","type":"event"},{"inputs":[],"name":"ccaFactory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"deployer","outputs":[{"internalType":"contract SuperchainLBPStrategyDeployer","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"configData","type":"bytes"},{"internalType":"bytes32","name":"salt","type":"bytes32"}],"name":"initializeDistribution","outputs":[{"internalType":"contract IDistributionContract","name":"distributionContract","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"liquidityLauncher","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"orderBookFactory","outputs":[{"internalType":"contract IOrderBookFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolManager","outputs":[{"internalType":"contract IPoolManager","name":"","type":"address"}],"stateMutability":"view","type":"function"}]Contract Creation Code
610120604052348015610010575f80fd5b5060405161697038038061697083398101604081905261002f9161015d565b6001600160a01b03841661005657604051637f34059360e11b815260040160405180910390fd5b6001600160a01b03831661007d57604051637f34059360e11b815260040160405180910390fd5b6001600160a01b0382166100a457604051637f34059360e11b815260040160405180910390fd5b6001600160a01b0381166100cb57604051637f34059360e11b815260040160405180910390fd5b6001600160a01b0380851660805283811660a05282811660e05281166101005260405130906100f990610139565b6001600160a01b039091168152602001604051809103905ff080158015610122573d5f803e3d5ffd5b506001600160a01b031660c052506101b992505050565b6159d480610f9c83390190565b6001600160a01b038116811461015a575f80fd5b50565b5f805f8060808587031215610170575f80fd5b845161017b81610146565b602086015190945061018c81610146565b604086015190935061019d81610146565b60608601519092506101ae81610146565b939692955090935050565b60805160a05160c05160e05161010051610d7f61021d5f395f818160ce015261034b01525f818160a7015261017001525f818161011b01526105bc01525f8181610142015261052901525f818160f20152818161047801526105510152610d7f5ff3fe608060405234801561000f575f80fd5b506004361061006f575f3560e01c80638364d95f1161004d5780638364d95f146100f0578063d5f3948814610116578063dc4c90d31461013d575f80fd5b806303770504146100735780633e8e4ee8146100a2578063688e6956146100c9575b5f80fd5b61008661008136600461066a565b610164565b6040516001600160a01b03909116815260200160405180910390f35b6100867f000000000000000000000000000000000000000000000000000000000000000081565b6100867f000000000000000000000000000000000000000000000000000000000000000081565b7f0000000000000000000000000000000000000000000000000000000000000000610086565b6100867f000000000000000000000000000000000000000000000000000000000000000081565b6100867f000000000000000000000000000000000000000000000000000000000000000081565b5f336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146101ae57604051635c427cd960e01b815260040160405180910390fd5b6001600160801b038511156101d657604051637f34059360e11b815260040160405180910390fd5b6101e386868686866101ed565b9695505050505050565b5f806101f98585610260565b9050610207878785846103ed565b6040516001600160801b03881681529092506001600160a01b0380891691908416907f34d4b985fe12d4cd11d805af2817afb1a621368fd44b86f2a6d21cd238348bfe9060200160405180910390a35095945050505050565b61032e6040805161022081019091525f60e08201818152610100830182905261012083018290526101408301829052610160830182905261018083018290526101a083018290526101c083018290526101e083018290526102008301919091528190815260408051610100810182525f8082526020828101829052928201819052606082018190526080820181905260a0820181905260c0820181905260e08201529101908152606060208201819052604082018190525f9082018190526080820181905260a09091015290565b5f808080808080610341898b018b6108df565b6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660a08901526020880151979e50959c50939a5091985096509450925016156103a757604051637f34059360e11b815260040160405180910390fd5b6040805160e081018252978852602088019690965294860193909352606085019190915260808401526001600160a01b0390811660a08401521660c08201529392505050565b5f806040518060800160405280876001600160a01b03168152602001866001600160801b03168152602001858152602001846080015181525090505f61044f82855f01518660200151876040015188606001518960a001518a60c001516104dc565b6040516331fa95d960e01b81526001600160a01b038083166004830152600160248301529192507f0000000000000000000000000000000000000000000000000000000000000000909116906331fa95d9906044015f604051808303815f87803b1580156104bb575f80fd5b505af11580156104cd573d5f803e3d5ffd5b50929998505050505050505050565b6040808801516060808a015183516101a0810185528b516001600160a01b0390811682526020808e01516001600160801b0316908301528186018c90529281018890525f608082018190527f0000000000000000000000000000000000000000000000000000000000000000841660a08301527f0000000000000000000000000000000000000000000000000000000000000000841660c083015260e082018b905261010082018a9052610120820183905261014082018590528784166101608301528684166101808301529451631de8802960e31b81529192909185917f0000000000000000000000000000000000000000000000000000000000000000169063ef440148906105f39087908690600401610bf4565b6020604051808303815f875af115801561060f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106339190610d27565b9c9b505050505050505050505050565b6001600160a01b0381168114610657575f80fd5b50565b803561066581610643565b919050565b5f805f805f6080868803121561067e575f80fd5b853561068981610643565b945060208601359350604086013567ffffffffffffffff8111156106ab575f80fd5b8601601f810188136106bb575f80fd5b803567ffffffffffffffff8111156106d1575f80fd5b8860208284010111156106e2575f80fd5b959894975060200195606001359392505050565b634e487b7160e01b5f52604160045260245ffd5b604051610100810167ffffffffffffffff8111828210171561072e5761072e6106f6565b60405290565b604051610140810167ffffffffffffffff8111828210171561072e5761072e6106f6565b803567ffffffffffffffff81168114610665575f80fd5b803562ffffff81168114610665575f80fd5b8035600281900b8114610665575f80fd5b80356001600160801b0381168114610665575f80fd5b80358015158114610665575f80fd5b5f61010082840312156107c8575f80fd5b6107d061070a565b905081356107dd81610643565b81526107eb60208301610781565b60208201526107fc6040830161076f565b604082015261080d6060830161076f565b606082015261081e6080830161076f565b608082015260a0828101359082015260c0808301359082015261084360e083016107a8565b60e082015292915050565b5f82601f83011261085d575f80fd5b8135602083015f8067ffffffffffffffff84111561087d5761087d6106f6565b50604051601f19601f85018116603f0116810181811067ffffffffffffffff821117156108ac576108ac6106f6565b6040528381529050808284018710156108c3575f80fd5b838360208301375f602085830101528094505050505092915050565b5f805f805f805f8789036102e08112156108f7575f80fd5b610140811215610905575f80fd5b5061090e610734565b61091789610758565b815261092560208a0161065a565b602082015261093660408a0161076f565b604082015261094760608a01610781565b606082015261095860808a0161076f565b608082015261096960a08a0161065a565b60a082015261097a60c08a0161065a565b60c082015261098b60e08a01610758565b60e082015261099d6101008a0161065a565b6101008201526109b06101208a01610792565b61012082015296506109c6896101408a016107b7565b955061024088013567ffffffffffffffff8111156109e2575f80fd5b6109ee8a828b0161084e565b95505061026088013567ffffffffffffffff811115610a0b575f80fd5b610a178a828b0161084e565b9450506102808801359250610a2f6102a0890161065a565b9150610a3e6102c0890161065a565b905092959891949750929550565b805167ffffffffffffffff1682526020810151610a7460208401826001600160a01b03169052565b506040810151610a8b604084018262ffffff169052565b506060810151610aa0606084018260020b9052565b506080810151610ab7608084018262ffffff169052565b5060a0810151610ad260a08401826001600160a01b03169052565b5060c0810151610aed60c08401826001600160a01b03169052565b5060e0810151610b0960e084018267ffffffffffffffff169052565b50610100810151610b266101008401826001600160a01b03169052565b50610120810151610b436101208401826001600160801b03169052565b505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b6001600160a01b038151168252602081015160020b602083015262ffffff60408201511660408301526060810151610bb5606084018262ffffff169052565b506080810151610bcc608084018262ffffff169052565b5060a081015160a083015260c081015160c083015260e0810151610b4360e084018215159052565b82815260406020820152610c146040820183516001600160a01b03169052565b5f6020830151610c2f60608401826001600160801b03169052565b506040830151610c426080840182610a4c565b5060608301516103a06101c0840152610c5f6103e0840182610b48565b90506080840151610c7c6101e08501826001600160a01b03169052565b5060a08401516001600160a01b0390811661020085015260c08501511661022084015260e0840151610cb2610240850182610b76565b50610100840151838203603f1901610340850152610cd08282610b48565b915050610120840151610360840152610140840151610380840152610160840151610d076103a08501826001600160a01b03169052565b506101808401516001600160a01b0381166103c085015250949350505050565b5f60208284031215610d37575f80fd5b8151610d4281610643565b939250505056fea26469706673582212208f16ddd1301fde714c108553bd2f204f58e886d24767fadfa09ee969a50cb85364736f6c634300081a003360a0604052348015600e575f80fd5b506040516159d43803806159d4833981016040819052602b91603b565b6001600160a01b03166080526066565b5f60208284031215604a575f80fd5b81516001600160a01b0381168114605f575f80fd5b9392505050565b6080516159516100835f395f81816048015260b801526159515ff3fe608060405234801561000f575f80fd5b506004361061003f575f3560e01c80630852f9f314610043578063ef44014814610086578063fd3f13c814610099575b5f80fd5b61006a7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b03909116815260200160405180910390f35b61006a61009436600461051f565b6100ac565b61006a6100a736600461051f565b610133565b5f336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146100f657604051635c427cd960e01b815260040160405180910390fd5b82826040516101049061020c565b61010e9190610832565b8190604051809103905ff590508015801561012b573d5f803e3d5ffd5b509392505050565b5f80604051806020016101459061020c565b601f1982820381018352601f909101166040819052610168908590602001610832565b60408051601f1981840301815290829052610186929160200161097e565b60408051601f1981840301815282825280516020918201207fff00000000000000000000000000000000000000000000000000000000000000828501523060601b6bffffffffffffffffffffffff191660218501526035840197909752605580840197909752815180840390970187526075909201905284519401939093209392505050565b614f818061099b83390190565b634e487b7160e01b5f52604160045260245ffd5b604051610140810167ffffffffffffffff8111828210171561025157610251610219565b60405290565b604051610100810167ffffffffffffffff8111828210171561025157610251610219565b6040516101a0810167ffffffffffffffff8111828210171561025157610251610219565b6001600160a01b03811681146102b3575f80fd5b50565b80356102c18161029f565b919050565b80356fffffffffffffffffffffffffffffffff811681146102c1575f80fd5b803567ffffffffffffffff811681146102c1575f80fd5b803562ffffff811681146102c1575f80fd5b8035600281900b81146102c1575f80fd5b5f6101408284031215610330575f80fd5b61033861022d565b9050610343826102e5565b8152610351602083016102b6565b6020820152610362604083016102fc565b60408201526103736060830161030e565b6060820152610384608083016102fc565b608082015261039560a083016102b6565b60a08201526103a660c083016102b6565b60c08201526103b760e083016102e5565b60e08201526103c961010083016102b6565b6101008201526103dc61012083016102c6565b61012082015292915050565b5f82601f8301126103f7575f80fd5b8135602083015f8067ffffffffffffffff84111561041757610417610219565b50604051601f19601f85018116603f0116810181811067ffffffffffffffff8211171561044657610446610219565b60405283815290508082840187101561045d575f80fd5b838360208301375f602085830101528094505050505092915050565b803580151581146102c1575f80fd5b5f6101008284031215610499575f80fd5b6104a1610257565b905081356104ae8161029f565b81526104bc6020830161030e565b60208201526104cd604083016102fc565b60408201526104de606083016102fc565b60608201526104ef608083016102fc565b608082015260a0828101359082015260c0808301359082015261051460e08301610479565b60e082015292915050565b5f8060408385031215610530575f80fd5b82359150602083013567ffffffffffffffff81111561054d575f80fd5b83016103a0818603121561055f575f80fd5b61056761027b565b610570826102b6565b815261057e602083016102c6565b6020820152610590866040840161031f565b604082015261018082013567ffffffffffffffff8111156105af575f80fd5b6105bb878285016103e8565b6060830152506105ce6101a083016102b6565b60808201526105e06101c083016102b6565b60a08201526105f26101e083016102b6565b60c0820152610605866102008401610488565b60e082015261030082013567ffffffffffffffff811115610624575f80fd5b610630878285016103e8565b6101008301525061032082013561012082015261034082013561014082015261065c61036083016102b6565b61016082015261066f61038083016102b6565b61018082015280925050509250929050565b805167ffffffffffffffff16825260208101516106a960208401826001600160a01b03169052565b5060408101516106c0604084018262ffffff169052565b5060608101516106d5606084018260020b9052565b5060808101516106ec608084018262ffffff169052565b5060a081015161070760a08401826001600160a01b03169052565b5060c081015161072260c08401826001600160a01b03169052565b5060e081015161073e60e084018267ffffffffffffffff169052565b5061010081015161075b6101008401826001600160a01b03169052565b506101208101516107816101208401826fffffffffffffffffffffffffffffffff169052565b505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b6001600160a01b038151168252602081015160020b602083015262ffffff604082015116604083015260608101516107f3606084018262ffffff169052565b50608081015161080a608084018262ffffff169052565b5060a081015160a083015260c081015160c083015260e081015161078160e084018215159052565b6020815261084c6020820183516001600160a01b03169052565b5f602083015161087060408401826fffffffffffffffffffffffffffffffff169052565b5060408301516108836060840182610681565b5060608301516103a06101a08401526108a06103c0840182610786565b905060808401516108bd6101c08501826001600160a01b03169052565b5060a08401516001600160a01b039081166101e085015260c08501511661020084015260e08401516108f36102208501826107b4565b50610100840151838203601f19016103208501526109118282610786565b9150506101208401516103408401526101408401516103608401526101608401516109486103808501826001600160a01b03169052565b506101808401516001600160a01b0381166103a0850152509392505050565b5f81518060208401855e5f93019283525090919050565b5f61099261098c8386610967565b84610967565b94935050505056fe6102a0604052348015610010575f80fd5b50604051614f81380380614f8183398101604081905261002f91610838565b805160208201516040830151606084015160808086015160a08701516001600160a01b0381169092529061006385856102da565b600161006f8482610a0f565b506001600160a01b0380871660a05260208501511660c0526001600160801b03851661012081905260808501516100a691906104ff565b6001600160801b03908116610140526101208501511661016052506001600160a01b039081166102205260c08084015182166101805283516001600160401b039081166101a05260a085015183166101c052604085015162ffffff1660e0908152606086015160020b61010090815286015184166101e0529094015190931661020052918501519091169250610152915050576040516308fa721160e41b815260040160405180910390fd5b60e0810151516001600160a01b031661017e57604051632711b74d60e11b815260040160405180910390fd5b6101608101516001600160a01b031615806101a557506101808101516001600160a01b0316155b156101c3576040516308fa721160e41b815260040160405180910390fd5b60c0818101516001600160a01b039081166102405260e0808401518051600280546020840151604085015160608601516080870151959098166001600160b81b031990931692909217600160a01b62ffffff928316021765ffffffffffff60b81b1916600160b81b9282169290920262ffffff60d01b191691909117600160d01b96821696909602959095176001600160e81b0316600160e81b95909216949094021790925560a08201516003559181015160045501516005805460ff191691151591909117905561010081015160069061029e9082610a0f565b506101208101516007556101408101516008556101608101516001600160a01b0390811661026052610180909101511661028052610b32565b50565b805f01516001600160401b03168160e001516001600160401b0316116103325760e0810151815160405163b834dcef60e01b81526001600160401b039283166004820152911660248201526044015b60405180910390fd5b8061012001516001600160801b03165f0361036057604051634f54eb2560e11b815260040160405180910390fd5b6298968062ffffff16816080015162ffffff16106103a757608081015160405163db75a46960e01b815262ffffff9091166004820152629896806024820152604401610329565b6060810151617fff60029190910b13806103cb5750600160020b816060015160020b125b15610404576060810151604051637466e7f360e11b815260029190910b600482015260016024820152617fff6044820152606401610329565b620f424062ffffff16816040015162ffffff16111561044c576040808201519051632eae35a760e01b815262ffffff9091166004820152620f42406024820152604401610329565b60c08101516001600160a01b03161580610473575060c08101516001600160a01b03166001145b8061048b575060c08101516001600160a01b03166002145b156104ba5760c0810151604051630864f00d60e01b81526001600160a01b039091166004820152602401610329565b60808101516104d3906001600160801b0384169061051d565b6001600160801b03165f036104fb57604051630324368b60e01b815260040160405180910390fd5b5050565b5f61050a838361051d565b6105149084610add565b90505b92915050565b5f6298968061053a62ffffff84166001600160801b038616610afc565b6105149190610b13565b634e487b7160e01b5f52604160045260245ffd5b60405161014081016001600160401b038111828210171561057b5761057b610544565b60405290565b60405161010081016001600160401b038111828210171561057b5761057b610544565b6040516101a081016001600160401b038111828210171561057b5761057b610544565b6001600160a01b03811681146102d7575f80fd5b80516105e6816105c7565b919050565b80516001600160801b03811681146105e6575f80fd5b80516001600160401b03811681146105e6575f80fd5b805162ffffff811681146105e6575f80fd5b8051600281900b81146105e6575f80fd5b5f610140828403121561064b575f80fd5b610653610558565b905061065e82610601565b815261066c602083016105db565b602082015261067d60408301610617565b604082015261068e60608301610629565b606082015261069f60808301610617565b60808201526106b060a083016105db565b60a08201526106c160c083016105db565b60c08201526106d260e08301610601565b60e08201526106e461010083016105db565b6101008201526106f761012083016105eb565b61012082015292915050565b5f82601f830112610712575f80fd5b8151602083015f806001600160401b0384111561073157610731610544565b50604051601f19601f85018116603f011681018181106001600160401b038211171561075f5761075f610544565b604052838152905080828401871015610776575f80fd5b8383602083015e5f602085830101528094505050505092915050565b805180151581146105e6575f80fd5b5f61010082840312156107b2575f80fd5b6107ba610581565b905081516107c7816105c7565b81526107d560208301610629565b60208201526107e660408301610617565b60408201526107f760608301610617565b606082015261080860808301610617565b608082015260a0828101519082015260c0808301519082015261082d60e08301610792565b60e082015292915050565b5f60208284031215610848575f80fd5b81516001600160401b0381111561085d575f80fd5b82016103a0818503121561086f575f80fd5b6108776105a4565b610880826105db565b815261088e602083016105eb565b60208201526108a0856040840161063a565b60408201526101808201516001600160401b038111156108be575f80fd5b6108ca86828501610703565b6060830152506108dd6101a083016105db565b60808201526108ef6101c083016105db565b60a08201526109016101e083016105db565b60c08201526109148561020084016107a1565b60e08201526103008201516001600160401b03811115610932575f80fd5b61093e86828501610703565b6101008301525061032082015161012082015261034082015161014082015261096a61036083016105db565b61016082015261097d61038083016105db565b610180820152949350505050565b600181811c9082168061099f57607f821691505b6020821081036109bd57634e487b7160e01b5f52602260045260245ffd5b50919050565b601f821115610a0a57805f5260205f20601f840160051c810160208510156109e85750805b601f840160051c820191505b81811015610a07575f81556001016109f4565b50505b505050565b81516001600160401b03811115610a2857610a28610544565b610a3c81610a36845461098b565b846109c3565b6020601f821160018114610a6e575f8315610a575750848201515b5f19600385901b1c1916600184901b178455610a07565b5f84815260208120601f198516915b82811015610a9d5787850151825560209485019460019092019101610a7d565b5084821015610aba57868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b634e487b7160e01b5f52601160045260245ffd5b6001600160801b03828116828216039081111561051757610517610ac9565b808202811582820484141761051757610517610ac9565b5f82610b2d57634e487b7160e01b5f52601260045260245ffd5b500490565b60805160a05160c05160e05161010051610120516101405161016051610180516101a0516101c0516101e05161020051610220516102405161026051610280516141a2610ddf5f395f8181610a8701526122d101525f8181610702015261226301525f81816107790152818161312c01528181613169015261340f01525f61073501525f81816109bb01528181610f2301528181610f5c015281816112d7015261131001525f818161058d01528181610fb901528181610ffb01528181611093015281816110ba01528181611342015281816113840152818161141c015261144301525f81816102d50152610d5c01525f8181610490015281816118700152818161198801528181611cc70152611d0001525f8181610812015281816121480152818161328a015261334d01525f81816105460152611e7801525f818161062b01528181610cfc01528181611f3301528181612f060152612f3f01525f818161034401528181610b5401528181610c0b0152610d1d01525f81816106bc01528181611f9601528181611fc7015281816120ce015261323b01525f81816104dc01526120a701525f8181610a54015281816113bf015281816113fa015281816119b901528181611ace01528181611dbd01528181611df701528181611ede01528181612ad501528181612b2701528181612b7a01528181612ba701528181612fe9015281816130190152818161304b01526130b701525f8181610aba01528181610b7f01528181610c2d01528181610d8901528181610e49015281816110360152818161107101528181611ebb01528181612ab201528181612b0201528181612b5701528181612bcc0152612fbd01525f81816109ee01528181610ae80152818161112d015281816112220152818161128b015281816116270152818161168e01526116f101526141a25ff3fe6080604052600436106102b9575f3560e01c8063791b98bc11610170578063b47b2fb1116100d1578063dc98354e11610087578063e5a6b10f11610062578063e5a6b10f14610a43578063f8ec691114610a76578063fc0c546a14610aa9575f80fd5b8063dc98354e14610a10578063e1b4af691461088a578063e2b8e1a214610a2f575f80fd5b8063c4e833ce116100b7578063c4e833ce146108a9578063d3decc68146109aa578063dc4c90d3146109dd575f80fd5b8063b47b2fb114610848578063b6a8b0fa1461088a575f80fd5b80639f063efc11610126578063a8c62e761161010c578063a8c62e76146107e4578063af7a40ca14610801578063b20881f814610834575f80fd5b80639f063efc1461064d578063a8b25c01146107cf575f80fd5b80638364d95f116101565780638364d95f1461076b5780638fd3ab801461079d5780639ce110d7146107b1575f80fd5b8063791b98bc146107245780637c12157414610757575f80fd5b8063531d35951161021a5780635d466045116101d05780636fe7e6eb116101b65780636fe7e6eb1461068c5780637164cf9b146106ab578063766608ad146106f1575f80fd5b80635d4660451461061a5780636c2bbe7e1461064d575f80fd5b8063570ca73511610200578063570ca7351461057c578063575e24b4146105af5780635a8d61fc146105f9575f80fd5b8063531d359514610535578063532cce1814610568575f80fd5b8063331f2f651161026f5780634216204411610255578063421620441461047f5780634b9bf62b146104cb5780634c2f239414610512575f80fd5b8063331f2f65146103b657806338f2e95c146103cc575f80fd5b806318160ddd1161029f57806318160ddd1461033357806321d0ee701461037e578063259982e51461037e575f80fd5b806306d9d915146102c45780630ddac7be14610314575f80fd5b366102c057005b5f80fd5b3480156102cf575f80fd5b506102f77f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020015b60405180910390f35b34801561031f575f80fd5b506009546102f7906001600160a01b031681565b34801561033e575f80fd5b506103667f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160801b03909116815260200161030b565b348015610389575f80fd5b5061039d6103983660046136b4565b610adc565b6040516001600160e01b0319909116815260200161030b565b3480156103c1575f80fd5b506103ca610b3f565b005b3480156103d7575f80fd5b5060028054600354600454600554610429946001600160a01b03851694600160a01b810490910b9362ffffff600160b81b8304811694600160d01b8404821694600160e81b9094049091169260ff1688565b604080516001600160a01b03909916895260029790970b602089015262ffffff9586169688019690965292841660608701529216608085015260a084019190915260c0830152151560e08201526101000161030b565b34801561048a575f80fd5b506104b27f000000000000000000000000000000000000000000000000000000000000000081565b60405167ffffffffffffffff909116815260200161030b565b3480156104d6575f80fd5b506104fe7f000000000000000000000000000000000000000000000000000000000000000081565b60405162ffffff909116815260200161030b565b34801561051d575f80fd5b5061052760075481565b60405190815260200161030b565b348015610540575f80fd5b506103667f000000000000000000000000000000000000000000000000000000000000000081565b348015610573575f80fd5b506103ca610f21565b348015610587575f80fd5b506102f77f000000000000000000000000000000000000000000000000000000000000000081565b3480156105ba575f80fd5b506105ce6105c936600461373b565b61111f565b604080516001600160e01b03199094168452602084019290925262ffffff169082015260600161030b565b348015610604575f80fd5b5061060d611189565b60405161030b91906137c3565b348015610625575f80fd5b506103667f000000000000000000000000000000000000000000000000000000000000000081565b348015610658575f80fd5b5061066c6106673660046137d5565b611215565b604080516001600160e01b0319909316835260208301919091520161030b565b348015610697575f80fd5b5061039d6106a636600461386e565b61127f565b3480156106b6575f80fd5b506106de7f000000000000000000000000000000000000000000000000000000000000000081565b60405160029190910b815260200161030b565b3480156106fc575f80fd5b506102f77f000000000000000000000000000000000000000000000000000000000000000081565b34801561072f575f80fd5b506102f77f000000000000000000000000000000000000000000000000000000000000000081565b348015610762575f80fd5b506103ca6112d5565b348015610776575f80fd5b507f00000000000000000000000000000000000000000000000000000000000000006102f7565b3480156107a8575f80fd5b506103ca61149c565b3480156107bc575f80fd5b505f546102f7906001600160a01b031681565b3480156107da575f80fd5b5061052760085481565b3480156107ef575f80fd5b506002546001600160a01b03166102f7565b34801561080c575f80fd5b506102f77f000000000000000000000000000000000000000000000000000000000000000081565b34801561083f575f80fd5b5061060d6115f2565b348015610853575f80fd5b506108676108623660046138c7565b61161a565b604080516001600160e01b03199093168352600f9190910b60208301520161030b565b348015610895575f80fd5b5061039d6108a4366004613948565b611682565b3480156108b4575f80fd5b5061099d604080516101c0810182525f80825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e08101829052610100810182905261012081018290526101408101829052610160810182905261018081018290526101a081019190915250604080516101c081018252600181525f60208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e08101829052610100810182905261012081018290526101408101829052610160810182905261018081018290526101a081019190915290565b60405161030b91906139a2565b3480156109b5575f80fd5b506104b27f000000000000000000000000000000000000000000000000000000000000000081565b3480156109e8575f80fd5b506102f77f000000000000000000000000000000000000000000000000000000000000000081565b348015610a1b575f80fd5b5061039d610a2a366004613ac3565b6116e5565b348015610a3a575f80fd5b5061060d611744565b348015610a4e575f80fd5b506102f77f000000000000000000000000000000000000000000000000000000000000000081565b348015610a81575f80fd5b506102f77f000000000000000000000000000000000000000000000000000000000000000081565b348015610ab4575f80fd5b506102f77f000000000000000000000000000000000000000000000000000000000000000081565b5f336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614610b265760405163570c108560e11b815260040160405180910390fd5b610b338686868686611751565b90505b95945050505050565b6040516370a0823160e01b81523060048201527f00000000000000000000000000000000000000000000000000000000000000006001600160801b0316907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa158015610bcc573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bf09190613b0a565b1015610ccd576040516370a0823160e01b81523060048201527f0000000000000000000000000000000000000000000000000000000000000000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa158015610c7a573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c9e9190613b0a565b604051631ad2e45b60e21b81526001600160801b03909216600483015260248201526044015b60405180910390fd5b5f546001600160a01b031615610cf657604051635918f72f60e01b815260040160405180910390fd5b5f610d417f00000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000000613b35565b60405162ddc14160e21b81529091505f906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690630377050490610db8907f00000000000000000000000000000000000000000000000000000000000000009086906001908790600401613b86565b6020604051808303815f875af1158015610dd4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610df89190613c59565b9050610e038161176b565b610e14816366981dad60e01b611afd565b610e3c57604051632a94abb360e21b81526001600160a01b0382166004820152602401610cc4565b610e796001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016826001600160801b038516611b21565b5f805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b03831690811782556040805163331f2f6560e01b81529051919263331f2f659260048084019382900301818387803b158015610ed4575f80fd5b505af1158015610ee6573d5f803e3d5ffd5b50506040516001600160a01b03841692507f908f61aeb7021a31205d0ee52004a47cc3cc268e5a3c6489cf116dc4044cec6791505f90a25050565b7f000000000000000000000000000000000000000000000000000000000000000067ffffffffffffffff16610f54611bc6565b1015610fae577f0000000000000000000000000000000000000000000000000000000000000000610f83611bc6565b604051634740621760e11b815267ffffffffffffffff90921660048301526024820152604401610cc4565b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614611028576040516311ce341560e21b81523360048201526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000166024820152604401610cc4565b5f61105c6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001630611bff565b9050801561111c576110b86001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000167f000000000000000000000000000000000000000000000000000000000000000083611b21565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03167fdd9a81eb1b5197489c3ccfdab7b542e2e6dbdcf4120324e2688fab56fd23f98b8260405161111391815260200190565b60405180910390a25b50565b5f8080336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161461116b5760405163570c108560e11b815260040160405180910390fd5b6111788888888888611c8e565b925092509250955095509592505050565b6006805461119690613b54565b80601f01602080910402602001604051908101604052809291908181526020018280546111c290613b54565b801561120d5780601f106111e45761010080835404028352916020019161120d565b820191905f5260205f20905b8154815290600101906020018083116111f057829003601f168201915b505050505081565b5f80336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146112605760405163570c108560e11b815260040160405180910390fd5b61126f89898989898989611caa565b9150915097509795505050505050565b5f336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146112c95760405163570c108560e11b815260040160405180910390fd5b610b3685858585611751565b7f000000000000000000000000000000000000000000000000000000000000000067ffffffffffffffff16611308611bc6565b1015611337577f0000000000000000000000000000000000000000000000000000000000000000610f83611bc6565b336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146113b1576040516311ce341560e21b81523360048201526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000166024820152604401610cc4565b5f6113e56001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001630611bff565b9050801561111c576114416001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000167f000000000000000000000000000000000000000000000000000000000000000083611b21565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03167f053dfa7183794b221b03c5109dfb5a07b67d719cb3e98262d48bc66b2a132ad38260405161111391815260200190565b5f805f9054906101000a90046001600160a01b03166001600160a01b031663e1d97d1f6040518163ffffffff1660e01b8152600401606060405180830381865afa1580156114ec573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115109190613ca9565b905061151b81611cc5565b5f61152582611e43565b90505f61153182612043565b90505f61154860408051602081019091525f815290565b90506115548382612102565b816040516115a8919081516001600160a01b03908116825260208084015182169083015260408084015162ffffff169083015260608084015160020b90830152608092830151169181019190915260a00190565b60405190819003812084516001600160a01b03168252907f95cb306ff00e5e11a80ded9ef46c964545cdfb5c889f7f6a0711669d129f120f9060200160405180910390a250505050565b606060026040516020016116069190613d0e565b604051602081830303815290604052905090565b5f80336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146116655760405163570c108560e11b815260040160405180910390fd5b611673888888888888611caa565b91509150965096945050505050565b5f336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146116cc5760405163570c108560e11b815260040160405180910390fd5b6116da878787878787611751565b979650505050505050565b5f336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161461172f5760405163570c108560e11b815260040160405180910390fd5b61173a84848461233c565b90505b9392505050565b6001805461119690613b54565b5f604051630a85dc2960e01b815260040160405180910390fd5b306001600160a01b0316816001600160a01b0316633b6fd2cf6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156117b1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117d59190613c59565b6001600160a01b03161461186e57806001600160a01b0316633b6fd2cf6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561181f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906118439190613c59565b60405163a629a93160e01b81526001600160a01b039091166004820152306024820152604401610cc4565b7f000000000000000000000000000000000000000000000000000000000000000067ffffffffffffffff16816001600160a01b031663083c63236040518163ffffffff1660e01b8152600401602060405180830381865afa1580156118d5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906118f99190613d8c565b67ffffffffffffffff16106119b757806001600160a01b031663083c63236040518163ffffffff1660e01b8152600401602060405180830381865afa158015611944573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906119689190613d8c565b60405163120ff99f60e11b815267ffffffffffffffff91821660048201527f00000000000000000000000000000000000000000000000000000000000000009091166024820152604401610cc4565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316816001600160a01b031663e5a6b10f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a1d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a419190613c59565b6001600160a01b03161461111c57806001600160a01b031663e5a6b10f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a8b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611aaf9190613c59565b604051637abe145160e01b81526001600160a01b0391821660048201527f00000000000000000000000000000000000000000000000000000000000000009091166024820152604401610cc4565b5f611b0783612387565b8015611b185750611b1883836123b9565b90505b92915050565b5f6001600160a01b038416611b56575f805f8085875af1905080611b5157611b51835f633d2cec6f60e21b61243c565b611bc0565b60405163a9059cbb60e01b81526001600160a01b038416600482015282602482015260205f6044835f895af13d15601f3d1160015f511416171691505f81525f60208201525f60408201525080611bc057611bc08463a9059cbb60e01b633c9fd93960e21b61243c565b50505050565b5f61a4b14603611bfa5763a3b1b31d5f5260205f6004601c60645afa60203d141581151715611bf3575f80fd5b50505f5190565b504390565b5f6001600160a01b038316611c1f57506001600160a01b03811631611b1b565b6040516370a0823160e01b81526001600160a01b0383811660048301528416906370a0823190602401602060405180830381865afa158015611c63573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c879190613b0a565b9050611b1b565b5f805f604051630a85dc2960e01b815260040160405180910390fd5b5f80604051630a85dc2960e01b815260040160405180910390fd5b7f000000000000000000000000000000000000000000000000000000000000000067ffffffffffffffff16611cf8611bc6565b1015611d52577f0000000000000000000000000000000000000000000000000000000000000000611d27611bc6565b60405163a06fc0c960e01b815267ffffffffffffffff90921660048301526024820152604401610cc4565b60408101516001600160801b03811115611d8f57604051634defa31760e01b8152600481018290526001600160801b036024820152604401610cc4565b805f03611daf576040516310ef230360e11b815260040160405180910390fd5b80611de36001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001630611bff565b1015611e3f5780611e1d6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001630611bff565b604051632bcaebd360e01b815260048101929092526024820152604401610cc4565b5050565b6040805160a0810182525f808252602082018190529181018290526060810182905260808101919091525f611eab83604001517f00000000000000000000000000000000000000000000000000000000000000006001600160801b0316808218908211021890565b90505f611f046001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081167f00000000000000000000000000000000000000000000000000000000000000009091161090565b84519091505f90611f1590836124b4565b9050611f208161257b565b6001600160a01b03168452611f578184847f0000000000000000000000000000000000000000000000000000000000000000612612565b6001600160801b039081166040870181905291166020860152611f7a9084613b35565b6001600160801b03166060850152835161202c90611fbf611fba7f00000000000000000000000000000000000000000000000000000000000000006126fe565b61271f565b611feb611fba7f00000000000000000000000000000000000000000000000000000000000000006129d7565b85611ffa578760200151612000565b87604001515b6001600160801b03168661201857886040015161201e565b88602001515b6001600160801b03166129ef565b6001600160801b0316608085015250919392505050565b6040805160a0810182525f808252602082018190529181018290526060810182905260808101919091526040518060a00160405280612080612aa4565b6001600160a01b03168152602001612096612b49565b6001600160a01b0316815262ffffff7f00000000000000000000000000000000000000000000000000000000000000001660208201527f000000000000000000000000000000000000000000000000000000000000000060020b60408201525f60609091015292915050565b5f8061210d84612bee565b6009805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b038381169182179092556040516370a0823160e01b81527f000000000000000000000000000000000000000000000000000000000000000090921660048301529294509092505f91906370a0823190602401602060405180830381865afa15801561219c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906121c09190613b0a565b9050816001600160a01b03167f10a3ea410b95c442e649f7ccd65207c703b9ee72212e12242766d8248b3106a0826040516121fd91815260200190565b60405180910390a284516040517f80343289cb6913b1cf7c8e15b6bbee9b77681713e4af8663d65776cc989d54e19161223a918691908690613db3565b60405180910390a1845160405163097ae7f160e21b81526001600160a01b0391821660048201527f0000000000000000000000000000000000000000000000000000000000000000909116906325eb9fc4906024015f604051808303815f87803b1580156122a6575f80fd5b505af11580156122b8573d5f803e3d5ffd5b505060405163f0ec98d760e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016925063f0ec98d79150612308908690600401613e35565b5f604051808303815f87803b15801561231f575f80fd5b505af1158015612331573d5f803e3d5ffd5b505050505050505050565b5f6001600160a01b038416301461237757604051638cbcc02560e01b81526001600160a01b0385166004820152306024820152604401610cc4565b50636e4c1aa760e11b9392505050565b5f612399826301ffc9a760e01b6123b9565b8015611b1b57506123b2826001600160e01b03196123b9565b1592915050565b6040516001600160e01b0319821660248201525f90819060440160408051601f19818403018152919052602080820180516001600160e01b03166301ffc9a760e01b17815282519293505f9283928392909183918a617530fa92503d91505f519050828015612429575060208210155b80156116da575015159695505050505050565b6040516390bfb86560e01b8082526001600160a01b03851660048301526001600160e01b031984166024830152608060448301526020601f3d018190040260a0810160648401523d608484015290913d5f60a483013e60048260a4018201526001600160e01b031984168260c4018201528160e40181fd5b5f825f036124d85760405163d173d09f60e01b815260048101849052602401610cc4565b81156125405760a06124ee84600160c01b613ea5565b901c1561252d5761250383600160c01b613ea5565b6040516387ebe85d60e01b815260048101919091526001600160a01b036024820152604401610cc4565b611c87600160c01b600160601b85612c54565b60a083901c15612573576040516387ebe85d60e01b8152600481018490526001600160a01b036024820152604401610cc4565b505060601b90565b5f61258582612cf0565b90506401000276a36001600160a01b03821610806125bf575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038216115b1561260d57604051633393dca160e11b81526001600160a01b03821660048201526401000276a3602482015273fffd8963efd1fc6a506488495d951d5263988d266044820152606401610cc4565b919050565b5f805f8461263757612632866001600160801b0316600160c01b89612c54565b61264f565b61264f87876001600160801b0316600160c01b612c54565b9050836001600160801b03168111156126ed575f856126855761268088866001600160801b0316600160c01b612c54565b61269d565b61269d856001600160801b0316600160c01b8a612c54565b90506001600160801b038111156126e3576040517fff29cf0d00000000000000000000000000000000000000000000000000000000815260048101829052602401610cc4565b84935091506126f4565b8591508092505b5094509492505050565b5f81600281900b620d89e7198161271757612717613e91565b050292915050565b60020b5f60ff82901d80830118620d89e8811115612748576127486345c3193d60e11b84612e48565b7001fffcb933bd6fad37aa2d162d1a5940016001821602600160801b186002821615612784576ffff97272373d413259a46990580e213a0260801c5b60048216156127a3576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b60088216156127c2576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b60108216156127e1576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615612800576fff973b41fa98c081472e6896dfb254c00260801c5b604082161561281f576fff2ea16466c96a3843ec78b326b528610260801c5b608082161561283e576ffe5dee046a99a2a811c461f1969c30530260801c5b61010082161561285e576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b61020082161561287e576ff987a7253ac413176f2b074cf7815e540260801c5b61040082161561289e576ff3392b0822b70005940c7a398e4b70f30260801c5b6108008216156128be576fe7159475a2c29b7443b29c7fa6e889d90260801c5b6110008216156128de576fd097f3bdfd2022b8845ad8f792aa58250260801c5b6120008216156128fe576fa9f746462d870fdf8a65dc1f90e061e50260801c5b61400082161561291e576f70d869a156d2a1b890bb3df62baf32f70260801c5b61800082161561293e576f31be135f97d08fd981231505542fcfa60260801c5b6201000082161561295f576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b6202000082161561297f576e5d6af8dedb81196699c329225ee6040260801c5b6204000082161561299e576d2216e584f5fa1ea926041bedfe980260801c5b620800008216156129bb576b048a170391f7dc42444e8fa20260801c5b5f8413156129c7575f19045b63ffffffff0160201c9392505050565b5f81600281900b620d89e88161271757612717613e91565b5f836001600160a01b0316856001600160a01b03161115612a0e579293925b846001600160a01b0316866001600160a01b031611612a3957612a32858585612e57565b9050610b36565b836001600160a01b0316866001600160a01b03161015612a99575f612a5f878686612e57565b90505f612a6d878986612eb8565b9050806001600160801b0316826001600160801b031610612a8e5780612a90565b815b92505050610b36565b610b33858584612eb8565b5f612afb6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081167f00000000000000000000000000000000000000000000000000000000000000009091161090565b612b2457507f000000000000000000000000000000000000000000000000000000000000000090565b507f000000000000000000000000000000000000000000000000000000000000000090565b5f612ba06001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081167f00000000000000000000000000000000000000000000000000000000000000009091161090565b612bc957507f000000000000000000000000000000000000000000000000000000000000000090565b507f000000000000000000000000000000000000000000000000000000000000000090565b6040805160a0810182525f808252602082018190529181018290526060810182905260808101829052908080612c2385612ef4565b915091505f612c328383612f7c565b9050612c3d81613103565b612c4786826131aa565b9097909650945050505050565b5f838302815f1985870982811083820303915050808411612c73575f80fd5b805f03612c855750829004905061173d565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f60018211612cfd575090565b816001600160801b8210612d165760809190911c9060401b5b680100000000000000008210612d315760409190911c9060201b5b6401000000008210612d485760209190911c9060101b5b620100008210612d5d5760109190911c9060081b5b6101008210612d715760089190911c9060041b5b60108210612d845760049190911c9060021b5b60048210612d905760011b5b600302600190811c90818581612da857612da8613e91565b048201901c90506001818581612dc057612dc0613e91565b048201901c90506001818581612dd857612dd8613e91565b048201901c90506001818581612df057612df0613e91565b048201901c90506001818581612e0857612e08613e91565b048201901c90506001818581612e2057612e20613e91565b048201901c9050612e3f818581612e3957612e39613e91565b04821190565b90039392505050565b815f528060020b60045260245ffd5b5f826001600160a01b0316846001600160a01b03161115612e76579192915b5f612e98856001600160a01b0316856001600160a01b0316600160601b612c54565b9050610b36612eb384838888036001600160a01b0316612c54565b613486565b5f826001600160a01b0316846001600160a01b03161115612ed7579192915b61173a612eb383600160601b8787036001600160a01b0316612c54565b5f8082602001516001600160801b03167f00000000000000000000000000000000000000000000000000000000000000006001600160801b031611612f3d578260200151612f5f565b7f00000000000000000000000000000000000000000000000000000000000000005b915082606001518360400151612f759190613ec4565b9050915091565b612fbb6040518060a001604052805f6001600160a01b031681526020015f6001600160a01b031681526020015f81526020015f81526020015f81525090565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b038082167f000000000000000000000000000000000000000000000000000000000000000090911610806130175781613039565b7f00000000000000000000000000000000000000000000000000000000000000005b6001600160a01b031683528061306f577f0000000000000000000000000000000000000000000000000000000000000000613071565b815b6001600160a01b031660208401528061308a578461308c565b835b6001600160801b03166040840152806130a557836130a7565b845b6001600160801b031660608401527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316156130ea575f6130ec565b835b6001600160801b0316608084015250909392505050565b80516001600160a01b0316156131515760408101518151613151916001600160a01b03909116907f0000000000000000000000000000000000000000000000000000000000000000906134a7565b60208101516001600160a01b03161561111c5761111c7f0000000000000000000000000000000000000000000000000000000000000000826060015183602001516001600160a01b03166134a79092919063ffffffff16565b6040805160a0810182525f8082526020808301829052828401829052606083018290526080830182905283518281529081019093529091819081613204565b6131f1613617565b8152602001906001900390816131e95790505b5090505f604051806101600160405280865f01516001600160a01b0316815260200186602001516001600160a01b031681526020017f000000000000000000000000000000000000000000000000000000000000000060020b8152602001875f01516001600160a01b0316815260200186604001518152602001866060015181526020017f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602001600680546132c490613b54565b80601f01602080910402602001604051908101604052809291908181526020018280546132f090613b54565b801561333b5780601f106133125761010080835404028352916020019161333b565b820191905f5260205f20905b81548152906001019060200180831161331e57829003601f168201915b50505091835250506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081166020808401919091526040808401879052805161010081018252600280548086168352600160a01b810490910b9382019390935262ffffff600160b81b8404811682840152600160d01b84048116606083810191909152600160e81b9094041660808083019190915260035460a08301526004805460c084015260055460ff16151560e084015293909501529289015192516320799a1160e21b81529394507f0000000000000000000000000000000000000000000000000000000000000000909116926381e66844929161344591869101613fc7565b60c06040518083038185885af1158015613461573d5f803e3d5ffd5b50505050506040513d601f19601f82011682018060405250810190612c4791906140cd565b806001600160801b038116811461260d5761260d6393dafdf160e01b61355a565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b1790526134f88482613562565b611bc057604080516001600160a01b03851660248201525f6044808301919091528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b1790526135509085906135ab565b611bc084826135ab565b805f5260045ffd5b5f805f8060205f8651602088015f8a5af192503d91505f5190508280156135a15750811561359357806001146135a1565b5f866001600160a01b03163b115b9695505050505050565b5f8060205f8451602086015f885af1806135ca576040513d5f823e3d81fd5b50505f513d915081156135e15780600114156135ee565b6001600160a01b0384163b155b15611bc057604051635274afe760e01b81526001600160a01b0385166004820152602401610cc4565b60405180604001604052806002906020820280368337509192915050565b6001600160a01b038116811461111c575f80fd5b5f60a08284031215613659575f80fd5b50919050565b5f60808284031215613659575f80fd5b5f8083601f84011261367f575f80fd5b50813567ffffffffffffffff811115613696575f80fd5b6020830191508360208285010111156136ad575f80fd5b9250929050565b5f805f805f61016086880312156136c9575f80fd5b85356136d481613635565b94506136e38760208801613649565b93506136f28760c0880161365f565b925061014086013567ffffffffffffffff81111561370e575f80fd5b61371a8882890161366f565b969995985093965092949392505050565b5f60608284031215613659575f80fd5b5f805f805f6101408688031215613750575f80fd5b853561375b81613635565b945061376a8760208801613649565b93506137798760c0880161372b565b925061012086013567ffffffffffffffff81111561370e575f80fd5b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f611b186020830184613795565b5f805f805f805f6101a0888a0312156137ec575f80fd5b87356137f781613635565b96506138068960208a01613649565b95506138158960c08a0161365f565b94506101408801359350610160880135925061018088013567ffffffffffffffff811115613841575f80fd5b61384d8a828b0161366f565b989b979a50959850939692959293505050565b8060020b811461111c575f80fd5b5f805f806101008587031215613882575f80fd5b843561388d81613635565b935061389c8660208701613649565b925060c08501356138ac81613635565b915060e08501356138bc81613860565b939692955090935050565b5f805f805f8061016087890312156138dd575f80fd5b86356138e881613635565b95506138f78860208901613649565b94506139068860c0890161372b565b9350610120870135925061014087013567ffffffffffffffff81111561392a575f80fd5b61393689828a0161366f565b979a9699509497509295939492505050565b5f805f805f80610120878903121561395e575f80fd5b863561396981613635565b95506139788860208901613649565b945060c0870135935060e0870135925061010087013567ffffffffffffffff81111561392a575f80fd5b8151151581526101c0810160208301516139c0602084018215159052565b5060408301516139d4604084018215159052565b5060608301516139e8606084018215159052565b5060808301516139fc608084018215159052565b5060a0830151613a1060a084018215159052565b5060c0830151613a2460c084018215159052565b5060e0830151613a3860e084018215159052565b50610100830151613a4e61010084018215159052565b50610120830151613a6461012084018215159052565b50610140830151613a7a61014084018215159052565b50610160830151613a9061016084018215159052565b50610180830151613aa661018084018215159052565b506101a0830151613abc6101a084018215159052565b5092915050565b5f805f60e08486031215613ad5575f80fd5b8335613ae081613635565b9250613aef8560208601613649565b915060c0840135613aff81613635565b809150509250925092565b5f60208284031215613b1a575f80fd5b5051919050565b634e487b7160e01b5f52601160045260245ffd5b6001600160801b038281168282160390811115611b1b57611b1b613b21565b600181811c90821680613b6857607f821691505b60208210810361365957634e487b7160e01b5f52602260045260245ffd5b6001600160a01b03851681526001600160801b0384166020820152608060408201525f8084545f8160011c90506001821680613bc357607f821691505b602082108103613be157634e487b7160e01b5f52602260045260245ffd5b6080860182905260a08601818015613c005760018114613c1657613c42565b60ff198516825283151560051b82019550613c42565b5f8a8152602090205f5b85811015613c3c57815484820152600190910190602001613c20565b83019650505b505050505060609290920192909252949350505050565b5f60208284031215613c69575f80fd5b815161173d81613635565b60405160a0810167ffffffffffffffff81118282101715613ca357634e487b7160e01b5f52604160045260245ffd5b60405290565b5f6060828403128015613cba575f80fd5b506040516060810167ffffffffffffffff81118282101715613cea57634e487b7160e01b5f52604160045260245ffd5b60409081528351825260208085015190830152928301519281019290925250919050565b81546001600160a01b038116825261010082019060a081901c60020b602084015260b881901c62ffffff16604084015260d081901c62ffffff16606084015260e881901c608084015250600183015460a0830152600283015460c0830152600383015460ff1680151560e0840152613abc565b805161260d81613635565b5f60208284031215613d9c575f80fd5b815167ffffffffffffffff8116811461173d575f80fd5b60e08101613e0f82866001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b6001600160a01b03841660a08301526001600160a01b03831660c0830152949350505050565b60a08101611b1b82846001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b634e487b7160e01b5f52601260045260245ffd5b5f82613ebf57634e487b7160e01b5f52601260045260245ffd5b500490565b6001600160801b038181168382160190811115611b1b57611b1b613b21565b5f8151808452602084019350602083015f5b82811015613f3a578151865f5b6002811015613f21578251825260209283019290910190600101613f02565b5050506040959095019460209190910190600101613ef5565b5093949350505050565b6001600160a01b038151168252602081015160020b602083015262ffffff60408201511660408301526060810151613f83606084018262ffffff169052565b506080810151613f9a608084018262ffffff169052565b5060a081015160a083015260c081015160c083015260e0810151613fc260e084018215159052565b505050565b60208152613fe16020820183516001600160a01b03169052565b5f6020830151613ffc60408401826001600160a01b03169052565b506040830151614011606084018260020b9052565b5060608301516001600160a01b038116608084015250608083015160a083015260a083015160c083015260c083015161405560e08401826001600160a01b03169052565b5060e0830151610240610100840152614072610260840182613795565b90506101008401516140906101208501826001600160a01b03169052565b50610120840151838203601f19016101408501526140ae8282613ee3565b9150506101408401516140c5610160850182613f44565b509392505050565b5f8082840360c08112156140df575f80fd5b60a08112156140ec575f80fd5b506140f5613c74565b835161410081613635565b8152602084015161411081613635565b6020820152604084015162ffffff8116811461412a575f80fd5b6040820152606084015161413d81613860565b6060820152608084015161415081613635565b6080820152915061416360a08401613d81565b9050925092905056fea26469706673582212208fff85f5dcc32a25b94e00f91c4aa4553f077fb7e435d4b418400833caad79b964736f6c634300081a0033a264697066735822122009e325916b7f849d2a4cb4485cc5293d89f0d8ea96a3c1d84aa6478aacf76c7564736f6c634300081a0033000000000000000000000000f198a9720aeed31d5cbe0b8b8ec75e16aaef676b0000000000000000000000001f9840000000000000000000000000000000000400000000000000000000000000000008412db3394c91a5cbd01635c6d140637c0000000000000000000000008c03ed1688d0e44ae1ffb6354bff0646e0d10e45
Deployed Bytecode
0x608060405234801561000f575f80fd5b506004361061006f575f3560e01c80638364d95f1161004d5780638364d95f146100f0578063d5f3948814610116578063dc4c90d31461013d575f80fd5b806303770504146100735780633e8e4ee8146100a2578063688e6956146100c9575b5f80fd5b61008661008136600461066a565b610164565b6040516001600160a01b03909116815260200160405180910390f35b6100867f00000000000000000000000000000008412db3394c91a5cbd01635c6d140637c81565b6100867f0000000000000000000000008c03ed1688d0e44ae1ffb6354bff0646e0d10e4581565b7f000000000000000000000000f198a9720aeed31d5cbe0b8b8ec75e16aaef676b610086565b6100867f000000000000000000000000737e601ea1c16636139b37822a38790f883b917581565b6100867f0000000000000000000000001f9840000000000000000000000000000000000481565b5f336001600160a01b037f00000000000000000000000000000008412db3394c91a5cbd01635c6d140637c16146101ae57604051635c427cd960e01b815260040160405180910390fd5b6001600160801b038511156101d657604051637f34059360e11b815260040160405180910390fd5b6101e386868686866101ed565b9695505050505050565b5f806101f98585610260565b9050610207878785846103ed565b6040516001600160801b03881681529092506001600160a01b0380891691908416907f34d4b985fe12d4cd11d805af2817afb1a621368fd44b86f2a6d21cd238348bfe9060200160405180910390a35095945050505050565b61032e6040805161022081019091525f60e08201818152610100830182905261012083018290526101408301829052610160830182905261018083018290526101a083018290526101c083018290526101e083018290526102008301919091528190815260408051610100810182525f8082526020828101829052928201819052606082018190526080820181905260a0820181905260c0820181905260e08201529101908152606060208201819052604082018190525f9082018190526080820181905260a09091015290565b5f808080808080610341898b018b6108df565b6001600160a01b037f0000000000000000000000008c03ed1688d0e44ae1ffb6354bff0646e0d10e45811660a08901526020880151979e50959c50939a5091985096509450925016156103a757604051637f34059360e11b815260040160405180910390fd5b6040805160e081018252978852602088019690965294860193909352606085019190915260808401526001600160a01b0390811660a08401521660c08201529392505050565b5f806040518060800160405280876001600160a01b03168152602001866001600160801b03168152602001858152602001846080015181525090505f61044f82855f01518660200151876040015188606001518960a001518a60c001516104dc565b6040516331fa95d960e01b81526001600160a01b038083166004830152600160248301529192507f000000000000000000000000f198a9720aeed31d5cbe0b8b8ec75e16aaef676b909116906331fa95d9906044015f604051808303815f87803b1580156104bb575f80fd5b505af11580156104cd573d5f803e3d5ffd5b50929998505050505050505050565b6040808801516060808a015183516101a0810185528b516001600160a01b0390811682526020808e01516001600160801b0316908301528186018c90529281018890525f608082018190527f0000000000000000000000001f98400000000000000000000000000000000004841660a08301527f000000000000000000000000f198a9720aeed31d5cbe0b8b8ec75e16aaef676b841660c083015260e082018b905261010082018a9052610120820183905261014082018590528784166101608301528684166101808301529451631de8802960e31b81529192909185917f000000000000000000000000737e601ea1c16636139b37822a38790f883b9175169063ef440148906105f39087908690600401610bf4565b6020604051808303815f875af115801561060f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106339190610d27565b9c9b505050505050505050505050565b6001600160a01b0381168114610657575f80fd5b50565b803561066581610643565b919050565b5f805f805f6080868803121561067e575f80fd5b853561068981610643565b945060208601359350604086013567ffffffffffffffff8111156106ab575f80fd5b8601601f810188136106bb575f80fd5b803567ffffffffffffffff8111156106d1575f80fd5b8860208284010111156106e2575f80fd5b959894975060200195606001359392505050565b634e487b7160e01b5f52604160045260245ffd5b604051610100810167ffffffffffffffff8111828210171561072e5761072e6106f6565b60405290565b604051610140810167ffffffffffffffff8111828210171561072e5761072e6106f6565b803567ffffffffffffffff81168114610665575f80fd5b803562ffffff81168114610665575f80fd5b8035600281900b8114610665575f80fd5b80356001600160801b0381168114610665575f80fd5b80358015158114610665575f80fd5b5f61010082840312156107c8575f80fd5b6107d061070a565b905081356107dd81610643565b81526107eb60208301610781565b60208201526107fc6040830161076f565b604082015261080d6060830161076f565b606082015261081e6080830161076f565b608082015260a0828101359082015260c0808301359082015261084360e083016107a8565b60e082015292915050565b5f82601f83011261085d575f80fd5b8135602083015f8067ffffffffffffffff84111561087d5761087d6106f6565b50604051601f19601f85018116603f0116810181811067ffffffffffffffff821117156108ac576108ac6106f6565b6040528381529050808284018710156108c3575f80fd5b838360208301375f602085830101528094505050505092915050565b5f805f805f805f8789036102e08112156108f7575f80fd5b610140811215610905575f80fd5b5061090e610734565b61091789610758565b815261092560208a0161065a565b602082015261093660408a0161076f565b604082015261094760608a01610781565b606082015261095860808a0161076f565b608082015261096960a08a0161065a565b60a082015261097a60c08a0161065a565b60c082015261098b60e08a01610758565b60e082015261099d6101008a0161065a565b6101008201526109b06101208a01610792565b61012082015296506109c6896101408a016107b7565b955061024088013567ffffffffffffffff8111156109e2575f80fd5b6109ee8a828b0161084e565b95505061026088013567ffffffffffffffff811115610a0b575f80fd5b610a178a828b0161084e565b9450506102808801359250610a2f6102a0890161065a565b9150610a3e6102c0890161065a565b905092959891949750929550565b805167ffffffffffffffff1682526020810151610a7460208401826001600160a01b03169052565b506040810151610a8b604084018262ffffff169052565b506060810151610aa0606084018260020b9052565b506080810151610ab7608084018262ffffff169052565b5060a0810151610ad260a08401826001600160a01b03169052565b5060c0810151610aed60c08401826001600160a01b03169052565b5060e0810151610b0960e084018267ffffffffffffffff169052565b50610100810151610b266101008401826001600160a01b03169052565b50610120810151610b436101208401826001600160801b03169052565b505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b6001600160a01b038151168252602081015160020b602083015262ffffff60408201511660408301526060810151610bb5606084018262ffffff169052565b506080810151610bcc608084018262ffffff169052565b5060a081015160a083015260c081015160c083015260e0810151610b4360e084018215159052565b82815260406020820152610c146040820183516001600160a01b03169052565b5f6020830151610c2f60608401826001600160801b03169052565b506040830151610c426080840182610a4c565b5060608301516103a06101c0840152610c5f6103e0840182610b48565b90506080840151610c7c6101e08501826001600160a01b03169052565b5060a08401516001600160a01b0390811661020085015260c08501511661022084015260e0840151610cb2610240850182610b76565b50610100840151838203603f1901610340850152610cd08282610b48565b915050610120840151610360840152610140840151610380840152610160840151610d076103a08501826001600160a01b03169052565b506101808401516001600160a01b0381166103c085015250949350505050565b5f60208284031215610d37575f80fd5b8151610d4281610643565b939250505056fea26469706673582212208f16ddd1301fde714c108553bd2f204f58e886d24767fadfa09ee969a50cb85364736f6c634300081a0033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
000000000000000000000000f198a9720aeed31d5cbe0b8b8ec75e16aaef676b0000000000000000000000001f9840000000000000000000000000000000000400000000000000000000000000000008412db3394c91a5cbd01635c6d140637c0000000000000000000000008c03ed1688d0e44ae1ffb6354bff0646e0d10e45
-----Decoded View---------------
Arg [0] : _orderBookFactory (address): 0xf198A9720AEeD31D5cbE0B8b8eC75e16AAeF676B
Arg [1] : _poolManager (address): 0x1F98400000000000000000000000000000000004
Arg [2] : _liquidityLauncher (address): 0x00000008412db3394C91A5CbD01635c6d140637C
Arg [3] : _ccaFactory (address): 0x8C03ED1688d0E44Ae1Ffb6354BfF0646e0d10e45
-----Encoded View---------------
4 Constructor Arguments found :
Arg [0] : 000000000000000000000000f198a9720aeed31d5cbe0b8b8ec75e16aaef676b
Arg [1] : 0000000000000000000000001f98400000000000000000000000000000000004
Arg [2] : 00000000000000000000000000000008412db3394c91a5cbd01635c6d140637c
Arg [3] : 0000000000000000000000008c03ed1688d0e44ae1ffb6354bff0646e0d10e45
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in ETH
0
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
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.